From 4c34cb5d5249291432670f86f3f48b15ea8ea7e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 21:21:51 +0000 Subject: [PATCH 01/30] =?UTF-8?q?Add=20a=20provider-neutral=20diary=20seam?= =?UTF-8?q?=20and=20the=20=C2=AB=D0=A1=D0=B5=D1=82=D0=B5=D0=B2=D0=BE=D0=B9?= =?UTF-8?q?=20=D0=B3=D0=BE=D1=80=D0=BE=D0=B4=C2=BB=20provider=20core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The diary talked to one upstream, Петербург's, through modules that named its classes directly. This adds the shape a second provider can meet, and the second provider's core, without changing what Петербург does. - app/providers/diary/ holds what every provider shares: the models, the error family, the DiaryProvider/DiaryConnection protocols and the SignInRequest they take, the HTTP client whose cookie jar keeps nothing so two families' sessions never meet, and the registry that maps a stored key to an implementation and reads a class's binding in one place. - app/providers/petersburg keeps every public name as a re-export of the very objects now defined in diary/, so PetersburgError is DiaryError and nothing that imports the old names breaks. Its behaviour is unchanged; a new petersburg/provider.py wraps the existing client and mapper behind the contract. The dead DiaryAccount is gone (#138). - app/providers/netschool/ reads «Сетевой город»: a region allow-list that is the only source of an origin (so no client input becomes a URL), the password sign-in every open client performs (windows-1251 salted md5), the weekly diary mapped onto the shared models with homework as assignment type 3, keep-alive, a working logout, and a credential that holds the session but never the password. Tested against a mock transport and hand-written payloads: a sealed session carries no password, a wrong password is BadCredentials, a Госуслуги-only region refuses before any password is sent, a blocked address is its own error, the token never rides in a URL, and two families' cookies never meet. Nothing has been tried against a live server (#121, #135). This is the seam and the core only; the service dispatch, the schema, the bot binding and the keep-alive follow. Part of #139. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/providers/diary/__init__.py | 22 + server/app/providers/diary/base.py | 98 ++++ server/app/providers/diary/errors.py | 112 +++++ server/app/providers/diary/http.py | 98 ++++ server/app/providers/diary/models.py | 139 ++++++ server/app/providers/diary/registry.py | 89 ++++ server/app/providers/netschool/__init__.py | 15 + server/app/providers/netschool/client.py | 463 ++++++++++++++++++ server/app/providers/netschool/mapper.py | 297 +++++++++++ server/app/providers/netschool/provider.py | 237 +++++++++ server/app/providers/netschool/regions.py | 90 ++++ server/app/providers/petersburg/exceptions.py | 74 +-- server/app/providers/petersburg/models.py | 165 ++----- server/app/providers/petersburg/provider.py | 98 ++++ server/tests/test_netschool_client.py | 212 ++++++++ server/tests/test_netschool_mapper.py | 125 +++++ 16 files changed, 2149 insertions(+), 185 deletions(-) create mode 100644 server/app/providers/diary/__init__.py create mode 100644 server/app/providers/diary/base.py create mode 100644 server/app/providers/diary/errors.py create mode 100644 server/app/providers/diary/http.py create mode 100644 server/app/providers/diary/models.py create mode 100644 server/app/providers/diary/registry.py create mode 100644 server/app/providers/netschool/__init__.py create mode 100644 server/app/providers/netschool/client.py create mode 100644 server/app/providers/netschool/mapper.py create mode 100644 server/app/providers/netschool/provider.py create mode 100644 server/app/providers/netschool/regions.py create mode 100644 server/app/providers/petersburg/provider.py create mode 100644 server/tests/test_netschool_client.py create mode 100644 server/tests/test_netschool_mapper.py diff --git a/server/app/providers/diary/__init__.py b/server/app/providers/diary/__init__.py new file mode 100644 index 00000000..70f1bd1d --- /dev/null +++ b/server/app/providers/diary/__init__.py @@ -0,0 +1,22 @@ +"""The electronic diary, as a shape any provider can meet. + +One diary is Petersburg's (`app.providers.petersburg`) and one is «Сетевой +город» (`app.providers.netschool`); more may follow. What they share lives +here so that the service, the routes and the bot depend on the shape rather +than on either upstream: + +- :mod:`app.providers.diary.models` — the models every provider returns; +- :mod:`app.providers.diary.errors` — the failures every provider raises, each + one a different answer at the API edge; +- :mod:`app.providers.diary.base` — the :class:`DiaryProvider` and + :class:`DiaryConnection` protocols, and the :class:`SignInRequest` they take; +- :mod:`app.providers.diary.http` — the shared HTTP client, whose cookie jar + keeps nothing so two families' sessions can never meet; +- :mod:`app.providers.diary.registry` — the map from a stored provider key to + an implementation, and :func:`binding`, the one place that reads a class's + diary binding. + +Petersburg pre-dates this package and keeps every public name it had, as a +re-export of the very objects defined here — so no import anywhere breaks and +`isinstance` still holds across the two spellings. +""" diff --git a/server/app/providers/diary/base.py b/server/app/providers/diary/base.py new file mode 100644 index 00000000..8a56440d --- /dev/null +++ b/server/app/providers/diary/base.py @@ -0,0 +1,98 @@ +"""The shape a diary provider meets, and the request that signs one in. + +Two protocols and one dataclass. `services/diary.DiaryService` builds a +:class:`DiaryConnection` from the provider named on the session row and calls +it; it never knows which upstream is behind it. A provider raises only the +:mod:`app.providers.diary.errors` family from these methods — never a +``ValueError`` or a ``KeyError``, which would reach the API edge as a 500. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date as Date +from typing import Protocol, runtime_checkable + +from app.providers.diary.models import ( + AcademicPeriod, + AttendanceEvent, + DiaryLesson, + HomeworkItem, + Mark, + Student, + Subject, + Teacher, +) + + +@dataclass(frozen=True) +class SignInRequest: + """What a family types, plus which diary and where. + + ``region`` and ``school_id`` are how a provider that serves many regional + servers, such as «Сетевой город», knows which one to talk to. Petersburg + ignores both. ``password`` is ``repr=False`` so it never lands in a log + line or a traceback that formats the request. + """ + + login: str + password: str = field(repr=False) + region: str | None = None + school_id: int | None = None + + +@runtime_checkable +class DiaryConnection(Protocol): + """One signed-in session's reads. + + ``credential`` is the current serialised upstream session; the service + re-seals it whenever it changes, so a token the upstream rotates mid-call + is kept. Every method raises only a :mod:`app.providers.diary.errors` + subclass. + """ + + credential: str + + async def students(self) -> list[Student]: ... + async def periods(self, group_id: int) -> list[AcademicPeriod]: ... + async def subjects(self, group_id: int, period_id: int) -> list[Subject]: ... + async def teachers(self, education_id: int) -> list[Teacher]: ... + async def schedule( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[DiaryLesson]: ... + async def homework( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[HomeworkItem]: ... + async def marks( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[Mark]: ... + async def attendance(self, education_id: int) -> list[AttendanceEvent]: ... + + async def keep_alive(self) -> None: + """Reset the upstream's idle timer. A no-op where none is needed.""" + + async def close(self) -> None: + """Tell the upstream we are done, best effort. A no-op where it has no logout.""" + + def today(self) -> Date: + """The date it is in the diary's own zone.""" + + +@runtime_checkable +class DiaryProvider(Protocol): + """One diary platform. + + ``key`` is stored in ``classes.diary_provider`` and ``diary_sessions.provider``. + ``title`` and ``genitive`` are what the bot and the web form print + («Сетевой город» / «Сетевого города»). + """ + + key: str + title: str + genitive: str + + async def sign_in(self, request: SignInRequest) -> str: + """Sign in and return the serialised credential, which the caller seals.""" + + def open(self, credential: str) -> DiaryConnection: + """A connection for a stored credential.""" diff --git a/server/app/providers/diary/errors.py b/server/app/providers/diary/errors.py new file mode 100644 index 00000000..3df0cee8 --- /dev/null +++ b/server/app/providers/diary/errors.py @@ -0,0 +1,112 @@ +"""What can go wrong with a diary, named so a route can answer it. + +An upstream speaks HTTP and sometimes speaks HTML at us; the rest of the +application should not have to tell "wrong password" from "session over" from +"they are down" from "they changed the response" from "they will not talk to +our address". Each needs a different answer at the API edge, so each is a type. + +`api/diary._guard` maps this family to a status code; anything outside it is a +500. `app.providers.petersburg` re-exports :class:`DiaryError` under its old +name :class:`PetersburgError`, so both spellings are the one class. +""" + +from __future__ import annotations + + +class DiaryError(Exception): + """Base for everything a diary provider raises.""" + + #: What the client is told. Deliberately short and Russian - these reach a + #: phone screen, not a log reader. + message = "Электронный дневник недоступен" + + def __init__(self, message: str | None = None) -> None: + super().__init__(message or self.message) + self.message = message or self.message + + +class BadCredentials(DiaryError): + """The login or the password is wrong. Nothing to retry.""" + + message = "Неверный логин или пароль" + + +class PasswordExpired(BadCredentials): + """The account's own password has expired upstream. + + A :class:`BadCredentials`, because there is nothing this end can retry, but + with its own message: retyping the same password will not help, and the fix + is on the region's own site. Kept apart so the web form can say which of + the two it is rather than «неверный пароль» over a password that was right + until last week. + """ + + message = "Пароль в дневнике устарел — смените его на сайте региона, потом войдите снова" + + +class SessionExpired(DiaryError): + """The stored session is no longer accepted. + + Distinct from :class:`BadCredentials` because the answer is different: the + person has not changed their password, they have simply been away long + enough. The client turns this into «войдите снова», not «вы ошиблись». + """ + + message = "Сессия дневника истекла — войдите заново" + + +class UpstreamUnavailable(DiaryError): + """A timeout, a connection failure, or a 5xx. + + The one failure that is safe to forgive on the sign-in path: nothing ever + looked at what was typed, so the ticket goes back and the throttle does not + count it. + """ + + message = "Электронный дневник не отвечает" + + +class AddressRefused(UpstreamUnavailable): + """The region's server will not talk to this deployment's address. + + A subclass of :class:`UpstreamUnavailable` — nothing looked at the + password, so the ticket is handed back and the throttle does not count it — + but a *permanent* refusal rather than a passing one: a Russian regional + server dropping a foreign or datacenter address, seen as a WAF block page, + a 403, or a connection reset. Told apart from a timeout because retrying + cannot help and the family must hear that it is not their password and not + worth trying again; the keep-alive trips a per-origin breaker on it rather + than pinging that origin's other sessions into the same wall. + """ + + message = ( + "Сайт дневника региона не пускает запросы с адреса нашего сервера — " + "дело не в пароле, и повтор не поможет. Сообщите администратору класса." + ) + + +class SignInUnsupported(DiaryError): + """The region takes only Госуслуги, so a login and password cannot get in. + + Raised only from the check made on the sign-in options *before* any + credential is sent (`_login_allowed`), so it is safe to hand the ticket + back and not count it: nothing looked at a password, and none was sent. + A different answer from :class:`BadCredentials`, which would send the family + to retype a password the region was never going to accept. + """ + + message = ( + "В этом регионе дневник впускает только через Госуслуги — " + "логин и пароль тут не подойдут" + ) + + +class UnexpectedResponse(DiaryError): + """A 200 whose body is not what the provider knows how to read. + + Its own type because it means *this code* needs changing, not the network + and not the user's password - and because it is the failure an undocumented + API produces when it is quietly redesigned. + """ + + message = "Электронный дневник ответил непонятно" diff --git a/server/app/providers/diary/http.py b/server/app/providers/diary/http.py new file mode 100644 index 00000000..6b5e490c --- /dev/null +++ b/server/app/providers/diary/http.py @@ -0,0 +1,98 @@ +"""The HTTP a diary provider is built on, shared so its traps are solved once. + +Two of them cost Petersburg real failures and are written down here so the +second provider does not pay them again: + +- **A shared client keeps a cookie jar, and that jar leaks between families.** + ``httpx`` stores every ``Set-Cookie`` on the *client* and merges it into the + next request. With one client per process, the first family's session cookie + rides out on the second family's call, and onto a sign-in that must carry + none. :class:`NoCookieJar` keeps nothing; the session travels per request. +- **Reading a cookie can raise past the error family.** + ``httpx.Cookies.get`` raises ``CookieConflict`` when one response sets a name + twice under different paths, the ordinary shape of a PHP app rotating a + scoped session. ``CookieConflict`` is not an ``httpx.HTTPError``, so a bare + ``response.cookies.get`` walks out of a provider as an exception the API edge + cannot map — a 500 on every call. :func:`session_cookie` is the only safe + reader: use it, never a bare ``.get``. + +``build_client`` also pins ``follow_redirects=False`` (a cross-origin redirect +would carry the session bearer to another host — the one way around a region +allow-list) and never turns TLS verification off. +""" + +from __future__ import annotations + +import http.cookiejar +import logging + +import httpx + +log = logging.getLogger(__name__) + +#: A browser's, because these upstreams are browsers' backends and have been +#: known to answer differently to anything else. +USER_AGENT = ( + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/124.0.0.0 Safari/537.36" +) + + +class NoCookieJar(http.cookiejar.CookieJar): + """A jar that keeps nothing it is handed. + + See the module docstring: the session is passed per request, so there is + nothing here worth remembering, and remembering it is how two families' + sessions meet. + """ + + def extract_cookies(self, response, request) -> None: # noqa: ARG002 + return None + + +def session_cookie(response: httpx.Response, name: str) -> str | None: + """The named cookie this answer carries, or ``None`` — CookieConflict-safe. + + **The only way to read a Set-Cookie in a provider.** A bare + ``response.cookies.get(name)`` raises ``CookieConflict`` when the answer + sets ``name`` twice under different paths, and that exception is not an + ``httpx.HTTPError``, so it escapes the provider's error family and becomes a + 500 on every call. The last value wins, which is what a browser sending the + next request to the same path would use; guessing is acceptable here and + refusing (a session that never refreshes and dies) is not. + """ + try: + return response.cookies.get(name) + except httpx.CookieConflict: + values = [ + cookie.value + for cookie in response.cookies.jar + if cookie.name == name and cookie.value + ] + log.warning("answer carried %d %s cookies; taking the last", len(values), name) + return values[-1] if values else None + + +def build_client( + *, + base_url: str = "", + timeout: httpx.Timeout, + limits: httpx.Limits | None = None, + headers: dict[str, str] | None = None, +) -> httpx.AsyncClient: + """A client that carries no cookies of its own, follows no redirect, and + verifies TLS. Every diary provider's pooled client is built here.""" + base_headers = {"user-agent": USER_AGENT, "accept": "application/json"} + if headers: + base_headers.update(headers) + return httpx.AsyncClient( + base_url=base_url, + timeout=timeout, + limits=limits or httpx.Limits(max_connections=10, max_keepalive_connections=5), + cookies=NoCookieJar(), + headers=base_headers, + follow_redirects=False, + # verify defaults to True and is never set False: a region that needs + # the Russian Trusted Root must carry its own CA bundle in regions.py, + # not have verification switched off for everyone. + ) diff --git a/server/app/providers/diary/models.py b/server/app/providers/diary/models.py new file mode 100644 index 00000000..14eb3b16 --- /dev/null +++ b/server/app/providers/diary/models.py @@ -0,0 +1,139 @@ +"""The diary as this project describes it, whichever provider answers. + +These are the models the rest of the application and the Android client see. +They are deliberately not any upstream's shapes: nothing here is called +``estimate_value_name`` or ``assignmentName``, nothing carries ``p_educations`` +or ``weekDays``, and no field exists only because an undocumented API happened +to send it. + +That distance is the point of the whole integration. When an upstream renames +a field, its ``mapper`` changes and these do not - so neither does the public +API, and neither does the phone. Two providers fill the same models from two +different upstreams, and every consumer reads one shape. +""" + +from __future__ import annotations + +from datetime import date as Date +from datetime import datetime +from datetime import time as Time +from enum import StrEnum + +from pydantic import BaseModel, Field + + +class MarkKind(StrEnum): + """What a mark in the register actually is. + + An upstream mixes several different things into one list - a grade, an + absence, a late arrival and a teacher's remark all arrive together and are + told apart by a code. Naming them here is what stops every consumer from + re-learning that code. + """ + + GRADE = "grade" + ABSENCE = "absence" + LATE = "late" + REMARK = "remark" + OTHER = "other" + + +class Student(BaseModel): + """One pupil the signed-in account may see.""" + + id: int + first_name: str + last_name: str + middle_name: str | None = None + school: str | None = None + class_name: str | None = None + #: Opaque upstream handles. Present because later calls need them and the + #: client passes them straight back; never parsed by the phone. + education_id: int + group_id: int | None = None + + @property + def full_name(self) -> str: + parts = [self.last_name, self.first_name, self.middle_name] + return " ".join(part for part in parts if part) + + +class AcademicPeriod(BaseModel): + """A quarter or a term, with the dates it covers.""" + + id: int + name: str + starts_on: Date | None = None + ends_on: Date | None = None + is_current: bool = False + + +class Subject(BaseModel): + id: int | None = None + name: str + + +class Teacher(BaseModel): + id: int | None = None + name: str + position: str | None = None + subjects: list[str] = Field(default_factory=list) + + +class Mark(BaseModel): + """One entry in the register. + + @property value what is written in the cell: «5», «Н», «!» - already + normalised, so a client never has to know which code means absent. + """ + + id: int | None = None + subject_id: int | None = None + subject_name: str + date: Date | None = None + value: str + kind: MarkKind = MarkKind.OTHER + #: The teacher's word for the occasion: «Контрольная работа», «Ответ на уроке». + reason: str | None = None + comment: str | None = None + + +class DiaryLesson(BaseModel): + """A lesson as the diary has it, with whatever was set on it.""" + + date: Date + number: int | None = None + subject: str + starts_at: Time | None = None + ends_at: Time | None = None + room: str | None = None + teacher: str | None = None + homework: str | None = None + topic: str | None = None + + +class HomeworkItem(BaseModel): + """Homework, addressed to the day it is due rather than the day it was set.""" + + id: int | None = None + due_date: Date + subject: str + text: str + teacher: str | None = None + + +class AttendanceEvent(BaseModel): + """A turnstile record. + + ``direction`` is ``in``, ``out`` or ``unknown``. The third one is not a + parsing failure to be tidied away: an upstream is undocumented, and a + spelling this code has not seen must not be rendered as the child leaving + the building. Anything reading this has three cases to answer, and the + third one is «дневник не сказал, куда». + + Not every provider has turnstiles: «Сетевой город» has none, so its + ``attendance`` is always empty. The model stays here for the one that does. + """ + + at: datetime + direction: str # "in" | "out" | "unknown" diff --git a/server/app/providers/diary/registry.py b/server/app/providers/diary/registry.py new file mode 100644 index 00000000..82365e72 --- /dev/null +++ b/server/app/providers/diary/registry.py @@ -0,0 +1,89 @@ +"""Which provider a stored key means, and what a class is bound to. + +`provider_for` is the one map from a key to an implementation, and it imports +the provider module lazily — so neither Petersburg's client nor «Сетевой +город»'s lands on the cold-start path of a request that does not use it, the +same care `main.py` takes. + +`binding` is the one place that reads a class's diary binding. `_bound` in the +bot, the main menu, the class card and the web form all call it, so that +"is this class bound, and to what" has a single answer and the web form never +imports aiogram to get it. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from app.providers.diary.base import DiaryProvider + +if TYPE_CHECKING: + from app.models import SchoolClass + +PETERSBURG = "petersburg" +NETSCHOOL = "netschool" +KEYS = (PETERSBURG, NETSCHOOL) + + +def provider_for(key: str | None) -> DiaryProvider | None: + """The provider for a key, or ``None`` for an unknown or absent one. + + A ``None`` (or unrecognised) key on a session row means the row pre-dates + the ``provider`` column, which is Petersburg — but the caller decides that, + not this function, which answers only about the key it was given. Lazy + imports keep a provider's HTTP module off the path until it is asked for. + """ + if key is None: + return None + if key == PETERSBURG: + from app.providers.petersburg.provider import PetersburgProvider + + return PetersburgProvider() + if key == NETSCHOOL: + from app.providers.netschool.provider import NetSchoolProvider + + return NetSchoolProvider() + return None + + +@dataclass(frozen=True) +class Binding: + """A class's diary binding, resolved and validated. + + For «Сетевой город» ``region`` names an allow-listed regional server and + ``school`` its id and name; for Petersburg both are ``None``. A class whose + stored region has since been dropped from the allow-list resolves to *no* + binding, so a diary that can no longer be reached stops being offered. + """ + + provider: DiaryProvider + region: str | None = None + school_id: int | None = None + school_name: str | None = None + + +def binding(school_class: SchoolClass) -> Binding | None: + """What ``school_class`` is bound to, or ``None`` if nothing usable. + + Reads only the class columns and the region allow-list — no aiogram, no + HTTP — so it is safe on the request path and in the web form. + """ + provider = provider_for(school_class.diary_provider) + if provider is None: + return None + if school_class.diary_provider == NETSCHOOL: + from app.providers.netschool import regions + + region = regions.get(school_class.diary_region) + # A class bound to a region since removed from the allow-list, or that + # never finished the school step, is not a usable binding. + if region is None or not region.password or school_class.diary_school_id is None: + return None + return Binding( + provider=provider, + region=region.key, + school_id=school_class.diary_school_id, + school_name=school_class.diary_school_name, + ) + return Binding(provider=provider) diff --git a/server/app/providers/netschool/__init__.py b/server/app/providers/netschool/__init__.py new file mode 100644 index 00000000..c7281d24 --- /dev/null +++ b/server/app/providers/netschool/__init__.py @@ -0,0 +1,15 @@ +"""«Сетевой город. Образование» (ИРТех NetSchool), behind one door. + +The one route set of `/webapi`, on a different regional server in each region. +Nothing outside this package knows a host, a cookie name or an `at` token; what +leaves here are the shared diary models and the shared diary errors. + +`regions` is the allow-list — the only origins this server ever contacts for +this provider, so a region key from a client, a class row or a stored +credential can never become an arbitrary URL. It imports nothing, so reading a +class's binding costs no HTTP module. +""" + +from app.providers.netschool.regions import Region, get, listed + +__all__ = ["Region", "get", "listed"] diff --git a/server/app/providers/netschool/client.py b/server/app/providers/netschool/client.py new file mode 100644 index 00000000..c7feb22c --- /dev/null +++ b/server/app/providers/netschool/client.py @@ -0,0 +1,463 @@ +"""The HTTP client for one «Сетевой город» session. + +One pooled `httpx.AsyncClient` per process, carrying no cookies of its own and +following no redirect (`app.providers.diary.http`), so two families' sessions +can never meet and the `at` bearer never rides a cross-origin redirect to +another host. Every call is to a region's own ``origin``, which comes only from +the allow-list (`app.providers.netschool.regions`). + +The session is a small dict, sealed by the service into ``upstream_token``: +``at`` (the bearer), the cookies to send, ``ver`` (for the SecurityWarning +acknowledgement), the school year id and its bounds, the assignment-type map, +and the login's ``timeOut`` so the keep-alive knows this server's idle window. +No password, and no hash of it, is ever in it. + +Rules the review nailed down, each with a reason: + +- ``at``, the cookies, ``pw`` and ``pw2`` travel only in a header or a form + body, never in a query string or a path — this process logs every request + URL, so a token in a URL is a token in the logs. The vendor's own + ``?token=`` keep-alive is banned for that reason. +- ``X-Requested-With: XMLHttpRequest`` on every call, so the ASP.NET side + answers JSON and 401 rather than an HTML redirect. +- A blocked address (403, a WAF page, a connection reset) is + :class:`AddressRefused`, never a wrong password and never an expired session. +- Sign-in *ends* at the accepted ``POST /webapi/login``. A failure before it + (logindata, getdata) is :class:`UpstreamUnavailable`/:class:`AddressRefused`/ + :class:`SignInUnsupported` — nothing looked at the password. A failure in the + bootstrap *after* it is :class:`SessionExpired`-shaped, because the password + was already judged. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import logging +from typing import Any + +import httpx + +from app.providers.diary.errors import ( + AddressRefused, + BadCredentials, + SessionExpired, + SignInUnsupported, + UnexpectedResponse, + UpstreamUnavailable, +) +from app.providers.diary.http import build_client, session_cookie +from app.providers.netschool.regions import Region + +log = logging.getLogger(__name__) + +CREDENTIAL_VERSION = 1 + +#: Cookies worth carrying between calls. NSSESSIONID is the session; ESRNSec is +#: the ESRN security module's, mandatory on the servers that set it (asurso.ru). +SESSION_COOKIES = ("NSSESSIONID", "ESRNSec") + +#: A short data timeout: a regional server that hangs must not hold a request +#: to the platform's ceiling. The keep-alive uses a shorter one of its own. +_TIMEOUT = httpx.Timeout(connect=5.0, read=15.0, write=10.0, pool=5.0) +_KEEPALIVE_TIMEOUT = httpx.Timeout(connect=3.0, read=5.0, write=5.0, pool=3.0) + +#: Markers of a "we do not serve this address" page, whatever its status. +_WAF_MARKERS = ("Доступ к сайту", "Request forbidden", "Access denied", "blocked") + +_client: httpx.AsyncClient | None = None +_client_lock = asyncio.Lock() + + +async def shared_client() -> httpx.AsyncClient: + """The one client, built on first use. Carries no cookies; the session is + passed on every call, so two families' cookies never meet.""" + global _client + if _client is None: + async with _client_lock: + if _client is None: + _client = build_client( + timeout=_TIMEOUT, + headers={ + "x-requested-with": "XMLHttpRequest", + "accept": "application/json, text/plain, */*", + }, + ) + return _client + + +async def close_client() -> None: + """Close the shared client. For the lifespan and for tests.""" + global _client + if _client is not None: + await _client.aclose() + _client = None + + +def _hash_password(salt: str, password: str) -> tuple[str, str]: + """``(pw, pw2)`` as every windows-1251 client computes them. + + A character the region's charset cannot encode is a wrong password from + here: raised as :class:`BadCredentials` without the source character in the + message, because that message would otherwise carry the password. + """ + try: + raw = password.encode("windows-1251") + except UnicodeEncodeError: + raise BadCredentials from None + inner = hashlib.md5(raw).hexdigest() # noqa: S324 - the upstream's scheme, not ours + pw2 = hashlib.md5((salt + inner).encode("ascii")).hexdigest() # noqa: S324 + return pw2[: len(password)], pw2 + + +class NetSchoolClient: + """Calls one region's ``/webapi`` on behalf of one session. + + @param region the allow-listed region — the only source of the origin. + @param session the sealed credential parsed back, or ``None`` before login. + """ + + __slots__ = ("region", "session") + + def __init__(self, region: Region, session: dict[str, Any] | None = None) -> None: + self.region = region + self.session: dict[str, Any] = session or {} + + @property + def credential(self) -> str: + return json.dumps(self.session, ensure_ascii=False, separators=(",", ":")) + + # ---- request plumbing ------------------------------------------------- + + def _url(self, path: str) -> str: + return f"{self.region.origin}{path}" + + def _auth_headers(self) -> dict[str, str]: + headers: dict[str, str] = {} + at = self.session.get("at") + if at: + headers["at"] = at + cookies = self.session.get("cookies") or {} + if cookies: + headers["cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items()) + return headers + + def _absorb_cookies(self, response: httpx.Response) -> None: + """Fold this answer's session cookies into the stored set.""" + cookies = dict(self.session.get("cookies") or {}) + changed = False + for name in SESSION_COOKIES: + value = session_cookie(response, name) + if value and value != cookies.get(name): + cookies[name] = value + changed = True + if changed: + self.session["cookies"] = cookies + + @staticmethod + def _looks_refused(response: httpx.Response) -> bool: + if response.status_code == 403: + return True + ctype = response.headers.get("content-type", "") + if "html" in ctype or "json" not in ctype: + body = response.text[:2000] + return any(marker in body for marker in _WAF_MARKERS) + return False + + @staticmethod + def _is_security_warning(response: httpx.Response) -> bool: + ctype = response.headers.get("content-type", "") + return "html" in ctype and "/asp/SecurityWarning.asp" in response.text[:2000] + + async def _send( + self, + method: str, + path: str, + *, + params: dict[str, str] | None = None, + data: dict[str, str] | None = None, + auth: bool = True, + timeout: httpx.Timeout | None = None, + ) -> httpx.Response: + """One request, with the session in headers and never in the URL.""" + client = await shared_client() + headers = self._auth_headers() if auth else {} + try: + response = await client.request( + method, + self._url(path), + params=params, + data=data, + headers=headers, + timeout=timeout or _TIMEOUT, + ) + except httpx.TransportError as error: + text = str(error).lower() + if "reset" in text or "refused" in text or "denied" in text: + raise AddressRefused from error + raise UpstreamUnavailable from error + if self._looks_refused(response): + raise AddressRefused + return response + + def _decode(self, response: httpx.Response, *, step: str) -> Any: + """A JSON body, or the mapped failure for anything else.""" + status = response.status_code + if status >= 500: + raise UpstreamUnavailable + if status == 429: + raise UpstreamUnavailable + try: + return response.json() + except ValueError: + raise UnexpectedResponse from None + + async def _authed_json(self, method: str, path: str, **kwargs: Any) -> Any: + """An authenticated call that returns JSON, handling the ways a dead + NetSchool session shows: 401, a redirect, an HTML login page, or the + co-working SecurityWarning interstitial.""" + response = await self._send(method, path, **kwargs) + if self._is_security_warning(response): + await self._acknowledge_warning() + response = await self._send(method, path, **kwargs) + if self._is_security_warning(response): + raise SessionExpired + if response.status_code == 401 or response.is_redirect: + raise SessionExpired + ctype = response.headers.get("content-type", "") + if "json" not in ctype: + # A non-JSON 200 on an authenticated call is a login page: the + # session is gone, which is «войдите снова», not «непонятно». + raise SessionExpired + self._absorb_cookies(response) + new_at = response.headers.get("at") + if new_at and new_at != self.session.get("at"): + self.session["at"] = new_at + return self._decode(response, step=path) + + async def _acknowledge_warning(self) -> None: + """Answer the «another session is open» interstitial once, best effort.""" + with_at = self.session.get("at") + if not with_at: + return + data = {"at": with_at, "WarnType": "2", "ver": str(self.session.get("ver", ""))} + try: + await self._send("POST", "/asp/SecurityWarning.asp", data=data) + except UpstreamUnavailable: + return + + # ---- sign-in ---------------------------------------------------------- + + async def login_allowed(self) -> None: + """Read the region's sign-in options. Raise before any credential is sent. + + This is the only place :class:`SignInUnsupported` comes from, so handing + the ticket back on it is safe: no password has been touched. + """ + response = await self._send("GET", "/webapi/logindata", auth=False) + data = self._decode(response, step="logindata") + self._absorb_cookies(response) + if not data.get("schoolLogin", True): + raise SignInUnsupported + self.session.setdefault("ver", data.get("cacheVer")) + + async def login(self, login: str, password: str, school_id: int) -> None: + """Sign in with a password. On return the session holds ``at`` and cookies. + + Ends at the accepted ``POST /webapi/login``; the caller runs the + bootstrap. A wrong password is :class:`BadCredentials`; the region + refusing our address is :class:`AddressRefused`; anything unreadable + before the password POST is :class:`UpstreamUnavailable`, so the ticket + survives. + """ + await self.login_allowed() + try: + await self._password_login(login, password, school_id, rolegroup=None) + except _NeedsRole as need: + await self._password_login(login, password, school_id, rolegroup=need.rolegroup) + + async def _password_login( + self, login: str, password: str, school_id: int, *, rolegroup: str | None + ) -> None: + # getdata carries a one-shot salt tied to the cookie it saw, so each + # attempt (including a role re-login) re-fetches it. + getdata = await self._send( + "POST", "/webapi/auth/getdata", auth=True, data={} + ) + self._absorb_cookies(getdata) + payload = self._decode(getdata, step="getdata") + salt = str(payload.get("salt", "")) + lt = str(payload.get("lt", "")) + ver = str(payload.get("ver", "")) + if not salt or not lt: + raise UpstreamUnavailable # getdata is before the password; hand the ticket back + pw, pw2 = _hash_password(salt, password) + form = { + "loginType": "1", + "scid": str(school_id), + "un": login, + "pw": pw, + "pw2": pw2, + "lt": lt, + "ver": ver, + } + if rolegroup is not None: + form["rolegroup"] = rolegroup + response = await self._send("POST", "/webapi/login", auth=True, data=form) + self._absorb_cookies(response) + self._consume_login(response, login, password, school_id, tried_role=rolegroup is not None) + + def _consume_login( + self, + response: httpx.Response, + login: str, + password: str, + school_id: int, + *, + tried_role: bool, + ) -> None: + status = response.status_code + if status == 409: + raise BadCredentials(self._login_message(response)) + if status == 429: + raise UpstreamUnavailable + if status >= 500: + raise UpstreamUnavailable + try: + body = response.json() + except ValueError: + raise UnexpectedResponse from None + entry = body.get("entryPoint") or "" + if "choose-session-role" in entry and not tried_role: + # The account is both staff and parent. The salt was one-shot, so + # the role re-login (in `login`) reruns the whole sequence with a + # fresh one. Checked before `at` is accepted, as netschoolpy does. + raise _NeedsRole(self._pick_parent_role(body)) + at = body.get("at") + if not at: + raise BadCredentials(self._login_message(body)) + self.session["at"] = at + if body.get("timeOut"): + self.session["time_out"] = int(body["timeOut"]) + + @staticmethod + def _login_message(source: Any) -> str | None: + if isinstance(source, httpx.Response): + try: + source = source.json() + except ValueError: + return None + if isinstance(source, dict): + text = source.get("message") or source.get("errorMessage") + if isinstance(text, str) and text.strip(): + return text.strip()[:200] + return None + + @staticmethod + def _pick_parent_role(body: dict[str, Any]) -> str | None: + info = body.get("accountInfo") or {} + roles = info.get("userRoles") or body.get("userRoles") or [] + for entry in roles: + role = entry.get("role", entry) if isinstance(entry, dict) else {} + name = str(role.get("name", "")) if isinstance(role, dict) else "" + if "Родител" in name: + rid = role.get("id") if isinstance(role, dict) else None + if rid is not None: + return str(rid) + if roles: + first = roles[0].get("role", roles[0]) if isinstance(roles[0], dict) else {} + rid = first.get("id") if isinstance(first, dict) else None + return str(rid) if rid is not None else None + return None + + # ---- keep-alive and logout ------------------------------------------- + + async def keep_alive(self) -> None: + """Reset the idle timer with GET /webapi/context (the `at` in a header, + never in the URL). A dead session raises :class:`SessionExpired`.""" + await self._authed_json("GET", "/webapi/context", timeout=_KEEPALIVE_TIMEOUT) + + async def logout(self) -> None: + """Tell the upstream we are done. Unlike Petersburg, NetSchool has a + logout that works without a browser. Best effort: a dead session or a + transport failure is fine, we are leaving anyway.""" + at = self.session.get("at") + if not at: + return + try: + await self._send( + "POST", + "/webapi/auth/logout", + auth=True, + data={"at": at, "ver": str(self.session.get("ver", ""))}, + timeout=_KEEPALIVE_TIMEOUT, + ) + except (UpstreamUnavailable, SessionExpired, UnexpectedResponse): + return + + # ---- reads ------------------------------------------------------------ + + async def diary_init(self) -> Any: + return await self._authed_json("GET", "/webapi/student/diary/init") + + async def years_current(self) -> Any: + return await self._authed_json("GET", "/webapi/years/current") + + async def context(self) -> Any: + return await self._authed_json("GET", "/webapi/context") + + async def assignment_types(self) -> Any: + return await self._authed_json( + "GET", "/webapi/grade/assignment/types", params={"all": "false"} + ) + + async def diary_week( + self, student_id: int, year_id: int, week_start: str, week_end: str + ) -> Any: + return await self._authed_json( + "GET", + "/webapi/student/diary", + params={ + "studentId": str(student_id), + "yearId": str(year_id), + "weekStart": week_start, + "weekEnd": week_end, + "withLaAssigns": "true", + }, + ) + + async def terms_search(self, group_id: int | None) -> Any: + # terms/search takes a JSON body, not a form. + body = {"classIds": [group_id]} if group_id is not None else {} + client = await shared_client() + headers = self._auth_headers() + headers["content-type"] = "application/json" + try: + response = await client.request( + "POST", + self._url("/webapi/terms/search"), + content=json.dumps(body), + headers=headers, + timeout=_TIMEOUT, + ) + except httpx.TransportError as error: + raise UpstreamUnavailable from error + if self._looks_refused(response): + raise AddressRefused + if response.status_code == 401 or response.is_redirect: + raise SessionExpired + if response.status_code in (404, 405): + return [] # this server has no such endpoint + try: + return response.json() + except ValueError: + raise UnexpectedResponse from None + + +class _NeedsRole(Exception): + """Internal: the login must be retried with a role. Never leaves the client.""" + + def __init__(self, rolegroup: str | None) -> None: + super().__init__("role required") + self.rolegroup = rolegroup diff --git a/server/app/providers/netschool/mapper.py b/server/app/providers/netschool/mapper.py new file mode 100644 index 00000000..78954064 --- /dev/null +++ b/server/app/providers/netschool/mapper.py @@ -0,0 +1,297 @@ +"""«Сетевой город» JSON → the shared diary models. + +Lenient in, strict out, like Petersburg's mapper: a single unreadable row is +dropped with a warning, and only a wholly unreadable answer raises +:class:`UnexpectedResponse`. The upstream field names are documented in +`docs/diaries/netschool.md` and were read from the open clients, not a live +server, so this file is the one place they live. + +Homework is the assignments of ``typeId == 3`` — which is how the «Сетевой +город» web diary itself tells homework from classwork. A mark's ``dutyMark`` is +a debt («·»), drawn instead of a number, not an absence: this platform's +absences live only in the SignalR reports, which batch 1 does not read, so +:func:`to_marks` never yields an ABSENCE or a LATE and :func:`to_attendance` +is always empty. +""" + +from __future__ import annotations + +import logging +from datetime import date as Date +from datetime import time as Time +from typing import Any + +from app.providers.diary.models import ( + AcademicPeriod, + AttendanceEvent, + DiaryLesson, + HomeworkItem, + Mark, + MarkKind, + Student, + Subject, + Teacher, +) + +log = logging.getLogger(__name__) + +HOMEWORK_TYPE_ID = 3 + + +def _text(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def _parse_date(raw: Any) -> Date | None: + """A naive ISO date or datetime (``2026-09-15`` or ``…T00:00:00``).""" + text = _text(raw) + if not text: + return None + try: + return Date.fromisoformat(text[:10]) + except ValueError: + return None + + +def _parse_time(raw: Any) -> Time | None: + """``HH:MM`` or ``HH:MM:SS`` — the two forms the clients see.""" + text = _text(raw) + if not text: + return None + for fmt_len in (5, 8): + try: + return Time.fromisoformat(text[:fmt_len]) + except ValueError: + continue + return None + + +def to_students(init: dict[str, Any], school: str | None) -> list[Student]: + """``student/diary/init`` → the pupils this account may see. + + ``students`` arrives as a list, or on some servers as an index-keyed dict; + both are accepted. A child's only name is ``nickName``, one display string, + so it is kept whole rather than split wrongly. + """ + raw = init.get("students") + if isinstance(raw, dict): + raw = list(raw.values()) + if not isinstance(raw, list): + raise UnexpectedResponseError + students: list[Student] = [] + for row in raw: + if not isinstance(row, dict): + continue + sid = row.get("studentId") + if not isinstance(sid, int): + continue + nick = _text(row.get("nickName")) or "" + students.append( + Student( + id=sid, + last_name=nick, + first_name="", + school=school, + class_name=_text(row.get("className")), + education_id=sid, + group_id=row.get("classId") if isinstance(row.get("classId"), int) else None, + ) + ) + if raw and not students: + raise UnexpectedResponseError + return students + + +def _days(diary: dict[str, Any]) -> list[dict[str, Any]]: + days = diary.get("weekDays") + return [d for d in days if isinstance(d, dict)] if isinstance(days, list) else [] + + +def _lessons(day: dict[str, Any]) -> list[dict[str, Any]]: + lessons = day.get("lessons") + return [x for x in lessons if isinstance(x, dict)] if isinstance(lessons, list) else [] + + +def _week_class_name(diary: dict[str, Any]) -> str | None: + return _text(diary.get("className")) + + +def to_lessons( + diary: dict[str, Any], date_from: Date, date_to: Date +) -> list[DiaryLesson]: + """One week's ``student/diary`` → lessons within ``[date_from, date_to]``. + + A lesson with an empty ``subjectName`` is dropped: the SGO web diary hides + those rows too. Homework on the lesson (``typeId == 3``) is joined into the + lesson's ``homework``; the teacher and the topic are not in this route, so + they stay ``None``. + """ + out: list[DiaryLesson] = [] + for day in _days(diary): + when = _parse_date(day.get("date")) + if when is None or not (date_from <= when <= date_to): + continue + for lesson in _lessons(day): + subject = _text(lesson.get("subjectName")) + if not subject: + continue + homework = _homework_text(lesson) + out.append( + DiaryLesson( + date=when, + number=lesson.get("number") if isinstance(lesson.get("number"), int) else None, + subject=subject, + starts_at=_parse_time(lesson.get("startTime")), + ends_at=_parse_time(lesson.get("endTime")), + room=_text(lesson.get("room")), + homework=homework, + ) + ) + return out + + +def _assignments(lesson: dict[str, Any]) -> list[dict[str, Any]]: + items = lesson.get("assignments") + return [a for a in items if isinstance(a, dict)] if isinstance(items, list) else [] + + +def _homework_text(lesson: dict[str, Any]) -> str | None: + parts = [ + _text(a.get("assignmentName")) + for a in _assignments(lesson) + if a.get("typeId") == HOMEWORK_TYPE_ID + ] + parts = [p for p in parts if p] + return "; ".join(parts) if parts else None + + +def to_homework( + diary: dict[str, Any], date_from: Date, date_to: Date +) -> list[HomeworkItem]: + """Homework as its own resource, addressed to the day it is due.""" + out: list[HomeworkItem] = [] + for day in _days(diary): + lesson_day = _parse_date(day.get("date")) + for lesson in _lessons(day): + subject = _text(lesson.get("subjectName")) + if not subject: + continue + for a in _assignments(lesson): + if a.get("typeId") != HOMEWORK_TYPE_ID: + continue + text = _text(a.get("assignmentName")) + if not text: + continue + due = _parse_date(a.get("dueDate")) or lesson_day + if due is None or not (date_from <= due <= date_to): + continue + out.append( + HomeworkItem( + id=a.get("id") if isinstance(a.get("id"), int) else None, + due_date=due, + subject=subject, + text=text, + ) + ) + return out + + +def to_marks( + diary: dict[str, Any], types: dict[str, str], date_from: Date, date_to: Date +) -> list[Mark]: + """Marks from one week's diary. ``dutyMark`` is a debt («·»), not a grade.""" + out: list[Mark] = [] + for day in _days(diary): + when = _parse_date(day.get("date")) + if when is None or not (date_from <= when <= date_to): + continue + for lesson in _lessons(day): + subject = _text(lesson.get("subjectName")) or "" + for a in _assignments(lesson): + mark = a.get("mark") + if not isinstance(mark, dict): + continue + if mark.get("dutyMark"): + value, kind = "·", MarkKind.OTHER + elif isinstance(mark.get("mark"), int): + value, kind = str(mark["mark"]), MarkKind.GRADE + else: + continue + comment = a.get("markComment") + out.append( + Mark( + id=a.get("id") if isinstance(a.get("id"), int) else None, + subject_name=subject, + date=when, + value=value, + kind=kind, + reason=types.get(str(a.get("typeId"))), + comment=_text(comment.get("name")) if isinstance(comment, dict) else None, + ) + ) + return out + + +def to_periods( + terms: Any, today: Date, week_term_name: str | None = None +) -> list[AcademicPeriod]: + """``terms/search`` → the year's terms. ``is_current`` is derived: the term + holding today, ties broken by the diary week's ``termName``, else the one + whose window is shortest.""" + if not isinstance(terms, list): + return [] + periods: list[AcademicPeriod] = [] + for row in terms: + if not isinstance(row, dict): + continue + tid = row.get("id") + name = _text(row.get("termName")) + if not isinstance(tid, int) or not name: + continue + periods.append( + AcademicPeriod( + id=tid, + name=name, + starts_on=_parse_date(row.get("startDate")), + ends_on=_parse_date(row.get("endDate")), + ) + ) + holding = [ + p for p in periods + if p.starts_on and p.ends_on and p.starts_on <= today <= p.ends_on + ] + current: AcademicPeriod | None = None + if len(holding) == 1: + current = holding[0] + elif holding: + by_name = [p for p in holding if week_term_name and p.name == week_term_name] + current = by_name[0] if by_name else min( + holding, key=lambda p: (p.ends_on - p.starts_on) # type: ignore[operator] + ) + if current is not None: + current.is_current = True + return periods + + +def to_subjects(diary: dict[str, Any]) -> list[Subject]: # noqa: ARG001 + """Not served in batch 1: the diary carries no subject list of its own.""" + return [] + + +def to_teachers(diary: dict[str, Any]) -> list[Teacher]: # noqa: ARG001 + """Not served in batch 1: the diary route carries no teacher.""" + return [] + + +def to_attendance() -> list[AttendanceEvent]: + """«Сетевой город» has no turnstile records at all.""" + return [] + + +class UnexpectedResponseError(Exception): + """Raised by the mappers on a wholly unreadable answer; the connection + turns it into the shared :class:`UnexpectedResponse`. Kept private so the + mapper stays free of the error module and testable on its own.""" diff --git a/server/app/providers/netschool/provider.py b/server/app/providers/netschool/provider.py new file mode 100644 index 00000000..78c4291b --- /dev/null +++ b/server/app/providers/netschool/provider.py @@ -0,0 +1,237 @@ +"""«Сетевой город» behind the shared provider contract. + +`NetSchoolProvider.sign_in` runs the password login and then the bootstrap that +every open client runs — the children (a staff-only account with no pupil is +refused here, not on the first screen later), the school year and its bounds, +and the assignment-type map — sealing them into the credential so later reads +cost fewer calls and a walk can be clipped to the year. + +`NetSchoolConnection` walks the diary a week at a time, because the route is a +week at a time in every client, and clips each walk to the school year's bounds +so a session kept alive across 1 September does not ask for a year that has +ended. A credential that will not parse makes every call +:class:`SessionExpired`, so a key rotation expires the row rather than 500ing. +""" + +from __future__ import annotations + +import json +import logging +from datetime import date as Date +from datetime import datetime, timedelta + +from app.providers.diary.errors import SessionExpired, UnexpectedResponse +from app.providers.diary.models import ( + AcademicPeriod, + AttendanceEvent, + DiaryLesson, + HomeworkItem, + Mark, + Student, + Subject, + Teacher, +) +from app.providers.netschool import mapper as m +from app.providers.netschool.client import CREDENTIAL_VERSION, NetSchoolClient +from app.providers.netschool.regions import Region +from app.providers.netschool.regions import get as region_for +from app.timezones import resolve + +log = logging.getLogger(__name__) + +#: The widest a single walk may run, matching the API's own MAX_RANGE_DAYS, so +#: a run is at most ~10 weekly calls. +MAX_WEEKS = 11 + + +def _iso(day: Date) -> str: + return day.isoformat() + + +def _weeks(date_from: Date, date_to: Date, year_start: Date | None, year_end: Date | None): + """(weekStart, weekEnd) Monday–Sunday spans covering [from, to], clipped to + the school year. A week wholly outside the year yields nothing, so no call + is made for it.""" + lo = max(date_from, year_start) if year_start else date_from + hi = min(date_to, year_end) if year_end else date_to + cursor = lo - timedelta(days=lo.weekday()) # Monday of the first week + count = 0 + while cursor <= hi and count < MAX_WEEKS: + week_start = max(cursor, lo) + week_end = min(cursor + timedelta(days=6), hi) + if week_start <= week_end: + yield week_start, week_end + cursor += timedelta(days=7) + count += 1 + + +class NetSchoolConnection: + __slots__ = ("_client", "_region") + + def __init__(self, region: Region, session: dict) -> None: + self._region = region + self._client = NetSchoolClient(region, session) + + @property + def credential(self) -> str: + return self._client.credential + + def _year(self) -> tuple[int | None, Date | None, Date | None]: + s = self._client.session + return ( + s.get("year_id"), + m._parse_date(s.get("year_start")), + m._parse_date(s.get("year_end")), + ) + + async def students(self) -> list[Student]: + init = await self._client.diary_init() + try: + return m.to_students(init, self._client.session.get("school")) + except m.UnexpectedResponseError: + raise UnexpectedResponse from None + + async def periods(self, group_id: int) -> list[AcademicPeriod]: + terms = await self._client.terms_search(group_id) + return m.to_periods(terms, self.today()) + + async def subjects(self, group_id: int, period_id: int) -> list[Subject]: # noqa: ARG002 + return [] + + async def teachers(self, education_id: int) -> list[Teacher]: # noqa: ARG002 + return [] + + async def attendance(self, education_id: int) -> list[AttendanceEvent]: # noqa: ARG002 + return m.to_attendance() + + async def _walk(self, education_id: int, date_from: Date, date_to: Date): + year_id, year_start, year_end = self._year() + if year_id is None: + raise SessionExpired # no year handle sealed → the session is unusable + for week_start, week_end in _weeks(date_from, date_to, year_start, year_end): + yield week_start, week_end, await self._client.diary_week( + education_id, year_id, _iso(week_start), _iso(week_end) + ) + + async def schedule( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[DiaryLesson]: + out: list[DiaryLesson] = [] + async for ws, we, diary in self._walk(education_id, date_from, date_to): + out.extend(m.to_lessons(diary, ws, we)) + return out + + async def homework( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[HomeworkItem]: + out: list[HomeworkItem] = [] + async for ws, we, diary in self._walk(education_id, date_from, date_to): + out.extend(m.to_homework(diary, ws, we)) + return out + + async def marks(self, education_id: int, date_from: Date, date_to: Date) -> list[Mark]: + types = self._client.session.get("types") or {} + out: list[Mark] = [] + async for ws, we, diary in self._walk(education_id, date_from, date_to): + out.extend(m.to_marks(diary, types, ws, we)) + return out + + async def keep_alive(self) -> None: + await self._client.keep_alive() + + async def close(self) -> None: + await self._client.logout() + + def today(self) -> Date: + return datetime.now(resolve(self._region.zone)).date() + + +class NetSchoolProvider: + """The «Сетевой город. Образование» diary.""" + + key = "netschool" + title = "Сетевой город" + genitive = "«Сетевого города»" + + async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest protocol + region = region_for(request.region) + if region is None or not region.password or request.school_id is None: + # A caller reached sign-in with a region the allow-list does not + # serve, or without a school. Callers validate first, so this is a + # programming error rather than a user's — a ValueError, not a + # DiaryError. + raise ValueError("netschool sign-in needs an allow-listed region and a school id") + client = NetSchoolClient(region, {"v": CREDENTIAL_VERSION, "region": region.key, + "school_id": request.school_id}) + await client.login(request.login.strip(), request.password, request.school_id) + await self._bootstrap(client) + return client.credential + + @staticmethod + async def _bootstrap(client: NetSchoolClient) -> None: + """After the password is accepted: the children, the year and the type + map. A failure here is a real session's failure — SessionExpired-shaped + — because the password was already judged.""" + init = await client.diary_init() + try: + students = m.to_students(init, None) + except m.UnexpectedResponseError: + raise UnexpectedResponse from None + if not students: + raise SessionExpired("В этой учётной записи нет ученика") + year = await client.years_current() + if isinstance(year, dict): + client.session["year_id"] = year.get("id") + client.session["year_start"] = _year_date(year.get("startDate")) + client.session["year_end"] = _year_date(year.get("endDate")) + ctx = await client.context() + if isinstance(ctx, dict): + org = ctx.get("organization") + name = ctx.get("organizationName") or ( + org.get("name") if isinstance(org, dict) else None + ) + if name: + client.session["school"] = str(name)[:300] + types = await client.assignment_types() + if isinstance(types, list): + client.session["types"] = { + str(t.get("id")): str(t.get("name")) + for t in types + if isinstance(t, dict) and t.get("id") is not None + } + + def open(self, credential: str) -> NetSchoolConnection: + try: + session = json.loads(credential) + region = region_for(session.get("region")) + if region is None: + raise ValueError("unknown region") + except (ValueError, TypeError): + # A credential that will not parse, or names a region no longer + # served, is a dead session: every call raises SessionExpired, and + # the row is expired on lookup rather than 500ing. + return _DeadConnection() # type: ignore[return-value] + return NetSchoolConnection(region, session) + + +def _year_date(raw) -> str | None: # noqa: ANN001 + parsed = m._parse_date(raw) + return parsed.isoformat() if parsed else None + + +class _DeadConnection: + """A connection for an unreadable credential: everything is SessionExpired.""" + + credential = "" + + def today(self) -> Date: + return datetime.now().date() + + async def _dead(self, *a, **k): # noqa: ANN002, ANN003, ARG002 + raise SessionExpired + + async def close(self) -> None: + """Nothing to log out of: the credential never opened.""" + + students = periods = subjects = teachers = attendance = _dead + schedule = homework = marks = keep_alive = _dead diff --git a/server/app/providers/netschool/regions.py b/server/app/providers/netschool/regions.py new file mode 100644 index 00000000..5f111488 --- /dev/null +++ b/server/app/providers/netschool/regions.py @@ -0,0 +1,90 @@ +"""The regional servers of «Сетевой город», and the only ones we ever call. + +This table is an allow-list first and a directory second. A region key that +reaches sign-in — from a client body, a class row or a sealed credential — is +looked up here, and a key that is not in the table is refused before any +network call. That is the whole SSRF guard: nothing turns free text into a +host, so this server cannot be pointed at an address of somebody's choosing. + +The set is the survey's (`docs/diaries/netschool.md`). A region that leaves +«Сетевой город» is removed here, which ends its sessions at their next call. + +Two flags decide what a region is good for: + +- ``password`` — whether a login and password get in at all. Three regions have + switched to Госуслуги only (`docs/diaries/netschool.md`), so ``password`` is + ``False`` there: the bot never offers them and every door refuses them + locally, with no request sent. +- ``verified`` — whether this server has been seen to answer from production. + It is ``False`` for every row, because **nothing here has been tried from the + deployment's own address** (#121, #135). The one-off owner probe fills that + gap; until then the bot marks an unverified region «не проверено». + +``https`` only: an ``http`` origin would send the salted password and the +session in clear text, so a region that serves only ``http`` (Волгоград) is +left out rather than downgraded. + +``ca_bundle`` is for a region that presents a non-Mozilla root (the Russian +Trusted Root): a path to a CA file to trust *for that origin only*. TLS +verification is never turned off; a region that would need that is left out. +""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Region: + key: str + title: str + origin: str # https:// only; the base for every /webapi call + zone: str # IANA; resolved through app.timezones.resolve, which falls back rather than raises + password: bool = True + verified: bool = False + ca_bundle: str | None = None + + +# Ordered as docs/diaries.md lists them. Zones are the region's administrative +# centre; a region spanning several keeps its capital's. +_REGIONS: tuple[Region, ...] = ( + # ЕСИА-only since 10 Jan 2026 — never offered, refused locally. + Region("altai-krai", "Алтайский край", "https://netschool.edu22.info", + "Asia/Barnaul", password=False), + Region("amur", "Амурская область", "https://region.obramur.ru", "Asia/Yakutsk"), + Region("zabaikalsky", "Забайкальский край", "https://region.zabedu.ru", "Asia/Chita"), + Region("kamchatka", "Камчатский край", "https://school.sgo41.ru", "Asia/Kamchatka"), + Region("kchr", "Карачаево-Черкесская Республика", "https://sgo.kchgov.ru", "Europe/Moscow"), + Region("leningrad", "Ленинградская область", "https://e-school.obr.lenreg.ru", "Europe/Moscow"), + # ЕСИА-only. + Region("primorye", "Приморский край", "https://sgo.prim-edu.ru", + "Asia/Vladivostok", password=False), + Region("buryatia", "Республика Бурятия", "https://deti.obr03.ru", "Asia/Irkutsk"), + Region("ingushetia", "Республика Ингушетия", "https://sgo.edu-ri.ru", "Europe/Moscow"), + Region("komi", "Республика Коми", "https://giseo.rkomi.ru", "Europe/Moscow"), + Region("mari-el", "Республика Марий Эл", "https://sgo.mari-el.gov.ru", "Europe/Moscow"), + Region("mordovia", "Республика Мордовия", "https://sgo.e-mordovia.ru", "Europe/Moscow"), + Region("yakutia", "Республика Саха (Якутия)", "https://sgo.e-yakutia.ru", "Asia/Yakutsk"), + Region("ryazan", "Рязанская область", "https://e-school.ryazan.gov.ru", "Europe/Moscow"), + Region("samara", "Самарская область", "https://asurso.ru", "Europe/Samara"), + Region("sakhalin", "Сахалинская область", "https://netcity.admsakhalin.ru:11111", + "Asia/Sakhalin"), + Region("tomsk", "Томская область", "https://sgo.tomedu.ru", "Asia/Tomsk"), + # ЕСИА + SMS only. + Region("tula", "Тульская область", "https://sgo1.edu71.ru", "Europe/Moscow", password=False), + Region("ulyanovsk", "Ульяновская область", "https://sgo.cit73.ru", "Europe/Ulyanovsk"), +) + +_BY_KEY = {r.key: r for r in _REGIONS} + + +def get(key: str | None) -> Region | None: + """The region for a key, or ``None`` for one not in the allow-list.""" + if not key: + return None + return _BY_KEY.get(key) + + +def listed(*, password_only: bool = True) -> list[Region]: + """The regions, for the bot's picker. Only password-capable ones by default.""" + return [r for r in _REGIONS if r.password or not password_only] diff --git a/server/app/providers/petersburg/exceptions.py b/server/app/providers/petersburg/exceptions.py index 75887f7d..8486b06d 100644 --- a/server/app/providers/petersburg/exceptions.py +++ b/server/app/providers/petersburg/exceptions.py @@ -1,55 +1,29 @@ -"""What can go wrong upstream, named so a route can answer it. +"""Petersburg's error names, which are now the shared diary errors. -The upstream speaks HTTP and sometimes speaks HTML at us; the rest of the -application should not have to tell the difference between "wrong password", -"session over", "they are down" and "they changed the response". Each of those -needs a different answer at the API edge, so each is a type here. +This module pre-dates :mod:`app.providers.diary.errors`. Its names are kept as +aliases of the very classes defined there — ``PetersburgError is DiaryError`` — +so every ``from app.providers.petersburg import BadCredentials`` still works and +``isinstance`` holds whether a failure was raised under the old spelling or the +new one. New code should import from :mod:`app.providers.diary.errors`. """ from __future__ import annotations - -class PetersburgError(Exception): - """Base for everything this provider raises.""" - - #: What the client is told. Deliberately short and Russian - these reach a - #: phone screen, not a log reader. - message = "Электронный дневник недоступен" - - def __init__(self, message: str | None = None) -> None: - super().__init__(message or self.message) - self.message = message or self.message - - -class BadCredentials(PetersburgError): - """The login or the password is wrong. Nothing to retry.""" - - message = "Неверный логин или пароль" - - -class SessionExpired(PetersburgError): - """The stored session is no longer accepted. - - Distinct from :class:`BadCredentials` because the answer is different: the - person has not changed their password, they have simply been away long - enough. The client turns this into «войдите снова», not «вы ошиблись». - """ - - message = "Сессия дневника истекла — войдите заново" - - -class UpstreamUnavailable(PetersburgError): - """A timeout, a connection failure, or a 5xx.""" - - message = "Электронный дневник не отвечает" - - -class UnexpectedResponse(PetersburgError): - """A 200 whose body is not what this provider knows how to read. - - Its own type because it means *this code* needs changing, not the network - and not the user's password - and because it is the failure an undocumented - API produces when it is quietly redesigned. - """ - - message = "Электронный дневник ответил непонятно" +from app.providers.diary.errors import ( + BadCredentials, + DiaryError, + SessionExpired, + UnexpectedResponse, + UpstreamUnavailable, +) + +#: The old base name. The same class as :class:`app.providers.diary.errors.DiaryError`. +PetersburgError = DiaryError + +__all__ = [ + "BadCredentials", + "PetersburgError", + "SessionExpired", + "UnexpectedResponse", + "UpstreamUnavailable", +] diff --git a/server/app/providers/petersburg/models.py b/server/app/providers/petersburg/models.py index fda24e3b..4b7e28e1 100644 --- a/server/app/providers/petersburg/models.py +++ b/server/app/providers/petersburg/models.py @@ -1,141 +1,36 @@ -"""The diary as this project describes it. +"""Petersburg's model names, which are now the shared diary models. -These are the models the rest of the application and the Android client see. -They are deliberately not the upstream's shapes: nothing here is called -``estimate_value_name``, nothing carries ``p_educations``, and no field exists -only because an undocumented API happened to send it. +This module pre-dates :mod:`app.providers.diary.models`. Every model it once +defined lives there now and is re-exported here unchanged — the same classes, +so ``isinstance`` holds across both spellings and nothing that imports +``app.providers.petersburg.models`` breaks. New code should import from +:mod:`app.providers.diary.models`. -That distance is the point of the whole integration. When the upstream renames -a field, :mod:`app.providers.petersburg.mapper` changes and these do not - so -neither does the public API, and neither does the phone. +``DiaryAccount`` used to live here and had no reader; it is gone (#138). """ from __future__ import annotations -from datetime import date as Date -from datetime import datetime -from datetime import time as Time -from enum import StrEnum - -from pydantic import BaseModel, Field - - -class MarkKind(StrEnum): - """What a mark in the register actually is. - - The upstream mixes four different things into one list - a grade, an - absence, a late arrival and a teacher's remark all arrive as "estimates" - and are told apart by a numeric code. Naming them here is what stops every - consumer from re-learning that code. - """ - - GRADE = "grade" - ABSENCE = "absence" - LATE = "late" - REMARK = "remark" - OTHER = "other" - - -class Student(BaseModel): - """One pupil the signed-in account may see.""" - - id: int - first_name: str - last_name: str - middle_name: str | None = None - school: str | None = None - class_name: str | None = None - #: Opaque upstream handles. Present because later calls need them and the - #: client passes them straight back; never parsed by the phone. - education_id: int - group_id: int | None = None - - @property - def full_name(self) -> str: - parts = [self.last_name, self.first_name, self.middle_name] - return " ".join(part for part in parts if part) - - -class AcademicPeriod(BaseModel): - """A quarter or a term, with the dates it covers.""" - - id: int - name: str - starts_on: Date | None = None - ends_on: Date | None = None - is_current: bool = False - - -class Subject(BaseModel): - id: int | None = None - name: str - - -class Teacher(BaseModel): - id: int | None = None - name: str - position: str | None = None - subjects: list[str] = Field(default_factory=list) - - -class Mark(BaseModel): - """One entry in the register. - - @property value what is written in the cell: «5», «Н», «!» - already - normalised, so a client never has to know which code means absent. - """ - - id: int | None = None - subject_id: int | None = None - subject_name: str - date: Date | None = None - value: str - kind: MarkKind = MarkKind.OTHER - #: The teacher's word for the occasion: «Контрольная работа», «Ответ на уроке». - reason: str | None = None - comment: str | None = None - - -class DiaryLesson(BaseModel): - """A lesson as the diary has it, with whatever was set on it.""" - - date: Date - number: int | None = None - subject: str - starts_at: Time | None = None - ends_at: Time | None = None - room: str | None = None - teacher: str | None = None - homework: str | None = None - topic: str | None = None - - -class HomeworkItem(BaseModel): - """Homework, addressed to the day it is due rather than the day it was set.""" - - id: int | None = None - due_date: Date - subject: str - text: str - teacher: str | None = None - - -class AttendanceEvent(BaseModel): - """A turnstile record. - - ``direction`` is ``in``, ``out`` or ``unknown``. The third one is not a - parsing failure to be tidied away: the upstream is undocumented, and a - spelling this code has not seen must not be rendered as the child leaving - the building. Anything reading this has three cases to answer, and the - third one is «дневник не сказал, куда». - """ - - at: datetime - direction: str # "in" | "out" | "unknown" - - -class DiaryAccount(BaseModel): - """Who is signed in, for the line that says so.""" - - login: str - students: list[Student] = Field(default_factory=list) +from app.providers.diary.models import ( + AcademicPeriod, + AttendanceEvent, + DiaryLesson, + HomeworkItem, + Mark, + MarkKind, + Student, + Subject, + Teacher, +) + +__all__ = [ + "AcademicPeriod", + "AttendanceEvent", + "DiaryLesson", + "HomeworkItem", + "Mark", + "MarkKind", + "Student", + "Subject", + "Teacher", +] diff --git a/server/app/providers/petersburg/provider.py b/server/app/providers/petersburg/provider.py new file mode 100644 index 00000000..9aa15012 --- /dev/null +++ b/server/app/providers/petersburg/provider.py @@ -0,0 +1,98 @@ +"""Petersburg behind the shared provider contract. + +Everything the diary does for Petersburg was in `services/diary.DiaryService`. +That knowledge moves here, unchanged, so the service can hold any provider and +Petersburg is just the first: the same calls, the same mapper functions, the +same «today is the city's clock» rule for periods. + +``PetersburgConnection`` keeps its :class:`PetersburgClient` public, because a +test swaps a fake in through it. The credential is the client's session token, +which the client refreshes in place on most calls; the service re-seals it +whenever :attr:`credential` changes. +""" + +from __future__ import annotations + +from datetime import date as Date + +from app.providers.diary.models import ( + AcademicPeriod, + AttendanceEvent, + DiaryLesson, + HomeworkItem, + Mark, + Student, + Subject, + Teacher, +) +from app.providers.petersburg import mapper as m +from app.providers.petersburg.client import PetersburgClient, today + + +class PetersburgConnection: + """One Petersburg session's reads.""" + + __slots__ = ("client",) + + def __init__(self, credential: str) -> None: + self.client = PetersburgClient(credential or None) + + @property + def credential(self) -> str: + return self.client.token or "" + + async def students(self) -> list[Student]: + return m.to_students(await self.client.children()) + + async def periods(self, group_id: int) -> list[AcademicPeriod]: + # The upstream's own clock, not the server's — the same reason the old + # DiaryService.periods gave: this diary is one city's, that city keeps + # Moscow time, and «current term» read on the server's UTC clock put an + # evening pupil into yesterday and answered the subjects screen empty. + return m.to_periods(await self.client.periods(group_id), today()) + + async def subjects(self, group_id: int, period_id: int) -> list[Subject]: + return m.to_subjects(await self.client.subjects(group_id, period_id)) + + async def teachers(self, education_id: int) -> list[Teacher]: + return m.to_teachers(await self.client.teachers(education_id)) + + async def marks(self, education_id: int, date_from: Date, date_to: Date) -> list[Mark]: + return m.to_marks(await self.client.marks(education_id, date_from, date_to)) + + async def schedule( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[DiaryLesson]: + return m.to_lessons(await self.client.schedule(education_id, date_from, date_to)) + + async def homework( + self, education_id: int, date_from: Date, date_to: Date + ) -> list[HomeworkItem]: + return m.to_homework(await self.client.lessons(education_id, date_from, date_to)) + + async def attendance(self, education_id: int) -> list[AttendanceEvent]: + return m.to_attendance(await self.client.attendance(education_id)) + + async def keep_alive(self) -> None: + """Nothing to do: this session is not kept alive by us.""" + + async def close(self) -> None: + """The upstream has no logout that can be called without a browser.""" + + def today(self) -> Date: + return today() + + +class PetersburgProvider: + """The «Петербургское образование» diary.""" + + key = "petersburg" + title = "Санкт-Петербург" + genitive = "Санкт-Петербурга" + + async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest protocol + client = PetersburgClient() + return await client.login(request.login.strip(), request.password) + + def open(self, credential: str) -> PetersburgConnection: + return PetersburgConnection(credential) diff --git a/server/tests/test_netschool_client.py b/server/tests/test_netschool_client.py new file mode 100644 index 00000000..55a7b53e --- /dev/null +++ b/server/tests/test_netschool_client.py @@ -0,0 +1,212 @@ +"""The «Сетевой город» client, against a mock transport. + +Nothing here reaches a live server. A routing handler answers each `/webapi` +path the sign-in and the reads touch, and the tests pin the things the review +said must hold: the credential holds a session and never a password, a wrong +password is BadCredentials, a Госуслуги-only region refuses before any password +is sent, a blocked address is its own error, the token never rides in a URL, +and two families' cookies never meet on the shared client. +""" + +from __future__ import annotations + +import json + +import httpx +import pytest + +from app.providers.diary import http as diary_http +from app.providers.diary.errors import ( + AddressRefused, + BadCredentials, + SessionExpired, + SignInUnsupported, +) +from app.providers.netschool import client as nsclient +from app.providers.netschool.provider import NetSchoolProvider +from app.providers.netschool.regions import get as region_for + + + +LOGINDATA_OK = {"productName": "Сетевой Город. Образование", "version": "5.58.0", + "schoolLogin": True, "esiaMainAuth": False, "cacheVer": "639"} + + +def _login_success_routes(recorder: list[httpx.Request]): + """A handler that walks a whole password sign-in and bootstrap to success.""" + + def handler(request: httpx.Request) -> httpx.Response: + recorder.append(request) + path = request.url.path + if path == "/webapi/logindata": + return httpx.Response(200, json=LOGINDATA_OK, + headers={"set-cookie": "NSSESSIONID=sess-A; Path=/"}) + if path == "/webapi/auth/getdata": + return httpx.Response(200, json={"lt": "111", "ver": "222", "salt": "333"}) + if path == "/webapi/login": + return httpx.Response(200, json={"at": "at-A", "timeOut": 900000, + "accountInfo": {"user": {"id": 1}}}) + if path == "/webapi/student/diary/init": + return httpx.Response(200, json={"students": [ + {"studentId": 11, "nickName": "Иванов Иван", "classId": 3}]}) + if path == "/webapi/years/current": + return httpx.Response(200, json={"id": 2026, "startDate": "2026-09-01", + "endDate": "2027-05-31"}) + if path == "/webapi/context": + return httpx.Response(200, json={"organizationName": "Школа № 1"}) + if path == "/webapi/grade/assignment/types": + return httpx.Response(200, json=[{"id": 3, "name": "Домашнее задание"}]) + return httpx.Response(404, json={}) + + return handler + + +def _install(monkeypatch, handler): + real = httpx.AsyncClient + + def build(**kwargs): + return real(**kwargs, transport=httpx.MockTransport(handler)) + + monkeypatch.setattr(diary_http.httpx, "AsyncClient", build) + + +async def test_sign_in_seals_a_session_and_never_the_password(monkeypatch): + reqs: list[httpx.Request] = [] + _install(monkeypatch, _login_success_routes(reqs)) + await nsclient.close_client() + try: + cred = await NetSchoolProvider().sign_in(_req("parent", "hunter2", "zabaikalsky", 42)) + finally: + await nsclient.close_client() + + session = json.loads(cred) + assert session["at"] == "at-A" + assert session["cookies"]["NSSESSIONID"] == "sess-A" + assert session["year_id"] == 2026 + assert session["year_start"] == "2026-09-01" + assert session["types"] == {"3": "Домашнее задание"} + assert session["time_out"] == 900000 + # No password, and no hash of it, anywhere in the sealed credential. + assert "hunter2" not in cred + for key in ("pw", "pw2", "password"): + assert key not in session + # The login form posted pw/pw2, but never the raw password. + login_req = next(r for r in reqs if r.url.path == "/webapi/login") + body = login_req.content.decode() + assert "hunter2" not in body and "pw2=" in body + + +async def test_the_token_never_rides_in_a_url(monkeypatch): + reqs: list[httpx.Request] = [] + _install(monkeypatch, _login_success_routes(reqs)) + await nsclient.close_client() + try: + cred = await NetSchoolProvider().sign_in(_req("parent", "hunter2", "zabaikalsky", 42)) + conn = NetSchoolProvider().open(cred) + await conn.keep_alive() + finally: + await nsclient.close_client() + + for r in reqs: + assert "at-A" not in str(r.url) + assert "sess-A" not in str(r.url) + assert "hunter2" not in str(r.url) + + +async def test_a_wrong_password_is_bad_credentials(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/webapi/logindata": + return httpx.Response(200, json=LOGINDATA_OK) + if request.url.path == "/webapi/auth/getdata": + return httpx.Response(200, json={"lt": "1", "ver": "2", "salt": "3"}) + if request.url.path == "/webapi/login": + return httpx.Response(409, json={"message": "Неверный пароль"}) + return httpx.Response(404, json={}) + + _install(monkeypatch, handler) + await nsclient.close_client() + try: + with pytest.raises(BadCredentials): + await NetSchoolProvider().sign_in(_req("parent", "wrong", "zabaikalsky", 42)) + finally: + await nsclient.close_client() + + +async def test_a_esia_only_region_refuses_before_any_password(monkeypatch): + seen: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request.url.path) + if request.url.path == "/webapi/logindata": + return httpx.Response(200, json={**LOGINDATA_OK, "schoolLogin": False}) + return httpx.Response(200, json={}) + + _install(monkeypatch, handler) + await nsclient.close_client() + try: + with pytest.raises(SignInUnsupported): + # ingushetia allows passwords in the table, but this server says no. + await NetSchoolProvider().sign_in(_req("parent", "hunter2", "ingushetia", 42)) + finally: + await nsclient.close_client() + assert "/webapi/auth/getdata" not in seen and "/webapi/login" not in seen + + +async def test_a_blocked_address_is_address_refused(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, text="

Доступ к сайту запрещён

", + headers={"content-type": "text/html"}) + + _install(monkeypatch, handler) + await nsclient.close_client() + try: + with pytest.raises(AddressRefused): + await NetSchoolProvider().sign_in(_req("parent", "hunter2", "zabaikalsky", 42)) + finally: + await nsclient.close_client() + + +async def test_a_dead_session_answers_session_expired(monkeypatch): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(401, json={}) + + _install(monkeypatch, handler) + await nsclient.close_client() + region = region_for("zabaikalsky") + conn = NetSchoolProvider().open(json.dumps( + {"v": 1, "region": "zabaikalsky", "school_id": 42, "at": "old", "year_id": 2026, + "year_start": "2026-09-01", "year_end": "2027-05-31", "cookies": {}})) + try: + with pytest.raises(SessionExpired): + await conn.keep_alive() + finally: + await nsclient.close_client() + assert region is not None + + +async def test_two_families_cookies_never_meet_on_the_shared_client(monkeypatch): + cookies_seen: list[str | None] = [] + + def handler(request: httpx.Request) -> httpx.Response: + cookies_seen.append(request.headers.get("cookie")) + return httpx.Response(200, json={"students": []}, + headers={"set-cookie": "NSSESSIONID=leak; Path=/"}) + + _install(monkeypatch, handler) + await nsclient.close_client() + region = region_for("zabaikalsky") + a = nsclient.NetSchoolClient(region, {"at": "at-A", "cookies": {"NSSESSIONID": "sess-A"}}) + b = nsclient.NetSchoolClient(region, {"at": "at-B", "cookies": {"NSSESSIONID": "sess-B"}}) + try: + await a.diary_init() + await b.diary_init() + finally: + await nsclient.close_client() + # B's request carries only B's session, never A's leaked Set-Cookie. + assert cookies_seen == ["NSSESSIONID=sess-A", "NSSESSIONID=sess-B"] + + +def _req(login, password, region, school_id): + from app.providers.diary.base import SignInRequest + + return SignInRequest(login=login, password=password, region=region, school_id=school_id) diff --git a/server/tests/test_netschool_mapper.py b/server/tests/test_netschool_mapper.py new file mode 100644 index 00000000..3b6b76a5 --- /dev/null +++ b/server/tests/test_netschool_mapper.py @@ -0,0 +1,125 @@ +"""The «Сетевой город» mapper, on hand-written payloads. + +No network and no live server: every shape here is written by hand from the +open clients (`docs/diaries/netschool.md`), which is the only evidence there +is. The point is that our models come out right, and that a single bad row is +dropped rather than raising. +""" + +from __future__ import annotations + +from datetime import date + +from app.providers.diary.models import MarkKind +from app.providers.netschool import mapper as m + +# One week's /webapi/student/diary, trimmed to what the mapper reads. +WEEK = { + "className": "6г", + "termName": "2 четверть", + "weekDays": [ + { + "date": "2026-11-30T00:00:00", + "lessons": [ + { + "number": 1, + "subjectName": "Алгебра", + "startTime": "09:00", + "endTime": "09:45", + "room": "312", + "assignments": [ + {"id": 5, "typeId": 3, "assignmentName": "§14, №3-5", + "dueDate": "2026-12-02T00:00:00"}, + {"id": 6, "typeId": 10, "assignmentName": "Ответ у доски", + "mark": {"mark": 5, "dutyMark": False}, + "markComment": {"name": "Отлично"}}, + ], + }, + { + "number": 2, + "subjectName": "", # empty subject: the row is hidden + "assignments": [], + }, + { + "number": 3, + "subjectName": "Химия", + "startTime": "10:00:00", # HH:MM:SS form + "endTime": "10:45:00", + "assignments": [ + {"id": 7, "typeId": 4, "assignmentName": "К/р", + "mark": {"dutyMark": True}}, # a debt, «·», not a grade + ], + }, + ], + } + ], +} + +TYPES = {"3": "Домашнее задание", "4": "Контрольная работа", "10": "Ответ на уроке"} + + +def test_lessons_drop_the_empty_subject_and_read_both_time_forms(): + lessons = m.to_lessons(WEEK, date(2026, 11, 30), date(2026, 12, 6)) + assert [l.subject for l in lessons] == ["Алгебра", "Химия"] + algebra, chem = lessons + assert algebra.number == 1 + assert algebra.starts_at.isoformat() == "09:00:00" + assert algebra.room == "312" + assert algebra.homework == "§14, №3-5" # only typeId==3 + assert chem.starts_at.isoformat() == "10:00:00" + + +def test_homework_is_addressed_to_its_due_day(): + hw = m.to_homework(WEEK, date(2026, 11, 30), date(2026, 12, 6)) + assert len(hw) == 1 + assert hw[0].due_date == date(2026, 12, 2) + assert hw[0].subject == "Алгебра" + assert hw[0].text == "§14, №3-5" + + +def test_marks_read_grade_and_duty_and_name_the_reason(): + marks = m.to_marks(WEEK, TYPES, date(2026, 11, 30), date(2026, 12, 6)) + assert len(marks) == 2 + grade, duty = marks + assert (grade.value, grade.kind, grade.reason) == ("5", MarkKind.GRADE, "Ответ на уроке") + assert grade.comment == "Отлично" + assert (duty.value, duty.kind) == ("·", MarkKind.OTHER) + + +def test_a_week_is_filtered_to_the_requested_range(): + # Ask only for 1 December: the 30 November rows fall outside. + assert m.to_lessons(WEEK, date(2026, 12, 1), date(2026, 12, 6)) == [] + + +def test_students_keep_the_whole_display_name_and_accept_a_dict(): + as_list = {"students": [{"studentId": 11, "nickName": "Иванов Иван", "classId": 3, + "className": None}], "currentStudentId": 11} + as_dict = {"students": {"0": {"studentId": 11, "nickName": "Иванов Иван", "classId": 3}}} + for payload in (as_list, as_dict): + students = m.to_students(payload, "Школа № 1") + assert len(students) == 1 + assert students[0].id == 11 == students[0].education_id + assert students[0].group_id == 3 + assert students[0].full_name == "Иванов Иван" + assert students[0].school == "Школа № 1" + + +def test_a_wholly_unreadable_children_answer_raises(): + import pytest + + with pytest.raises(m.UnexpectedResponseError): + m.to_students({"students": "nonsense"}, None) + + +def test_periods_mark_the_term_holding_today(): + terms = [ + {"id": 1, "termName": "1 четверть", "startDate": "2026-09-01", "endDate": "2026-10-26"}, + {"id": 2, "termName": "2 четверть", "startDate": "2026-11-05", "endDate": "2026-12-28"}, + ] + periods = m.to_periods(terms, date(2026, 11, 30)) + current = [p for p in periods if p.is_current] + assert len(current) == 1 and current[0].id == 2 + + +def test_attendance_is_always_empty(): + assert m.to_attendance() == [] From f6b3f2f4c189fc62c8a98b1815e6c6fea96e9683 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 21:31:50 +0000 Subject: [PATCH 02/30] Dispatch the diary service by provider, and let the API sign in to either MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The diary service built a Petersburg client directly; now it opens whichever provider the session row names and calls it through the shared connection contract, re-sealing a rotated credential on the way out (even when the answer that carried it failed to map, so the next call does not replay the old one). "today" comes from the provider, so «Сетевой город» gets its region's zone. Corrections are still keyed by the login, but a «Сетевой город» login is unique only on its own regional server, so for any provider but Petersburg the key folds in the provider and region through a hash — Petersburg's key is the bare case-folded login, unchanged, so every correction filed before stays matched. Signing out now tells the upstream goodbye where it can be told; «Сетевой город» has a logout that works without a browser and Petersburg does not, so its connection's close is a no-op. - POST /api/v1/diary/login accepts an optional provider, region and school. Absent provider is Petersburg, so an older phone is unchanged. A «Сетевой город» region must be an allow-listed, password-capable key and the school a positive id, both checked before any upstream call; a Госуслуги-only region or a blocked address answers 503 and the login limiter does not count it. - Revision 0015 adds diary_sessions.provider/region and the keep-alive clocks, and classes.diary_region/diary_school_id/diary_school_name — seven nullable columns, additive, applied before the merge, with a rollback step that expires non-Petersburg sessions first. EXPECTED_REVISION is 0015. Part of #139. The bot binding, the web form's provider text and the cron keep-alive follow. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/diary.py | 102 +++++++-- server/app/db.py | 2 +- server/app/models.py | 28 +++ server/app/schemas.py | 7 + server/app/services/diary.py | 208 +++++++++++------- .../versions/0015_diary_provider_columns.py | 101 +++++++++ server/tests/test_services.py | 2 +- 7 files changed, 358 insertions(+), 92 deletions(-) create mode 100644 server/migrations/versions/0015_diary_provider_columns.py diff --git a/server/app/api/diary.py b/server/app/api/diary.py index 32e526fc..cd0d2545 100644 --- a/server/app/api/diary.py +++ b/server/app/api/diary.py @@ -24,13 +24,15 @@ from app.api.public import MAX_BUNDLE_START, MIN_BUNDLE_START, caller_bucket from app.api.routing import DishkaAnnotatedRoute from app.models import DiarySession -from app.providers.petersburg import ( +from app.providers.diary.errors import ( BadCredentials, - PetersburgError, + DiaryError, SessionExpired, + SignInUnsupported, UnexpectedResponse, UpstreamUnavailable, ) +from app.providers.diary.registry import NETSCHOOL, PETERSBURG from app.providers.petersburg import ( today as diary_today, ) @@ -73,15 +75,20 @@ MAX_DATE = MAX_BUNDLE_START -def _range(date_from: Date | None, date_to: Date | None) -> tuple[Date, Date]: +def _range( + date_from: Date | None, date_to: Date | None, today: Date | None = None +) -> tuple[Date, Date]: for day in (date_from, date_to): if day is not None and not (MIN_DATE <= day <= MAX_DATE): raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"dates must be between {MIN_DATE.isoformat()} and {MAX_DATE.isoformat()}", ) - # The diary's own day, not the server's: see `petersburg.TIMEZONE`. - start = date_from or diary_today() + # The diary's own day, not the server's — the provider's, so «Сетевой + # город» gets its region's zone and Petersburg its city's. The default is + # Petersburg's when a caller passes no `today`, which keeps the standalone + # `_range(None, None)` behaviour its test pins. + start = date_from or today or diary_today() end = date_to or start + timedelta(days=DEFAULT_RANGE_DAYS) if end < start: raise HTTPException( @@ -156,7 +163,17 @@ async def _guard(awaitable): detail=failure.message, headers={"X-Diary-Reauth": "required"}, ) from failure + except SignInUnsupported as failure: + # The region takes only Госуслуги. A 503 rather than a 401, because it + # is not the password and there is nothing to retry — and so that the + # login limiter, which forgives only a 503, does not count an attempt + # where nothing looked at a password. + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=failure.message + ) from failure except UpstreamUnavailable as failure: + # AddressRefused is a subclass and lands here too: a 503, uncounted, + # carrying its own «дело не в пароле» message. raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=failure.message ) from failure @@ -164,7 +181,7 @@ async def _guard(awaitable): raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail=failure.message ) from failure - except PetersburgError as failure: + except DiaryError as failure: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail=failure.message ) from failure @@ -195,6 +212,39 @@ async def _guard(awaitable): diary_login_limiter = JoinThrottle(limit=10, window=900.0) +def _resolve_login_target(payload: DiaryLoginIn) -> tuple[str, str | None, int | None]: + """The provider, region and school to sign in with, validated locally. + + Absent provider is Petersburg, so an older phone that sends only a login and + a password is unchanged. For «Сетевой город» the region must be an + allow-listed key that still takes a password and the school a positive id — + checked here, before any upstream call, so a bad target is a 422 and never a + request to a region we do not serve. + """ + provider = payload.provider or PETERSBURG + if provider == PETERSBURG: + return PETERSBURG, None, None + if provider == NETSCHOOL: + from app.providers.netschool import regions + + region = regions.get(payload.region) + if region is None or not region.password: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Unknown or unsupported region for «Сетевой город»", + ) + if payload.school_id is None: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="A school id is required for «Сетевой город»", + ) + return NETSCHOOL, region.key, payload.school_id + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"Unknown diary provider {provider!r}", + ) + + @router.post("/login", response_model=DiaryLoginOut) async def login( request: Request, @@ -224,8 +274,19 @@ async def login( headers={"Retry-After": str(int(retry_after) + 1)}, ) + provider, region, school_id = _resolve_login_target(payload) + try: - token, row = await _guard(service.sign_in(session, payload.login, payload.password)) + token, row = await _guard( + service.sign_in( + session, + payload.login, + payload.password, + provider=provider, + region=region, + school_id=school_id, + ) + ) except service.DiaryDisabled as failure: # No ``DIARY_SECRET``, so the feature is off — see ``app/crypto.py`` # for why that is a refusal rather than a fallback. ``_guard`` knows @@ -308,9 +369,11 @@ async def schedule( session: FromDishka[AsyncSession], ) -> list[DiaryLessonOut]: student = await _student(svc, student_id) - start, end = _range(date_from, date_to) + start, end = _range(date_from, date_to, svc.today()) lessons = await _guard(svc.schedule(student.education_id, start, end)) - corrections = await service.load_corrections(session, row.login, student_id) + corrections = await service.load_corrections( + session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region + ) return [ DiaryLessonOut.of(overlaid) for overlaid in overrides.overlay_lessons(lessons, corrections) @@ -333,9 +396,11 @@ async def homework( that, so the provider pulls it out and this endpoint exists. """ student = await _student(svc, student_id) - start, end = _range(date_from, date_to) + start, end = _range(date_from, date_to, svc.today()) items = await _guard(svc.homework(student.education_id, start, end)) - corrections = await service.load_corrections(session, row.login, student_id) + corrections = await service.load_corrections( + session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region + ) return [ DiaryHomeworkOut.of(overlaid) for overlaid in overrides.overlay_homework(items, corrections) @@ -350,7 +415,7 @@ async def grades( svc: service.DiaryService = Depends(_service), ) -> list[DiaryMarkOut]: student = await _student(svc, student_id) - start, end = _range(date_from, date_to) + start, end = _range(date_from, date_to, svc.today()) marks = await _guard(svc.marks(student.education_id, start, end)) return [DiaryMarkOut.of(mark) for mark in marks] @@ -435,7 +500,9 @@ async def list_overrides( ) -> list[DiaryOverrideOut]: """Every correction this account has made for this child.""" await _student(svc, student_id) - found = await service.list_overrides(session, row.login, student_id) + found = await service.list_overrides( + session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region + ) return [DiaryOverrideOut.of(item) for item in found] @@ -486,6 +553,8 @@ async def put_override( field=payload.field, value=payload.value, original=payload.original, + provider=row.provider or PETERSBURG, + region=row.region, ) return DiaryOverrideOut.of(stored) @@ -514,7 +583,8 @@ async def reset_override( """ await _student(svc, student_id) await service.drop_override( - session, row.login, student_id, payload.target, payload.field + session, row.login, student_id, payload.target, payload.field, + provider=row.provider or PETERSBURG, region=row.region, ) @@ -531,4 +601,6 @@ async def reset_all_overrides( ) -> None: """Resets every correction for this child. The diary answers for itself again.""" await _student(svc, student_id) - await service.drop_overrides(session, row.login, student_id) + await service.drop_overrides( + session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region + ) diff --git a/server/app/db.py b/server/app/db.py index e86fc61a..9fbbc6e5 100644 --- a/server/app/db.py +++ b/server/app/db.py @@ -134,7 +134,7 @@ def rows_affected(result: Any) -> int: #: inside a request. A constant that has to be kept in step by hand would rot, #: so ``tests/test_schema_version.py`` pins it to the real head and fails the #: build if a new revision lands without updating it. -EXPECTED_REVISION = "0014" +EXPECTED_REVISION = "0015" async def current_revision(session: AsyncSession) -> str | None: diff --git a/server/app/models.py b/server/app/models.py index eec48f3f..ebab84f4 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -217,6 +217,16 @@ class SchoolClass(Base): # *member* a way to sign in to their own account and read their own diary # in the same chat — which is why nothing here holds a credential. diary_provider: Mapped[str | None] = mapped_column(String(32)) + # For a provider that serves many regional servers — «Сетевой город» — + # which one this class reads, and which school on it. NULL for Petersburg, + # whose one server needs neither. The region is a key into the provider's + # own allow-list, never a URL; the id is the upstream's own `scid`; the name + # is what the class card and the sign-in form show. Added by 0015. + diary_region: Mapped[str | None] = mapped_column(String(32)) + # No foreign key — it is a foreign system's id — so BigInteger, per the + # hardening rule for any *_id column that does not reference a table here. + diary_school_id: Mapped[int | None] = mapped_column(BigInteger) + diary_school_name: Mapped[str | None] = mapped_column(String(300)) # `is_public` used to sit here. It was toggled from «⚙️ Класс», printed on # the card as «публичный / закрытый», and read by nothing at all: an admin # who closed the class closed nothing, and the screen told them otherwise. @@ -790,8 +800,26 @@ class DiarySession(Base): # account can carry several; the bot asks once and remembers, because # asking on every screen is a question with the same answer every time. student_id: Mapped[int | None] = mapped_column(BigInteger) + # Which diary this session is with. NULL means a row written before 0015, + # which is Petersburg — a string, not an SAEnum, so a new provider is a + # value and not a migration, and never a `.value` server_default (an enum + # column stores the member NAME, and that has taken the bot down once). + provider: Mapped[str | None] = mapped_column(String(32)) + # For a many-server provider, which regional server this session is on, so + # a session can be matched to its class's binding and grouped per origin + # for the keep-alive without unsealing the credential. NULL for Petersburg. + region: Mapped[str | None] = mapped_column(String(32)) created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) last_used_at: Mapped[datetime | None] = mapped_column(DateTime) + # The keep-alive's own clocks, kept apart from last_used_at so pinging a + # session never looks like the family using it (which would defeat the + # 30-day purge of one nobody opens). `kept_alive_at` / `upstream_ok_at` is + # the last successful ping / any successful upstream contact; + # `keepalive_attempted_at` is the last attempt whatever its outcome, so the + # tick can order by it and a failing origin cannot sit at the head forever. + kept_alive_at: Mapped[datetime | None] = mapped_column(DateTime) + keepalive_attempted_at: Mapped[datetime | None] = mapped_column(DateTime) + upstream_ok_at: Mapped[datetime | None] = mapped_column(DateTime) # When the upstream refused us and the person has to sign in again. expired_at: Mapped[datetime | None] = mapped_column(DateTime) diff --git a/server/app/schemas.py b/server/app/schemas.py index b44617ef..38743ca9 100644 --- a/server/app/schemas.py +++ b/server/app/schemas.py @@ -569,6 +569,13 @@ class DiaryLoginIn(BaseModel): login: str = Field(min_length=3, max_length=200) password: str = Field(min_length=1, max_length=200) + #: Which diary. Absent means Petersburg, so an older phone that sends only a + #: login and a password still signs in there. For «Сетевой город» the region + #: is a key into the allow-list and the school is the upstream's own id; + #: both are validated in the route before any upstream call. + provider: str | None = Field(default=None, max_length=32) + region: str | None = Field(default=None, max_length=32) + school_id: int | None = Field(default=None, ge=1, le=2_000_000_000) @field_validator("login") @classmethod diff --git a/server/app/services/diary.py b/server/app/services/diary.py index 0b310c38..4f1a72a4 100644 --- a/server/app/services/diary.py +++ b/server/app/services/diary.py @@ -16,10 +16,10 @@ from __future__ import annotations +import hashlib import logging from datetime import UTC, datetime from datetime import date as Date -from typing import Any from sqlalchemy import delete as sa_delete from sqlalchemy import select @@ -29,15 +29,9 @@ from app.crypto import diary_enabled, seal, unseal from app.db import rows_affected from app.models import DiaryOverride, DiarySession -from app.providers.petersburg import ( - PetersburgClient, - SessionExpired, -) -from app.providers.petersburg import mapper as m -from app.providers.petersburg import ( - today as upstream_today, -) -from app.providers.petersburg.models import ( +from app.providers.diary.base import SignInRequest +from app.providers.diary.errors import DiaryError, SessionExpired +from app.providers.diary.models import ( AcademicPeriod, AttendanceEvent, DiaryLesson, @@ -47,6 +41,7 @@ Subject, Teacher, ) +from app.providers.diary.registry import PETERSBURG, provider_for from app.security import hash_token, new_token log = logging.getLogger(__name__) @@ -71,9 +66,16 @@ def utcnow() -> datetime: async def sign_in( - session: AsyncSession, login: str, password: str, telegram_id: int | None = None + session: AsyncSession, + login: str, + password: str, + telegram_id: int | None = None, + *, + provider: str = PETERSBURG, + region: str | None = None, + school_id: int | None = None, ) -> tuple[str, DiarySession]: - """Logs in upstream and opens a session of ours. + """Logs in upstream through the named provider and opens a session of ours. @return the token to hand the client - shown once, stored only as a hash - and the row behind it. @@ -85,16 +87,27 @@ async def sign_in( if not diary_enabled(): raise DiaryDisabled("DIARY_SECRET is not configured") - client = PetersburgClient() - upstream = await client.login(login.strip(), password) + impl = provider_for(provider) + if impl is None: + # A provider key no implementation answers. Callers validate first, so + # this is a programming error, not a user's. + raise ValueError(f"unknown diary provider {provider!r}") + + credential = await impl.sign_in( + SignInRequest( + login=login.strip(), password=password, region=region, school_id=school_id + ) + ) token = new_token() row = DiarySession( token_hash=hash_token(token), # Sealed before it is ever handed to the session, so there is no path # through this function on which the plaintext reaches the ORM. - upstream_token=seal(upstream), + upstream_token=seal(credential), login=login.strip(), + provider=provider, + region=region, telegram_id=telegram_id, last_used_at=utcnow(), ) @@ -144,10 +157,10 @@ async def find_session(session: AsyncSession, token: str) -> DiarySession | None # correction must not. -def owner_key(login: str) -> str: +def owner_key(login: str, provider: str = PETERSBURG, region: str | None = None) -> str: """The form of a login that corrections are filed under. - Case-folded, because the upstream does not care: a family that signed in as + Case-folded, because an upstream does not care: a family that signed in as ``Ivan@mail.ru`` and later types ``ivan@mail.ru`` lands in the same account there, and must land on the same corrections here. Keyed on the raw string, every one of them would vanish the first time somebody's keyboard @@ -156,12 +169,26 @@ def owner_key(login: str) -> str: The row's own ``login`` stays as it was typed: it is what «вы вошли как» prints, and that should say what the person wrote. + + **Petersburg's key is the bare case-folded login, unchanged**, so every + correction filed before there was a second provider still matches. For any + other provider a login is unique only on its own regional server, so the + key folds in the provider and region — through a hash, because + ``login:region:`` prefixes would push a 200-character login past the + ``DiaryOverride.login`` column, and a family whose corrections silently + stopped saving would have no way to see why. The hash is 71 characters, so + it always fits and never collides. """ - return login.strip().casefold() + folded = login.strip().casefold() + if provider == PETERSBURG: + return folded + digest = hashlib.sha256(f"{region}\0{folded}".encode()).hexdigest() + return f"{provider}:{digest}" async def load_corrections( - session: AsyncSession, login: str, student_id: int + session: AsyncSession, login: str, student_id: int, + *, provider: str = PETERSBURG, region: str | None = None ) -> dict[str, dict[str, tuple[str, str | None]]]: """Every correction for one child, shaped the way the overlay wants it. @@ -171,7 +198,7 @@ async def load_corrections( """ rows = await session.scalars( select(DiaryOverride).where( - DiaryOverride.login == owner_key(login), + DiaryOverride.login == owner_key(login, provider, region), DiaryOverride.student_id == student_id, ) ) @@ -182,13 +209,14 @@ async def load_corrections( async def list_overrides( - session: AsyncSession, login: str, student_id: int + session: AsyncSession, login: str, student_id: int, + *, provider: str = PETERSBURG, region: str | None = None ) -> list[DiaryOverride]: """The raw rows, for the screen that lists and resets them.""" rows = await session.scalars( select(DiaryOverride) .where( - DiaryOverride.login == owner_key(login), + DiaryOverride.login == owner_key(login, provider, region), DiaryOverride.student_id == student_id, ) .order_by(DiaryOverride.target, DiaryOverride.field) @@ -204,6 +232,7 @@ async def put_override( field: str, value: str, original: str | None, + *, provider: str = PETERSBURG, region: str | None = None ) -> DiaryOverride: """Writes a correction, replacing the one that was there. @@ -213,7 +242,7 @@ async def put_override( """ row = await session.scalar( select(DiaryOverride).where( - DiaryOverride.login == owner_key(login), + DiaryOverride.login == owner_key(login, provider, region), DiaryOverride.student_id == student_id, DiaryOverride.target == target, DiaryOverride.field == field, @@ -227,7 +256,7 @@ async def put_override( return row row = DiaryOverride( - login=owner_key(login), + login=owner_key(login, provider, region), student_id=student_id, target=target, field=field, @@ -247,7 +276,7 @@ async def put_override( await session.rollback() row = await session.scalar( select(DiaryOverride).where( - DiaryOverride.login == owner_key(login), + DiaryOverride.login == owner_key(login, provider, region), DiaryOverride.student_id == student_id, DiaryOverride.target == target, DiaryOverride.field == field, @@ -263,12 +292,13 @@ async def put_override( async def drop_override( - session: AsyncSession, login: str, student_id: int, target: str, field: str + session: AsyncSession, login: str, student_id: int, target: str, field: str, + *, provider: str = PETERSBURG, region: str | None = None ) -> bool: """Resets one field. @return whether there was anything to reset.""" row = await session.scalar( select(DiaryOverride).where( - DiaryOverride.login == owner_key(login), + DiaryOverride.login == owner_key(login, provider, region), DiaryOverride.student_id == student_id, DiaryOverride.target == target, DiaryOverride.field == field, @@ -281,9 +311,12 @@ async def drop_override( return True -async def drop_overrides(session: AsyncSession, login: str, student_id: int) -> int: +async def drop_overrides( + session: AsyncSession, login: str, student_id: int, + *, provider: str = PETERSBURG, region: str | None = None +) -> int: """Resets everything for one child. @return how many were dropped.""" - rows = await list_overrides(session, login, student_id) + rows = await list_overrides(session, login, student_id, provider=provider, region=region) for row in rows: await session.delete(row) if rows: @@ -291,9 +324,29 @@ async def drop_overrides(session: AsyncSession, login: str, student_id: int) -> return len(rows) +async def _tell_upstream_goodbye(row: DiarySession) -> None: + """Best-effort logout upstream before we forget a session. + + Petersburg has no logout that works without a browser, so its connection's + ``close`` does nothing; «Сетевой город» has one, and leaving a session live + when the family pressed «Выйти» is exactly what its `close` prevents. + Nothing here may raise: we are forgetting the row regardless. + """ + provider = provider_for(row.provider or PETERSBURG) + if provider is None: + return + credential = upstream_of(row) + if not credential: + return + try: + await provider.open(credential).close() + except Exception: # noqa: BLE001 - we are leaving; an upstream failure is fine + log.info("diary logout upstream failed for session %s", row.id, exc_info=True) + + async def sign_out(session: AsyncSession, row: DiarySession) -> None: - """Forgets the session. The upstream is not told: it has no logout that - can be called without a browser, and its token expires on its own.""" + """Forgets the session, telling the upstream first where it can be told.""" + await _tell_upstream_goodbye(row) await session.delete(row) await session.commit() @@ -314,6 +367,16 @@ async def sign_out_here( Scoped to the one class on purpose: a parent in two of them is signing out of one child, not both. @return how many rows went. """ + rows = list( + await session.scalars( + select(DiarySession).where( + DiarySession.telegram_id == telegram_id, + DiarySession.class_id == class_id, + ) + ) + ) + for row in rows: + await _tell_upstream_goodbye(row) result = await session.execute( sa_delete(DiarySession).where( DiarySession.telegram_id == telegram_id, @@ -355,7 +418,7 @@ class DiaryService: that should have lived for weeks dies in a day. """ - __slots__ = ("session", "row", "client", "_upstream") + __slots__ = ("session", "row", "connection", "_credential") def __init__(self, session: AsyncSession, row: DiarySession) -> None: self.session = session @@ -364,76 +427,70 @@ def __init__(self, session: AsyncSession, row: DiarySession) -> None: # empty string when the seal will not open, which every call then turns # into the upstream's own «signed out» — the same ending the person # would reach a few days later anyway. - self._upstream = upstream_of(row) or "" - self.client = PetersburgClient(self._upstream) + self._credential = upstream_of(row) or "" + provider = provider_for(row.provider or PETERSBURG) + # An unknown provider is treated like an unreadable seal: `find_session` + # and the bot's `_session_for` expire such a row before building this, + # so this fallback is only ever reached in a test that skips them. + provider = provider or provider_for(PETERSBURG) + self.connection = provider.open(self._credential) # type: ignore[union-attr] async def students(self) -> list[Student]: - return await self._call(lambda: self.client.children(), m.to_students) + return await self._call(self.connection.students()) async def periods(self, group_id: int) -> list[AcademicPeriod]: - # The upstream's own clock, not the server's. This decides which - # term is «текущая», and `api/diary.py` answers «какие предметы» - # with nothing at all when no period is current — so on the evening of - # the day a quarter opens, a server running in UTC (which Vercel does) - # was still in yesterday, which is a holiday, and the subjects screen - # came back empty. Every other "today" in this project comes from - # `SchoolClass.timezone`; a diary session has no class behind it, and - # `petersburg.today()` is the clock of the one city whose diary this is. - today = upstream_today() - return await self._call( - lambda: self.client.periods(group_id), lambda items: m.to_periods(items, today) - ) + return await self._call(self.connection.periods(group_id)) async def subjects(self, group_id: int, period_id: int) -> list[Subject]: - return await self._call( - lambda: self.client.subjects(group_id, period_id), m.to_subjects - ) + return await self._call(self.connection.subjects(group_id, period_id)) async def teachers(self, education_id: int) -> list[Teacher]: - return await self._call(lambda: self.client.teachers(education_id), m.to_teachers) + return await self._call(self.connection.teachers(education_id)) async def marks(self, education_id: int, date_from: Date, date_to: Date) -> list[Mark]: - return await self._call( - lambda: self.client.marks(education_id, date_from, date_to), m.to_marks - ) + return await self._call(self.connection.marks(education_id, date_from, date_to)) async def schedule( self, education_id: int, date_from: Date, date_to: Date ) -> list[DiaryLesson]: - return await self._call( - lambda: self.client.schedule(education_id, date_from, date_to), m.to_lessons - ) - - async def lessons( - self, education_id: int, date_from: Date, date_to: Date - ) -> list[DiaryLesson]: - return await self._call( - lambda: self.client.lessons(education_id, date_from, date_to), m.to_lessons - ) + return await self._call(self.connection.schedule(education_id, date_from, date_to)) async def homework( self, education_id: int, date_from: Date, date_to: Date ) -> list[HomeworkItem]: - return await self._call( - lambda: self.client.lessons(education_id, date_from, date_to), m.to_homework - ) + return await self._call(self.connection.homework(education_id, date_from, date_to)) async def attendance(self, education_id: int) -> list[AttendanceEvent]: - return await self._call(lambda: self.client.attendance(education_id), m.to_attendance) + return await self._call(self.connection.attendance(education_id)) + + def today(self) -> Date: + """The diary's own day, from the provider — one city's clock for + Petersburg, the region's zone for «Сетевой город».""" + return self.connection.today() # ---- plumbing ----------------------------------------------------- - async def _call(self, fetch, convert): + async def _call(self, awaitable): + """Run one provider read, then keep any refreshed credential. + + A ``SessionExpired`` expires the row and is re-raised untouched — the + route turns it into the re-sign-in signal. Any other provider failure + still re-seals first: the answer that failed to read may have carried a + rotated token, and dropping it would replay the old one next call. + """ try: - items: list[dict[str, Any]] = await fetch() + result = await awaitable except SessionExpired: await self._expire() raise + except DiaryError: + await self._remember_token() + raise await self._remember_token() - return convert(items) + return result async def _remember_token(self) -> None: - """Stores a refreshed upstream token, and the fact we were here. + """Stores a refreshed upstream credential, and the fact we were here. Both writes are the same transaction and neither is worth failing a read over, so a failure here is logged and swallowed - the answer the @@ -441,9 +498,10 @@ async def _remember_token(self) -> None: """ now = utcnow() changed = False - if self.client.token and self.client.token != self._upstream: - self._upstream = self.client.token - self.row.upstream_token = seal(self.client.token) + credential = self.connection.credential + if credential and credential != self._credential: + self._credential = credential + self.row.upstream_token = seal(credential) changed = True last = self.row.last_used_at if last is None or (now - last).total_seconds() >= LAST_USED_INTERVAL_SECONDS: diff --git a/server/migrations/versions/0015_diary_provider_columns.py b/server/migrations/versions/0015_diary_provider_columns.py new file mode 100644 index 00000000..7140e9ba --- /dev/null +++ b/server/migrations/versions/0015_diary_provider_columns.py @@ -0,0 +1,101 @@ +"""Add the columns a second diary provider needs. + +Revision ID: 0015 +Revises: 0014 +Create Date: 2026-09-24 + +Until now there was one diary, Petersburg's, and a class carried only whether +it was bound (``classes.diary_provider``). A second provider, «Сетевой город», +serves many regional servers and keeps sessions alive from the cron tick, so a +session and a class each need a little more said about them: + +On ``diary_sessions``: + +- ``provider`` — which diary this session is with. ``NULL`` on every row + written before this revision, which means Petersburg. A string, not an enum, + so a third provider is a value and not a migration. +- ``region`` — for a many-server provider, which regional server, so a session + can be matched to its class's binding and grouped per origin for the + keep-alive without unsealing its credential. +- ``kept_alive_at`` / ``keepalive_attempted_at`` / ``upstream_ok_at`` — the + keep-alive's clocks, kept apart from ``last_used_at`` so that pinging a + session never looks like the family using it (which would defeat the 30-day + purge of one nobody opens). + +On ``classes``: + +- ``diary_region`` — the region key an admin bound, into the provider's own + allow-list, never a URL. +- ``diary_school_id`` — the upstream's own school id (``scid``); no foreign key + because it is a foreign system's id, so ``BigInteger``. +- ``diary_school_name`` — what the class card and the sign-in form show. + +**Destroys nothing.** Seven nullable columns with no default and no constraint. +The running code neither writes nor reads them, so every row inserted in the +window before the deploy lands has a ``NULL`` provider, which is Petersburg — +exactly what that code already assumes. + +**Apply this BEFORE the merge**, the ordinary additive order: it is the *new* +code that needs the columns, and the old code is happy without them. + +**Before rolling the code back past the merge** that carries this, expire any +non-Petersburg session first, or old code will read a «Сетевой город» +credential as Petersburg's and replay it against ``dnevnik2`` — one third +party's session handed to another: + + UPDATE diary_sessions SET expired_at = now() + WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL; + +``downgrade`` does exactly that before dropping the columns. + +The DDL is taken from the model, as ``CLAUDE.md`` requires: +``CreateTable(...).compile(dialect=postgresql.dialect())`` prints these column +types. Applied through the Neon connector, ``alembic_version`` stamped in the +same transaction; on local SQLite the columns arrive through ``create_all``. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "0015" +down_revision: str | None = "0014" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # Local SQLite only ever exists here through `create_all`, which builds + # every column the model declares; there is nothing to add. Postgres's + # alone, exactly as the additive revisions before this one. + if op.get_bind().dialect.name == "sqlite": + return + op.add_column("diary_sessions", sa.Column("provider", sa.String(length=32), nullable=True)) + op.add_column("diary_sessions", sa.Column("region", sa.String(length=32), nullable=True)) + op.add_column("diary_sessions", sa.Column("kept_alive_at", sa.DateTime(), nullable=True)) + op.add_column( + "diary_sessions", sa.Column("keepalive_attempted_at", sa.DateTime(), nullable=True) + ) + op.add_column("diary_sessions", sa.Column("upstream_ok_at", sa.DateTime(), nullable=True)) + op.add_column("classes", sa.Column("diary_region", sa.String(length=32), nullable=True)) + op.add_column("classes", sa.Column("diary_school_id", sa.BigInteger(), nullable=True)) + op.add_column("classes", sa.Column("diary_school_name", sa.String(length=300), nullable=True)) + + +def downgrade() -> None: + if op.get_bind().dialect.name == "sqlite": + return + # Expire any non-Petersburg session before the columns that tell it apart + # are gone, so the reverted code cannot replay its credential at the wrong + # upstream. The rows stay; expired ones are swept within a day. + op.execute( + "UPDATE diary_sessions SET expired_at = now() " + "WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL" + ) + for column in ("upstream_ok_at", "keepalive_attempted_at", "kept_alive_at", "region", "provider"): + op.drop_column("diary_sessions", column) + for column in ("diary_school_name", "diary_school_id", "diary_region"): + op.drop_column("classes", column) diff --git a/server/tests/test_services.py b/server/tests/test_services.py index a0ae1f47..c8fee547 100644 --- a/server/tests/test_services.py +++ b/server/tests/test_services.py @@ -1452,7 +1452,7 @@ def now(tz=None): await session.commit() service = diary_service.DiaryService(session, row) - service.client = _FakeDiaryClient( + service.connection.client = _FakeDiaryClient( [ { "identity": {"id": 1}, From 60f4bdb465a02bad568ae993cd6bcace3ffa6843 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 21:37:26 +0000 Subject: [PATCH 03/30] Fix the two diary defects, and name the provider on the sign-in form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #136: revoking a member left their diary sessions and any unspent sign-in ticket in the class. A session is reached only by (telegram_id, class_id), so after revocation nobody could sign it out, and with the coming keep-alive it would be held live upstream for the family for thirty days. The revoke handler now signs those sessions out (telling «Сетевой город» goodbye where it can be told) and drops the tickets, beside the connect codes and subscriptions it already dropped. #137: the sign-in form trusted the class's binding from when the ticket was minted. It now reads the binding at both the GET and the POST, before spending anything: a class unbound or rebound since the link was made refuses with 410 rather than sending the password to a diary the family is no longer looking at. The form's subtitle names the provider — and, for «Сетевой город», the region and school — every part escaped, because the school name comes from the upstream. Petersburg's page is byte-for-byte what it was. The web form's error mapping gains «Сетевой город»'s errors: a Госуслуги-only region or a blocked address hands the ticket back (nothing looked at the password), and an expired-password message is passed through rather than flattened to «неверный пароль». Closes #136 Closes #137 Part of #139. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/diary_web.py | 109 +++++++++++++++++--- server/app/bot/handlers/access.py | 13 ++- server/app/providers/diary/base.py | 1 + server/app/providers/netschool/provider.py | 1 + server/app/providers/petersburg/provider.py | 1 + server/app/services/diary_link.py | 16 +++ server/tests/test_diary_web.py | 4 + 7 files changed, 129 insertions(+), 16 deletions(-) diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index 1a0fff69..2b6b5667 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -47,8 +47,15 @@ from app.api.routing import DishkaAnnotatedRoute from app.crypto import diary_enabled -from app.models import DiaryLinkCode -from app.providers.petersburg import BadCredentials, PetersburgError, UpstreamUnavailable +from app.models import DiaryLinkCode, SchoolClass +from app.providers.diary.errors import ( + BadCredentials, + DiaryError, + SignInUnsupported, + UpstreamUnavailable, +) +from app.providers.diary.registry import Binding +from app.providers.diary.registry import binding as class_binding from app.security import hash_token from app.services import diary as diary_service from app.services import diary_link @@ -126,7 +133,45 @@ def _closed(message: str, status: int = 400, note: str = _ASK_AGAIN) -> HTMLResp ) -def _form(code: str) -> HTMLResponse: +async def _binding_of(session: AsyncSession, class_id: int | None) -> Binding | None: + """The diary binding of the ticket's class, or ``None`` if it has none now. + + Read at both the GET and the POST, never trusted from when the ticket was + minted: an admin who unbinds or rebinds the class between the two must not + have the password sent to a diary the family is no longer looking at (#137). + """ + if class_id is None: + return None + school_class = await session.get(SchoolClass, class_id) + if school_class is None: + return None + return class_binding(school_class) + + +def _where(binding: Binding | None) -> str: + """The subtitle line under the form's heading, escaped. + + Names the provider, and for «Сетевой город» its region and school, so the + family can see which diary and which school this password goes to. Every + part is escaped: the school name comes from the upstream's search. + """ + if binding is None: + return "Санкт-Петербург · dnevnik2.petersburgedu.ru" + parts = [binding.provider.title] + if binding.region: + from app.providers.netschool import regions + + region = regions.get(binding.region) + if region is not None: + parts.append(region.title) + if binding.school_name: + parts.append(binding.school_name) + elif binding.provider.site: + parts.append(binding.provider.site) + return " · ".join(escape(part) for part in parts) + + +def _form(code: str, binding: Binding | None = None) -> HTMLResponse: # The code goes in the action rather than a hidden field: it is already in # the URL the browser is on, and one place for it is one place to get # wrong. autocomplete is on, so a password manager can fill this — the @@ -142,7 +187,7 @@ def _form(code: str) -> HTMLResponse: return _page( "Вход в дневник", f"

Электронный дневник

" - f"

Санкт-Петербург · dnevnik2.petersburgedu.ru

" + f"

{_where(binding)}

" f'
' "" " _Verdict: +def _why(error: DiaryError) -> _Verdict: """The upstream's failure, said in a way the reader can act on. Only :class:`BadCredentials` is «неверный пароль». Everything else said so @@ -309,16 +380,24 @@ def _why(error: PetersburgError) -> _Verdict: this was fixed first). Rendered as «неверный логин или пароль» it sends somebody to retype a password that was right, over and over, with nothing anywhere hinting that the diary is the thing that is broken. + + A message that is not the class default (the expired-password one, say) + is passed through rather than flattened to «неверный пароль». """ + if isinstance(error, SignInUnsupported): + # Decided before any password was sent, so the ticket goes back — but + # retrying will not help, so the note points at Госуслуги rather than + # «попробуйте снова». + return _Verdict(error.message, 502, keep_ticket=True) if isinstance(error, BadCredentials): - return _Verdict("Неверный логин или пароль.", 401, keep_ticket=False) + # PasswordExpired and any other BadCredentials with its own words keep + # them; the bare base message becomes the fixed «неверный пароль». + spoke = error.message and error.message != BadCredentials.message + return _Verdict(error.message if spoke else "Неверный логин или пароль.", 401, + keep_ticket=False) if isinstance(error, UpstreamUnavailable): - return _Verdict( - "Дневник сейчас не отвечает — дело не в пароле. Попробуйте через " - "несколько минут.", - 503, - keep_ticket=True, - ) + # AddressRefused lands here too, with its own «дело не в пароле» words. + return _Verdict(error.message, 503, keep_ticket=True) # UnexpectedResponse, SessionExpired and any future member of the family. # The address is named on purpose: opening the diary in a browser is the # one check that tells the person which of the two is broken, and it is diff --git a/server/app/bot/handlers/access.py b/server/app/bot/handlers/access.py index 40951f0f..790d32e8 100644 --- a/server/app/bot/handlers/access.py +++ b/server/app/bot/handlers/access.py @@ -40,7 +40,8 @@ from app.bot.states import AddInvite from app.models import AccessRequest, BotUser, JoinMode, PhoneInvite, Role, SchoolClass from app.security import normalise_phone -from app.services import audit, device_invites, reminders +from app.services import audit, device_invites, diary_link, reminders +from app.services import diary as diary_service router = Router(name="access") @@ -625,6 +626,16 @@ async def revoke( # keeps the digests and every substitution arriving in the chat of somebody who # is no longer in the class. await reminders.drop_for(session, telegram_id=member.telegram_id, class_id=school_class.id) + # Their diary sessions and any unspent sign-in ticket go too (#136). A + # session is reached only by (telegram_id, class_id), so after revocation + # nobody could sign it out — and with the keep-alive it would otherwise be + # kept live upstream for the family for the thirty days until the purge. The + # sign-out tells «Сетевой город» goodbye where it can be told. An unspent + # ticket is a sign-in an ex-member must not still be able to make. + await diary_service.sign_out_here( + session, telegram_id=member.telegram_id, class_id=school_class.id + ) + await diary_link.drop_for(session, telegram_id=member.telegram_id, class_id=school_class.id) await session.delete(member) await session.commit() await callback.message.edit_text("🚫 Доступ убран.", reply_markup=back_to_menu()) diff --git a/server/app/providers/diary/base.py b/server/app/providers/diary/base.py index 8a56440d..ea813526 100644 --- a/server/app/providers/diary/base.py +++ b/server/app/providers/diary/base.py @@ -90,6 +90,7 @@ class DiaryProvider(Protocol): key: str title: str genitive: str + site: str async def sign_in(self, request: SignInRequest) -> str: """Sign in and return the serialised credential, which the caller seals.""" diff --git a/server/app/providers/netschool/provider.py b/server/app/providers/netschool/provider.py index 78c4291b..d35fd6b4 100644 --- a/server/app/providers/netschool/provider.py +++ b/server/app/providers/netschool/provider.py @@ -152,6 +152,7 @@ class NetSchoolProvider: key = "netschool" title = "Сетевой город" genitive = "«Сетевого города»" + site = "" async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest protocol region = region_for(request.region) diff --git a/server/app/providers/petersburg/provider.py b/server/app/providers/petersburg/provider.py index 9aa15012..e513a323 100644 --- a/server/app/providers/petersburg/provider.py +++ b/server/app/providers/petersburg/provider.py @@ -89,6 +89,7 @@ class PetersburgProvider: key = "petersburg" title = "Санкт-Петербург" genitive = "Санкт-Петербурга" + site = "dnevnik2.petersburgedu.ru" async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest protocol client = PetersburgClient() diff --git a/server/app/services/diary_link.py b/server/app/services/diary_link.py index 7744b937..610fee22 100644 --- a/server/app/services/diary_link.py +++ b/server/app/services/diary_link.py @@ -114,6 +114,22 @@ async def claim(session: AsyncSession, code: str) -> DiaryLinkCode | None: return row +async def drop_for(session: AsyncSession, *, telegram_id: int, class_id: int) -> int: + """Drop every outstanding sign-in ticket this account holds in this class. + + Used when a member is removed: an unspent ticket is worth a sign-in for + fifteen minutes, and an ex-member must not be able to open a session in a + class they have just been taken out of. Committed by the caller. + """ + result = await session.execute( + sa_delete(DiaryLinkCode).where( + DiaryLinkCode.telegram_id == telegram_id, + DiaryLinkCode.class_id == class_id, + ) + ) + return rows_affected(result) + + async def purge(session: AsyncSession) -> int: """Drop tickets nobody can use any more. Returns how many went. diff --git a/server/tests/test_diary_web.py b/server/tests/test_diary_web.py index 2a652b5c..54b53322 100644 --- a/server/tests/test_diary_web.py +++ b/server/tests/test_diary_web.py @@ -46,6 +46,10 @@ async def web(): @pytest.fixture async def ticket(session, school_class) -> str: + # The form and the submit read the class's diary binding now (#137), so the + # ticket's class has to be bound. Petersburg, the diary these tests exercise. + school_class.diary_provider = "petersburg" + await session.commit() return await diary_link.mint(session, telegram_id=42, class_id=school_class.id) From b1bd8e570817571900ff0019a20193c31d25c48d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 21:41:48 +0000 Subject: [PATCH 04/30] =?UTF-8?q?Hold=20=C2=AB=D0=A1=D0=B5=D1=82=D0=B5?= =?UTF-8?q?=D0=B2=D0=BE=D0=B9=20=D0=B3=D0=BE=D1=80=D0=BE=D0=B4=C2=BB=20ses?= =?UTF-8?q?sions=20open=20from=20the=20cron=20tick?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A NetSchool session idles out in fifteen minutes to an hour, and this project stores no password to sign back in with, so the tick pings each live one with GET /webapi/context — the call every open client keeps a session alive with. - It claims a batch first, stamping keepalive_attempted_at whatever the outcome, so a failing origin cannot sit at the head of the queue and starve the healthy ones, and two overlapping ticks never ping the same row (FOR UPDATE SKIP LOCKED on Postgres). - It pings with no database transaction held open, then writes each outcome back with a guarded UPDATE that matches nothing if the row was signed out or its credential rotated meanwhile — no lost update, no StaleDataError. - It never touches last_used_at, so the 30-day purge of a session nobody opens still fires; a dropped session (401) is expired, a down or blocking origin is left for next tick. - Its deadline counts from the start of the request, and it runs last inside its own try/except, so a slow morning of digests shortens it and a diary fault never fails the tick (which would redden the fallback clock). It needs the external cron (#120); GitHub's fallback clock is too sparse to keep a session alive. The netschool client is closed in the lifespan beside the others. Part of #139. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/cron.py | 22 ++- server/app/main.py | 8 +- server/app/schemas.py | 7 + server/app/services/diary_keepalive.py | 188 +++++++++++++++++++++++++ server/tests/test_diary_keepalive.py | 126 +++++++++++++++++ server/tests/test_netschool_client.py | 2 - server/tests/test_netschool_mapper.py | 2 +- 7 files changed, 348 insertions(+), 7 deletions(-) create mode 100644 server/app/services/diary_keepalive.py create mode 100644 server/tests/test_diary_keepalive.py diff --git a/server/app/api/cron.py b/server/app/api/cron.py index 48fb592b..f1b75044 100644 --- a/server/app/api/cron.py +++ b/server/app/api/cron.py @@ -12,6 +12,8 @@ from __future__ import annotations +import asyncio +import logging from datetime import UTC, datetime, timedelta from hmac import compare_digest from typing import Any @@ -26,7 +28,9 @@ from app.db import SessionLocal, rows_affected from app.models import DeviceToken, DiarySession, JoinAttempt from app.schemas import TickOut -from app.services import device_invites, diary_link, reminders +from app.services import device_invites, diary_keepalive, diary_link, reminders + +log = logging.getLogger(__name__) router = APIRouter(route_class=DishkaAnnotatedRoute, prefix="/api/v1", tags=["cron"]) @@ -144,6 +148,7 @@ async def tick( subscriber at will. The comparison is constant-time for the same reason the webhook's is. """ + started = asyncio.get_running_loop().time() settings = get_settings() if not settings.cron_secret: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Cron is not configured") @@ -173,6 +178,18 @@ async def tick( # The personal join codes of a class in «по приглашению». Same reason again: # they expire in fifteen minutes and nothing would ever come back for them. invites_purged = await device_invites.prune(session) + # Hold the «Сетевой город» sessions open. Last, and inside its own guard, so + # a slow or raising keep-alive never fails the tick — that would turn the + # fallback clock red every five minutes over a diary fault. Its deadline + # counts from the start of the request, so a morning heavy with digests + # shortens the keep-alive rather than pushing the function past its ceiling. + kept_alive = lost = 0 + keepalive_failed = False + try: + kept_alive, lost = await diary_keepalive.keep_alive(session, started=started) + except Exception: # noqa: BLE001 - a diary fault must not fail the whole tick + keepalive_failed = True + log.exception("diary keep-alive failed") return TickOut( **counts, fsm_purged=fsm_purged, @@ -181,6 +198,9 @@ async def tick( device_tokens_purged=device_purged, diary_links_purged=links_purged, device_invites_purged=invites_purged, + diary_sessions_kept_alive=kept_alive, + diary_sessions_lost=lost, + diary_keepalive_failed=keepalive_failed, ) diff --git a/server/app/main.py b/server/app/main.py index 382173ba..a5b0bce2 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -90,14 +90,16 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: if bot_task is not None: with contextlib.suppress(asyncio.CancelledError): await bot_task - # Both providers hold a process-wide pooled HTTP client; closing them + # Each provider holds a process-wide pooled HTTP client; closing them # is what returns their sockets rather than leaving them to a - # finaliser. Imported here rather than at module scope so neither - # lands on the cold-start path of a request that uses neither. + # finaliser. Imported here rather than at module scope so none of them + # lands on the cold-start path of a request that uses none. from app.providers.dadata import close_client as close_directory + from app.providers.netschool.client import close_client as close_netschool from app.providers.petersburg import close_client await close_client() + await close_netschool() await close_directory() # Last, and after the bot has stopped: a handler still running would # otherwise be holding a session out of a container that has shut its diff --git a/server/app/schemas.py b/server/app/schemas.py index 38743ca9..3005db7e 100644 --- a/server/app/schemas.py +++ b/server/app/schemas.py @@ -547,6 +547,13 @@ class TickOut(BaseModel): device_tokens_purged: int = 0 diary_links_purged: int = 0 device_invites_purged: int = 0 + #: The keep-alive that holds a «Сетевой город» session open across its short + #: idle window: how many were pinged alive, how many the upstream had already + #: dropped, and true when the keep-alive itself raised (isolated so a diary + #: fault never fails the whole tick and reddens the clock). + diary_sessions_kept_alive: int = 0 + diary_sessions_lost: int = 0 + diary_keepalive_failed: bool = False # --------------------------------------------------------------------------- diff --git a/server/app/services/diary_keepalive.py b/server/app/services/diary_keepalive.py new file mode 100644 index 00000000..90124777 --- /dev/null +++ b/server/app/services/diary_keepalive.py @@ -0,0 +1,188 @@ +"""Hold «Сетевой город» sessions open from the cron tick. + +A NetSchool session idles out in fifteen minutes to an hour, and this project +stores no password to sign back in with. So the tick pings each live session +with ``GET /webapi/context``, which resets its idle timer — the same call every +open client keeps a session alive with. It needs the external cron (#120): +GitHub's fallback clock is too sparse, and a session goes dead between two of +its ticks. + +Three rules the review nailed down: + +- **Never touch ``last_used_at``.** Pinging must not look like the family using + the session, or the 30-day purge of one nobody opens would never fire. +- **Claim before pinging.** ``keepalive_attempted_at`` is set on every attempt, + whatever its outcome, so a failing origin cannot sit at the head of the queue + for ever and starve the healthy ones, and two overlapping ticks do not both + ping the same row. +- **Read, then ping with no session open, then apply.** The pings run with the + database transaction closed; the results are written back one row at a time + with a guarded ``UPDATE`` that matches nothing if the row was signed out or + its credential rotated meanwhile — so a vanished or changed row is skipped, + not a lost update and not a crash. +""" + +from __future__ import annotations + +import asyncio +import logging +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta + +from sqlalchemy import select +from sqlalchemy import update as sa_update +from sqlalchemy.ext.asyncio import AsyncSession + +from app.crypto import diary_enabled, seal, unseal +from app.models import DiarySession +from app.providers.diary.errors import SessionExpired +from app.providers.diary.registry import NETSCHOOL, provider_for + +log = logging.getLogger(__name__) + +#: At most this many sessions a tick, so one tick's work is bounded whatever the +#: number of families. The rest are first next tick (ordered oldest-attempt). +KEEPALIVE_BATCH = 200 +#: A floor between two pings of one session, so extra or overlapping ticks are +#: free and one address is not hammered. Well under the shortest idle window. +KEEPALIVE_MIN_INTERVAL = timedelta(minutes=4) +#: Stop starting new pings this many seconds into the tick, so the whole +#: request stays inside the platform's function ceiling. +KEEPALIVE_DEADLINE_SECONDS = 18.0 +#: At most this many pings in flight at once. +KEEPALIVE_CONCURRENCY = 8 + + +def _now() -> datetime: + return datetime.now(UTC).replace(tzinfo=None) + + +@dataclass +class _Claim: + """One row claimed for a ping, read out as plain values.""" + + id: int + provider: str + credential: str + + +@dataclass +class _Result: + id: int + outcome: str # "ok" | "expired" | "skip" + credential: str | None = None + + +async def keep_alive(session: AsyncSession, *, started: float | None = None) -> tuple[int, int]: + """Ping the live «Сетевой город» sessions. @return (kept_alive, lost). + + ``started`` is ``loop.time()`` at the start of the request, so the deadline + counts the digests and purges that ran first; omitted, it counts from here. + """ + if not diary_enabled(): + # Nothing would unseal, so a ping could only fail. Do nothing rather + # than expire every session over a key that was mistyped for an hour. + return 0, 0 + loop = asyncio.get_running_loop() + started = started if started is not None else loop.time() + + claims = await _claim(session) + if not claims: + return 0, 0 + + results = await _ping_all(claims, loop=loop, started=started) + return await _apply(session, results) + + +async def _claim(session: AsyncSession) -> list[_Claim]: + """Take the next batch and stamp ``keepalive_attempted_at`` so no other + tick takes them too. Committed here, before any network call.""" + now = _now() + cutoff = now - KEEPALIVE_MIN_INTERVAL + stmt = ( + select(DiarySession) + .where( + DiarySession.provider == NETSCHOOL, + DiarySession.expired_at.is_(None), + (DiarySession.keepalive_attempted_at.is_(None)) + | (DiarySession.keepalive_attempted_at < cutoff), + ) + .order_by(DiarySession.keepalive_attempted_at.is_(None).desc(), + DiarySession.keepalive_attempted_at, + DiarySession.id) + .limit(KEEPALIVE_BATCH) + ) + # FOR UPDATE SKIP LOCKED on Postgres so two overlapping ticks never take the + # same rows; SQLite (local, tests) has no such clause and one worker anyway. + if session.bind and session.bind.dialect.name == "postgresql": + stmt = stmt.with_for_update(skip_locked=True) + rows = list(await session.scalars(stmt)) + claims: list[_Claim] = [] + for row in rows: + row.keepalive_attempted_at = now + claims.append(_Claim(id=row.id, provider=row.provider or "", credential=row.upstream_token)) + await session.commit() + return claims + + +async def _ping_all(claims: list[_Claim], *, loop, started: float) -> list[_Result]: + """Ping every claimed session, with no database session held open.""" + semaphore = asyncio.Semaphore(KEEPALIVE_CONCURRENCY) + + async def one(claim: _Claim) -> _Result: + if loop.time() - started > KEEPALIVE_DEADLINE_SECONDS: + return _Result(claim.id, "skip") # out of budget; first next tick + async with semaphore: + return await _ping(claim) + + return list(await asyncio.gather(*(one(c) for c in claims))) + + +async def _ping(claim: _Claim) -> _Result: + provider = provider_for(claim.provider) + plain = unseal(claim.credential) + if provider is None or not plain: + # A key rotation or an unknown provider: leave it for a real request to + # expire when somebody actually asks, rather than expiring en masse. + return _Result(claim.id, "skip") + connection = provider.open(plain) + try: + await connection.keep_alive() + except SessionExpired: + return _Result(claim.id, "expired") + except Exception: # noqa: BLE001 - a down or blocking origin is left as-is + log.info("diary keep-alive ping failed for session %s", claim.id, exc_info=True) + return _Result(claim.id, "skip") + return _Result(claim.id, "ok", credential=connection.credential) + + + +async def _apply(session: AsyncSession, results: list[_Result]) -> tuple[int, int]: + """Write each ping's outcome with a guarded UPDATE, then commit once. + + Each UPDATE matches on what was read, so a row signed out or rotated between + the claim and now simply matches nothing and is skipped — no lost update, no + StaleDataError. + """ + now = _now() + kept = lost = 0 + for result in results: + if result.outcome == "ok": + values = {"kept_alive_at": now, "upstream_ok_at": now} + if result.credential: + values["upstream_token"] = seal(result.credential) + await session.execute( + sa_update(DiarySession) + .where(DiarySession.id == result.id, DiarySession.expired_at.is_(None)) + .values(**values) + ) + kept += 1 + elif result.outcome == "expired": + await session.execute( + sa_update(DiarySession) + .where(DiarySession.id == result.id, DiarySession.expired_at.is_(None)) + .values(expired_at=now) + ) + lost += 1 + await session.commit() + return kept, lost diff --git a/server/tests/test_diary_keepalive.py b/server/tests/test_diary_keepalive.py new file mode 100644 index 00000000..c23953c6 --- /dev/null +++ b/server/tests/test_diary_keepalive.py @@ -0,0 +1,126 @@ +"""The cron keep-alive that holds «Сетевой город» sessions open. + +It pings live netschool rows, expires the ones the upstream has dropped, leaves +the ones behind a down or blocking origin, and never touches ``last_used_at`` +(so the 30-day purge of an unused session still fires). A ping runs with no +database session held open; the outcome is written back with a guarded UPDATE, +so a row signed out between the claim and the write is skipped, not a crash. +""" + +from __future__ import annotations + +import json + +from app.crypto import seal +from app.models import DiarySession +from app.providers.diary.errors import SessionExpired, UpstreamUnavailable +from app.security import hash_token, new_token +from app.services import diary_keepalive + + +def _netschool_row(**over) -> DiarySession: + cred = json.dumps({"v": 1, "region": "zabaikalsky", "school_id": 1, "at": "at", + "cookies": {}, "year_id": 2026}) + fields = dict( + token_hash=hash_token(new_token()), + upstream_token=seal(cred), + login="parent@example.com", + provider="netschool", + region="zabaikalsky", + ) + fields.update(over) + return DiarySession(**fields) + + +async def test_a_live_session_is_pinged_and_not_touched_as_used(session, monkeypatch): + row = _netschool_row() + session.add(row) + await session.commit() + + pinged: list[int] = [] + + async def fake_keep_alive(self): + pinged.append(1) + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", fake_keep_alive + ) + kept, lost = await diary_keepalive.keep_alive(session) + await session.refresh(row) + + assert (kept, lost) == (1, 0) + assert pinged == [1] + assert row.kept_alive_at is not None + assert row.upstream_ok_at is not None + assert row.keepalive_attempted_at is not None + # The family did not use it; the purge clock must not have moved. + assert row.last_used_at is None + assert row.expired_at is None + + +async def test_a_dropped_session_is_expired(session, monkeypatch): + row = _netschool_row() + session.add(row) + await session.commit() + + async def dead(self): + raise SessionExpired + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", dead + ) + kept, lost = await diary_keepalive.keep_alive(session) + await session.refresh(row) + + assert (kept, lost) == (0, 1) + assert row.expired_at is not None + + +async def test_a_down_origin_leaves_the_session_alone(session, monkeypatch): + row = _netschool_row() + session.add(row) + await session.commit() + + async def down(self): + raise UpstreamUnavailable + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", down + ) + kept, lost = await diary_keepalive.keep_alive(session) + await session.refresh(row) + + assert (kept, lost) == (0, 0) + assert row.expired_at is None + # It was attempted, so it goes to the back of the queue rather than the front. + assert row.keepalive_attempted_at is not None + + +async def test_petersburg_and_expired_rows_are_left_out(session, monkeypatch): + petersburg = DiarySession( + token_hash=hash_token(new_token()), upstream_token=seal("tok"), + login="p@example.com", provider="petersburg", + ) + already_dead = _netschool_row(expired_at=__import__("datetime").datetime(2020, 1, 1)) + session.add_all([petersburg, already_dead]) + await session.commit() + + called: list[int] = [] + + async def fake(self): + called.append(1) + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", fake + ) + kept, lost = await diary_keepalive.keep_alive(session) + assert (kept, lost) == (0, 0) + assert called == [] # neither a Petersburg row nor an already-expired one is pinged + + +async def test_the_keep_alive_does_nothing_without_a_diary_secret(session, monkeypatch): + row = _netschool_row() + session.add(row) + await session.commit() + monkeypatch.setattr(diary_keepalive, "diary_enabled", lambda: False) + assert await diary_keepalive.keep_alive(session) == (0, 0) diff --git a/server/tests/test_netschool_client.py b/server/tests/test_netschool_client.py index 55a7b53e..168c0d07 100644 --- a/server/tests/test_netschool_client.py +++ b/server/tests/test_netschool_client.py @@ -26,8 +26,6 @@ from app.providers.netschool.provider import NetSchoolProvider from app.providers.netschool.regions import get as region_for - - LOGINDATA_OK = {"productName": "Сетевой Город. Образование", "version": "5.58.0", "schoolLogin": True, "esiaMainAuth": False, "cacheVer": "639"} diff --git a/server/tests/test_netschool_mapper.py b/server/tests/test_netschool_mapper.py index 3b6b76a5..7b118352 100644 --- a/server/tests/test_netschool_mapper.py +++ b/server/tests/test_netschool_mapper.py @@ -60,7 +60,7 @@ def test_lessons_drop_the_empty_subject_and_read_both_time_forms(): lessons = m.to_lessons(WEEK, date(2026, 11, 30), date(2026, 12, 6)) - assert [l.subject for l in lessons] == ["Алгебра", "Химия"] + assert [x.subject for x in lessons] == ["Алгебра", "Химия"] algebra, chem = lessons assert algebra.number == 1 assert algebra.starts_at.isoformat() == "09:00:00" From 1975b60541d80dbc83274b8a88a096dfdf25c466 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 22:06:44 +0000 Subject: [PATCH 05/30] =?UTF-8?q?Bind=20a=20class=20to=20=C2=AB=D0=A1?= =?UTF-8?q?=D0=B5=D1=82=D0=B5=D0=B2=D0=BE=D0=B9=20=D0=B3=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B4=C2=BB=20from=20the=20bot,=20and=20read=20either=20diary?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «📒 Привязать дневник» is no longer a single toggle: with a second provider it opens a chooser. Petersburg binds in one press, as before; «Сетевой город» asks for the region, then a school. The region step probes the region's sign-in options first (`login_allowed`) so an admin learns once that a Госуслуги-only region cannot be bound, rather than every family finding out at sign-in, and the school step searches the region server by name and offers what it found. The pick carries an index into the searched list held in FSM data, checked against that list where it is read — never an id trusted from the client. Every step re-checks the role, including the school-name message handler, because FSM state is per-user and attacker-controlled. The read path is now provider-neutral. `_bound` and the class card read the registry's `binding()` rather than the raw column, so a class bound to a region since dropped from the allow-list reads «не привязан» instead of a dead name; `_session_for` is keyed on the class's *current* provider, so after a rebind a session opened against the old upstream becomes a clean «войдите снова» rather than a screen that silently talks to the diary the class left; and the sign-in card names whichever diary is bound, in the genitive, since a card that always said Petersburg would be wrong for the other. Adds `schools_search` to the «Сетевой город» client for the binding flow, and `diary_provider_menu` / `diary_region_menu` / `diary_school_menu`, capped at one constant so what is drawn is what can be pressed. Uncovered: nothing here has been run against a real «Сетевой город» server — the search endpoint path and the login-options probe are written from research, and the first live sign-in is the owner's (#121/#135). Part of #139. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/bot/diary_render.py | 9 +- server/app/bot/handlers/diary.py | 70 +++-- server/app/bot/handlers/manage.py | 239 +++++++++++++- server/app/bot/keyboards.py | 14 + server/app/bot/manage_keyboards.py | 79 ++++- server/app/bot/manage_render.py | 3 +- server/app/bot/states.py | 8 + server/app/providers/netschool/client.py | 20 ++ .../versions/0015_diary_provider_columns.py | 8 +- server/tests/test_api_extended.py | 3 + server/tests/test_bot_diary.py | 34 +- server/tests/test_bot_manage.py | 291 +++++++++++++++++- 12 files changed, 725 insertions(+), 53 deletions(-) diff --git a/server/app/bot/diary_render.py b/server/app/bot/diary_render.py index ca9d8486..2af2efd1 100644 --- a/server/app/bot/diary_render.py +++ b/server/app/bot/diary_render.py @@ -159,10 +159,15 @@ def render_week(lessons: list[DiaryLesson], start: Date, today: Date) -> str: return clamp(lines) -def render_signed_out() -> str: +def render_signed_out(genitive: str) -> str: + """The sign-in offer. ``genitive`` names the bound diary in the genitive + case — «Санкт-Петербурга», «„Сетевого города“» — because there is more than + one now, and a card that always said Petersburg would be wrong for the + other. It is a fixed provider string, never anything a user typed, so it + goes in unescaped like the rest of this template.""" return ( "📒 Электронный дневник\n\n" - "Класс привязан к дневнику Санкт-Петербурга. Вход — ваш личный: " + f"Класс привязан к дневнику {genitive}. Вход — ваш личный: " "вы видите своего ребёнка, и никто из класса не видит его за вас.\n\n" "Пароль не вводится в чат. Бот даст ссылку на страницу входа — " "оттуда пароль уходит прямо в дневник и нигде не сохраняется." diff --git a/server/app/bot/handlers/diary.py b/server/app/bot/handlers/diary.py index d860df2f..ab5ec0c9 100644 --- a/server/app/bot/handlers/diary.py +++ b/server/app/bot/handlers/diary.py @@ -22,7 +22,7 @@ class to dnevnik2 gives the class nothing; it offers every member a door to from aiogram import F, Router from aiogram.types import CallbackQuery -from sqlalchemy import select +from sqlalchemy import or_, select from sqlalchemy.ext.asyncio import AsyncSession from app.bot.diary_keyboard import ( @@ -44,7 +44,8 @@ class to dnevnik2 gives the class nothing; it offers every member a door to from app.config import get_settings from app.crypto import diary_enabled from app.models import DiarySession, Role, SchoolClass -from app.providers.petersburg import PetersburgError, SessionExpired, UpstreamUnavailable +from app.providers.diary.errors import DiaryError, SessionExpired, UpstreamUnavailable +from app.providers.diary.registry import binding as diary_binding from app.services import diary as diary_service from app.services import diary_link @@ -64,20 +65,37 @@ class to dnevnik2 gives the class nothing; it offers every member a door to async def _session_for( - session: AsyncSession, telegram_id: int, class_id: int + session: AsyncSession, telegram_id: int, school_class: SchoolClass ) -> DiarySession | None: """This person's live diary session in this class, or ``None``. - Keyed on both, always. On telegram_id alone, a parent in two classes would - read one child's diary from the other class's screen; on class_id alone - there would be no diary in this bot worth having. + Keyed on person and class, always. On telegram_id alone, a parent in two + classes would read one child's diary from the other class's screen; on + class_id alone there would be no diary in this bot worth having. + + Also keyed on the class's *current* provider: an admin can rebind a class + from one diary to another, and a session opened against the old upstream + holds a credential the new diary would not accept. Filtering it out here + turns the stale row into a clean «войдите снова» rather than a screen that + silently talks to the diary the class left. A legacy row with no provider + is Petersburg, which is what the column meant before it existed. """ + b = diary_binding(school_class) + if b is None: + return None + if b.provider.key == PETERSBURG: + provider_clause = or_( + DiarySession.provider == PETERSBURG, DiarySession.provider.is_(None) + ) + else: + provider_clause = DiarySession.provider == b.provider.key row = await session.scalar( select(DiarySession) .where( DiarySession.telegram_id == telegram_id, - DiarySession.class_id == class_id, + DiarySession.class_id == school_class.id, DiarySession.expired_at.is_(None), + provider_clause, ) .order_by(DiarySession.id.desc()) ) @@ -91,12 +109,22 @@ async def _session_for( def _bound(school_class: SchoolClass) -> bool: - return school_class.diary_provider == PETERSBURG + """Whether the class is bound to a diary this server can still reach. Reads + the registry rather than the raw column, so a class bound to a «Сетевой + город» region since dropped from the allow-list counts as unbound.""" + return diary_binding(school_class) is not None + + +def _genitive(school_class: SchoolClass) -> str: + """The bound diary's name in the genitive, for the sign-in card. Falls back + to Petersburg's, which is the only binding that predates the column.""" + b = diary_binding(school_class) + return b.provider.genitive if b is not None else "Санкт-Петербурга" -async def _offer_sign_in(callback: CallbackQuery) -> None: +async def _offer_sign_in(callback: CallbackQuery, school_class: SchoolClass) -> None: await callback.message.edit_text( - render_signed_out(), + render_signed_out(_genitive(school_class)), reply_markup=signed_out_keyboard(can_sign_in=diary_enabled()), disable_web_page_preview=True, ) @@ -126,9 +154,9 @@ async def diary_root( ) return - row = await _session_for(session, callback.from_user.id, school_class.id) + row = await _session_for(session, callback.from_user.id, school_class) if row is None: - await _offer_sign_in(callback) + await _offer_sign_in(callback, school_class) await callback.answer() return @@ -200,7 +228,7 @@ async def diary_sign_out( await diary_service.sign_out_here( session, telegram_id=callback.from_user.id, class_id=school_class.id ) - await _offer_sign_in(callback) + await _offer_sign_in(callback, school_class) await callback.answer("Вы вышли из дневника") @@ -213,16 +241,16 @@ async def diary_students( if school_class is None: await callback.answer("Нет доступа", show_alert=True) return - row = await _session_for(session, callback.from_user.id, school_class.id) + row = await _session_for(session, callback.from_user.id, school_class) if row is None: - await _offer_sign_in(callback) + await _offer_sign_in(callback, school_class) await callback.answer() return service = diary_service.DiaryService(session, row) try: students = await service.students() - except PetersburgError as error: + except DiaryError as error: await _stumble(callback, session, school_class, error) return @@ -243,9 +271,9 @@ async def diary_view( if school_class is None: await callback.answer("Нет доступа", show_alert=True) return - row = await _session_for(session, callback.from_user.id, school_class.id) + row = await _session_for(session, callback.from_user.id, school_class) if row is None: - await _offer_sign_in(callback) + await _offer_sign_in(callback, school_class) await callback.answer() return @@ -296,10 +324,10 @@ async def _show( text = await _body(service, school_class, view, offset, student) except SessionExpired: - await _offer_sign_in(callback) + await _offer_sign_in(callback, school_class) await callback.answer("Дневник разлогинил — войдите снова", show_alert=True) return - except PetersburgError as error: + except DiaryError as error: await _stumble(callback, session, school_class, error) return except Exception: # noqa: BLE001 - an upstream shape must not reach a chat @@ -379,7 +407,7 @@ async def _stumble( callback: CallbackQuery, session: AsyncSession, school_class: SchoolClass, - error: PetersburgError, + error: DiaryError, ) -> None: """One place that turns an upstream failure into something to do about it.""" if isinstance(error, UpstreamUnavailable): diff --git a/server/app/bot/handlers/manage.py b/server/app/bot/handlers/manage.py index f075e788..3ae1aff6 100644 --- a/server/app/bot/handlers/manage.py +++ b/server/app/bot/handlers/manage.py @@ -40,16 +40,17 @@ from app.bot import manage_render as mr from app.bot import render from app.bot.handlers.calendar import open_month -from app.bot.handlers.diary import PETERSBURG as DIARY_PROVIDER from app.bot.handlers.timetable import REJECTED_MAX from app.bot.keyboards import ( WEEKDAY_FULL, + DiarySchoolPick, Menu, back_to_menu, cancel_keyboard, ) from app.bot.manage_keyboards import ( COLOUR_PRESETS, + DIARY_SCHOOLS_MAX, PERIOD_KINDS, AuditAction, BellsAction, @@ -68,6 +69,9 @@ colour_keyboard, day_kind_keyboard, device_keyboard, + diary_provider_menu, + diary_region_menu, + diary_school_menu, holiday_list_keyboard, import_keyboard, period_kind_keyboard, @@ -91,6 +95,7 @@ from app.bot.middlewares import prefs_key from app.bot.render import clamp, more_line, plural from app.bot.roles import list_memberships +from app.bot.states import BindDiary from app.config import get_settings from app.db import SessionLocal from app.fsm_storage import DatabaseStorage @@ -109,6 +114,11 @@ TermKind, TimetableEntry, ) +from app.providers.diary.errors import AddressRefused, DiaryError, SignInUnsupported +from app.providers.diary.registry import NETSCHOOL, PETERSBURG +from app.providers.diary.registry import binding as diary_binding +from app.providers.netschool import regions as ns_regions +from app.providers.netschool.client import NetSchoolClient from app.services import access as access_service from app.services import audit, linking, structure, timetable_io from app.services import calendar as calendar_service @@ -2016,6 +2026,7 @@ async def _class_card( members=members, devices=devices, pending=pending, + diary_label=_diary_label(school_class), ) keyboard = class_menu( is_owner=role.at_least(Role.OWNER), @@ -2028,6 +2039,26 @@ async def _class_card( return text, keyboard +def _diary_label(school_class: SchoolClass) -> str: + """The diary line for the class card: the provider, and for «Сетевой город» + the region and school. Reads the binding, so a class bound to a region since + dropped from the allow-list reads «не привязан» rather than a dead name.""" + b = diary_binding(school_class) + if b is None: + return "не привязан" + if b.region: + from app.providers.netschool import regions + + region = regions.get(b.region) + parts = [b.provider.title] + if region is not None: + parts.append(region.title) + if b.school_name: + parts.append(b.school_name) + return " · ".join(parts) + return b.provider.title + + @router.message(Command("class")) async def cmd_class( message: Message, @@ -2356,16 +2387,210 @@ async def class_diary_bind( return if school_class.diary_provider: + # Bound → unbind. The door goes; the sessions people opened stay theirs + # until they sign out or the class is deleted, as three screens promise. school_class.diary_provider = None - note = "дневник отвязан" - else: - school_class.diary_provider = DIARY_PROVIDER - note = "привязан дневник Санкт-Петербурга" + school_class.diary_region = None + school_class.diary_school_id = None + school_class.diary_school_name = None + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", "дневник отвязан" + ) + await session.commit() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Дневник отвязан") + return + + # Unbound → choose which diary. There is more than one now, so binding is a + # small chooser rather than a single toggle. + await callback.message.edit_text( + "📒 Электронный дневник\n\nВыберите, к какому дневнику привязать класс.", + reply_markup=diary_provider_menu(), + ) + await callback.answer() + + +@router.callback_query(ManageAction.filter(F.action == "diary_prov")) +async def class_diary_provider( + callback: CallbackQuery, + callback_data: ManageAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Second step of binding: the provider was picked.""" + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await callback.answer("Только для администраторов", show_alert=True) + return + if callback_data.value == PETERSBURG: + school_class.diary_provider = PETERSBURG + school_class.diary_region = None + school_class.diary_school_id = None + school_class.diary_school_name = None + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", + "привязан дневник Санкт-Петербурга", + ) + await session.commit() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Привязан дневник Санкт-Петербурга") + return + if callback_data.value == NETSCHOOL: + await callback.message.edit_text( + "🌆 Сетевой город\n\nВыберите регион.", reply_markup=diary_region_menu() + ) + await callback.answer() + return + await callback.answer("Неизвестный дневник", show_alert=True) + - await audit.record(session, school_class.id, callback.from_user.id, "class.diary", note) +@router.callback_query(ManageAction.filter(F.action == "diary_reg")) +async def class_diary_region( + callback: CallbackQuery, + callback_data: ManageAction, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, + state: FSMContext, +) -> None: + """Third step: the «Сетевой город» region was picked. Check the region + accepts a password from us before asking for the school, so the admin + learns once rather than every family finding out at sign-in.""" + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await callback.answer("Только для администраторов", show_alert=True) + return + region = ns_regions.get(callback_data.value) + if region is None or not region.password: + await callback.answer("Этот регион недоступен", show_alert=True) + return + ok, why = await _probe_region(region) + if not ok: + await callback.answer(why, show_alert=True) + return + await state.set_state(BindDiary.school) + await state.update_data(diary_region=region.key, diary_class_id=school_class.id) + await callback.message.edit_text( + f"🌆 Сетевой город · {escape(region.title)}\n\n" + "Напишите часть названия школы — я поищу её на сайте региона.", + ) + await callback.answer() + + +async def _probe_region(region) -> tuple[bool, str]: # noqa: ANN001 + """Ask the region's sign-in options, so a class is not bound to a diary no + family can reach. @return (ok, message-if-not).""" + try: + await NetSchoolClient(region).login_allowed() + except SignInUnsupported: + return False, "Этот регион пускает только через Госуслуги — привязать нельзя." + except AddressRefused: + return False, "Сайт региона не отвечает нашему серверу. Сообщите владельцу проекта." + except DiaryError: + return False, "Сайт региона сейчас недоступен. Попробуйте позже." + return True, "" + + +@router.message(BindDiary.school) +async def class_diary_search( + message: Message, + session: AsyncSession, + state: FSMContext, + school_class: SchoolClass | None, + role: Role | None, +) -> None: + """Fourth step: a school-name query. Show what the region's search found. + + FSM state is per-user and attacker-controlled, so the role is re-checked + here as at every step — a non-admin who set itself into this state would + otherwise turn the class card into an outbound search against a region + server. + """ + if not _allowed(school_class, role, Role.ADMIN): + await state.clear() + return + data = await state.get_data() + region = ns_regions.get(data.get("diary_region")) + class_id = data.get("diary_class_id") + if region is None or class_id is None: + await state.clear() + return + query = (message.text or "").strip() + if len(query) < 2: + await message.answer("Введите хотя бы два символа названия школы.") + return + try: + schools = await NetSchoolClient(region).schools_search(query) + except DiaryError: + await message.answer("Не удалось найти школы — сайт региона не ответил. Попробуйте позже.") + return + if not schools: + await message.answer("Школа не найдена. Уточните запрос.") + return + shown = schools[:DIARY_SCHOOLS_MAX] + await state.update_data(diary_schools=shown) + caption = f"🌆 Сетевой город · {escape(region.title)}\n\nВыберите школу:" + more = len(schools) > len(shown) + if more: + caption += f"\n\nПоказаны первые {len(shown)} — уточните запрос, если нужной нет." + await message.answer(caption, reply_markup=diary_school_menu(shown, more=more)) + + +@router.callback_query(DiarySchoolPick.filter(F.action == "cancel")) +async def class_diary_cancel( + callback: CallbackQuery, + session: AsyncSession, + school_class: SchoolClass | None, + role: Role | None, + state: FSMContext, +) -> None: + # A role check like every other step: the callback payload is whatever the + # client sent, and this one redraws the (admin-only) class card, so a + # наблюдатель who pressed it would otherwise be shown it. + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await state.clear() + await callback.answer("Только для администраторов", show_alert=True) + return + await state.clear() + await _redraw_class(callback, session, school_class, role) + await callback.answer("Отменено") + + +@router.callback_query(DiarySchoolPick.filter(F.action == "pick")) +async def class_diary_school( + callback: CallbackQuery, + callback_data: DiarySchoolPick, + session: AsyncSession, + role: Role | None, + state: FSMContext, +) -> None: + """Last step: a school was picked. Bind the class to it.""" + data = await state.get_data() + schools = data.get("diary_schools") or [] + region = ns_regions.get(data.get("diary_region")) + class_id = data.get("diary_class_id") + index = callback_data.value + if region is None or class_id is None or not (0 <= index < len(schools)): + await state.clear() + await callback.answer("Список устарел — начните заново.", show_alert=True) + return + school_class = await session.get(SchoolClass, class_id) + if school_class is None or role is None or not role.at_least(Role.ADMIN): + await state.clear() + await callback.answer("Только для администраторов", show_alert=True) + return + school = schools[index] + school_class.diary_provider = NETSCHOOL + school_class.diary_region = region.key + school_class.diary_school_id = int(school["id"]) + school_class.diary_school_name = str(school["name"])[:300] + await audit.record( + session, school_class.id, callback.from_user.id, "class.diary", + f"привязан «Сетевой город»: {region.title}, {str(school['name'])[:200]}", + ) await session.commit() + await state.clear() await _redraw_class(callback, session, school_class, role) - await callback.answer(note.capitalize()) + await callback.answer("Дневник привязан") async def _redraw_class( diff --git a/server/app/bot/keyboards.py b/server/app/bot/keyboards.py index 88f35bfd..4fd6f90f 100644 --- a/server/app/bot/keyboards.py +++ b/server/app/bot/keyboards.py @@ -113,6 +113,20 @@ class SchoolPick(CallbackData, prefix="sch"): value: int = 0 +class DiarySchoolPick(CallbackData, prefix="dsch"): + """A pick from the «Сетевой город» school search, when binding a class. + + Its own prefix rather than sharing :class:`SchoolPick`, which is scoped to + the create-a-class flow: two flows on one payload would be told apart only + by which state was active, and a diary school id is not a ЕГРЮЛ record. The + value is the school's index in the searched list held in FSM data, checked + against that list where it is read — never trusted as an id. + """ + + action: str # pick | cancel + value: int = 0 + + class ClassAction(CallbackData, prefix="cls"): action: str # settings | rotate_code | rename | create | switch value: str = "" diff --git a/server/app/bot/manage_keyboards.py b/server/app/bot/manage_keyboards.py index f9bfbf11..aa9ee152 100644 --- a/server/app/bot/manage_keyboards.py +++ b/server/app/bot/manage_keyboards.py @@ -13,7 +13,7 @@ from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup from app.bot.button_style import DANGER, PRIMARY, SUCCESS -from app.bot.keyboards import ClassAction, Menu, back_to_menu +from app.bot.keyboards import ClassAction, DiarySchoolPick, Menu, back_to_menu from app.bot.manage_render import AUDIT_PAGE, BELLS_MAX, DEVICES_MAX, LIST_MAX, SUBJECTS_MAX from app.models import DayKind @@ -647,3 +647,80 @@ def terms_menu(terms, *, is_semester: bool) -> InlineKeyboardMarkup: ) rows.append(back_to("root")) return InlineKeyboardMarkup(inline_keyboard=rows) + + +# --------------------------------------------------------------------------- +# Binding a class to an electronic diary +# +# The unbound «📒 Привязать дневник» opens a small chooser rather than binding +# at once, because there is more than one diary now. The rows drawn and the +# rows a press can reach are the same set, so «… и ещё» can never lie: the +# region list is every allow-listed, password-capable region, and the school +# list is capped and says «показаны первые N» when the search found more. +# --------------------------------------------------------------------------- + +#: At most this many schools shown after a search. One constant for the rows +#: drawn and the buttons built, so what is on the screen is what can be pressed. +DIARY_SCHOOLS_MAX = 8 + + +def diary_provider_menu() -> InlineKeyboardMarkup: + """Choose which diary to bind: Petersburg, or «Сетевой город».""" + rows = [ + [ + InlineKeyboardButton( + text="🏛 Санкт-Петербург", + callback_data=ManageAction(action="diary_prov", value="petersburg").pack(), + ) + ], + [ + InlineKeyboardButton( + text="🌆 Сетевой город", + callback_data=ManageAction(action="diary_prov", value="netschool").pack(), + ) + ], + back_to("root"), + ] + return InlineKeyboardMarkup(inline_keyboard=rows) + + +def diary_region_menu() -> InlineKeyboardMarkup: + """Every «Сетевой город» region a family can sign in to with a password.""" + from app.providers.netschool import regions + + rows = [ + [ + InlineKeyboardButton( + text=region.title, + callback_data=ManageAction(action="diary_reg", value=region.key).pack(), + ) + ] + for region in regions.listed() + ] + rows.append(back_to("root")) + return InlineKeyboardMarkup(inline_keyboard=rows) + + +def diary_school_menu(schools: list[dict], *, more: bool) -> InlineKeyboardMarkup: + """The search results, each carrying its index in the searched list. + + ``schools`` is already cut to :data:`DIARY_SCHOOLS_MAX`; ``more`` says the + search found others, so the caption can ask for a narrower query. + """ + rows = [ + [ + InlineKeyboardButton( + text=school["name"][:60], + callback_data=DiarySchoolPick(action="pick", value=index).pack(), + ) + ] + for index, school in enumerate(schools) + ] + rows.append( + [ + InlineKeyboardButton( + text="‹ Отмена", callback_data=DiarySchoolPick(action="cancel").pack() + ) + ] + ) + return InlineKeyboardMarkup(inline_keyboard=rows) diff --git a/server/app/bot/manage_render.py b/server/app/bot/manage_render.py index d70b4744..ef897313 100644 --- a/server/app/bot/manage_render.py +++ b/server/app/bot/manage_render.py @@ -398,6 +398,7 @@ def render_class_card( members: int, devices: int, pending: int, + diary_label: str = "не привязан", ) -> str: lines = [ f"⚙️ {escape(school_class.name)}", @@ -419,7 +420,7 @@ def render_class_card( if school_class.join_mode is JoinMode.INVITE else "🔓 Подключение телефонов: по коду класса" ), - f"📒 Дневник: {'Санкт-Петербург' if school_class.diary_provider else 'не привязан'}", + f"📒 Дневник: {escape(diary_label)}", "", f"👥 Участников: {members} · 📱 устройств: {devices}", ] diff --git a/server/app/bot/states.py b/server/app/bot/states.py index a5ae98f9..e7600523 100644 --- a/server/app/bot/states.py +++ b/server/app/bot/states.py @@ -20,6 +20,14 @@ class CreateClass(StatesGroup): timezone = State() +class BindDiary(StatesGroup): + # Binding a class to «Сетевой город» after the region is chosen: this one + # state holds the region key in its data and takes a school-name query. Kept + # apart from CreateClass.school so a typed school name here is never sent off + # as a create-a-class query, and the pick payload is its own prefix. + school = State() + + class AddHomework(StatesGroup): subject = State() text = State() diff --git a/server/app/providers/netschool/client.py b/server/app/providers/netschool/client.py index c7feb22c..3c71c80e 100644 --- a/server/app/providers/netschool/client.py +++ b/server/app/providers/netschool/client.py @@ -427,6 +427,26 @@ async def diary_week( }, ) + async def schools_search(self, query: str) -> list[dict[str, Any]]: + """Search the region's schools by name, for binding a class. + + No session: the server answers this to the login page. Returns at most + what it gives; the caller cuts and indexes. A blocked address or a down + server raises, so the admin is told which rather than shown an empty + list they cannot tell from «no such school». + """ + response = await self._send( + "GET", "/webapi/schools/search", auth=False, params={"name": query[:60]} + ) + data = self._decode(response, step="schools/search") + if not isinstance(data, list): + raise UnexpectedResponse + out: list[dict[str, Any]] = [] + for row in data: + if isinstance(row, dict) and isinstance(row.get("id"), int) and row.get("name"): + out.append({"id": row["id"], "name": str(row["name"])}) + return out + async def terms_search(self, group_id: int | None) -> Any: # terms/search takes a JSON body, not a form. body = {"classIds": [group_id]} if group_id is not None else {} diff --git a/server/migrations/versions/0015_diary_provider_columns.py b/server/migrations/versions/0015_diary_provider_columns.py index 7140e9ba..12510005 100644 --- a/server/migrations/versions/0015_diary_provider_columns.py +++ b/server/migrations/versions/0015_diary_provider_columns.py @@ -95,7 +95,13 @@ def downgrade() -> None: "UPDATE diary_sessions SET expired_at = now() " "WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL" ) - for column in ("upstream_ok_at", "keepalive_attempted_at", "kept_alive_at", "region", "provider"): + for column in ( + "upstream_ok_at", + "keepalive_attempted_at", + "kept_alive_at", + "region", + "provider", + ): op.drop_column("diary_sessions", column) for column in ("diary_school_name", "diary_school_id", "diary_region"): op.drop_column("classes", column) diff --git a/server/tests/test_api_extended.py b/server/tests/test_api_extended.py index 8922ff4d..d92ff533 100644 --- a/server/tests/test_api_extended.py +++ b/server/tests/test_api_extended.py @@ -1605,6 +1605,9 @@ def now(cls, tz=None): "device_tokens_purged": 0, "diary_links_purged": 0, "device_invites_purged": 0, + "diary_sessions_kept_alive": 0, + "diary_sessions_lost": 0, + "diary_keepalive_failed": False, } assert len(tick_bot.sent) == 1 recipient, text = tick_bot.sent[0] diff --git a/server/tests/test_bot_diary.py b/server/tests/test_bot_diary.py index 4d9fb016..2f704c99 100644 --- a/server/tests/test_bot_diary.py +++ b/server/tests/test_bot_diary.py @@ -66,10 +66,10 @@ async def test_a_session_is_found_by_the_presser_and_never_by_the_class( await _bind(session, school_class) theirs = await _open_session(session, telegram_id=SOMEBODY_ELSE, class_id=school_class.id) - assert await handlers._session_for(session, MINE, school_class.id) is None + assert await handlers._session_for(session, MINE, school_class) is None mine = await _open_session(session, telegram_id=MINE, class_id=school_class.id) - found = await handlers._session_for(session, MINE, school_class.id) + found = await handlers._session_for(session, MINE, school_class) assert found.id == mine.id assert found.id != theirs.id @@ -77,22 +77,26 @@ async def test_a_session_is_found_by_the_presser_and_never_by_the_class( async def test_a_session_does_not_cross_between_classes(session, school_class): """A parent in two classes must not read one child's diary from the other class's screen — the session is keyed on both halves, always.""" - other = SchoolClass(name="9Б", school="Школа № 1", join_code="OTHER42") + other = SchoolClass( + name="9Б", school="Школа № 1", join_code="OTHER42", diary_provider="petersburg" + ) session.add(other) + await _bind(session, school_class) await session.commit() await _open_session(session, telegram_id=MINE, class_id=other.id) - assert await handlers._session_for(session, MINE, school_class.id) is None - assert await handlers._session_for(session, MINE, other.id) is not None + assert await handlers._session_for(session, MINE, school_class) is None + assert await handlers._session_for(session, MINE, other) is not None async def test_a_session_whose_key_no_longer_opens_it_is_dead(session, school_class): + await _bind(session, school_class) row = await _open_session(session, telegram_id=MINE, class_id=school_class.id) row.upstream_token = "not-a-fernet-blob" await session.commit() - assert await handlers._session_for(session, MINE, school_class.id) is None + assert await handlers._session_for(session, MINE, school_class) is None await session.refresh(row) assert row.expired_at is not None @@ -189,7 +193,7 @@ async def test_signing_out_drops_the_session_and_returns_the_door( await handlers.diary_sign_out(callback, session, school_class) - assert await handlers._session_for(session, MINE, school_class.id) is None + assert await handlers._session_for(session, MINE, school_class) is None assert "Пароль не вводится в чат" in callback.message.last @@ -221,7 +225,7 @@ async def test_signing_out_leaves_no_session_behind_to_walk_back_in_on( await handlers.diary_sign_out(CardCallback(user_id=MINE), session, school_class) - assert await handlers._session_for(session, MINE, school_class.id) is None + assert await handlers._session_for(session, MINE, school_class) is None async def test_signing_out_of_one_class_leaves_the_other_class_alone( @@ -230,7 +234,7 @@ async def test_signing_out_of_one_class_leaves_the_other_class_alone( """The bot addresses a session by (telegram_id, class_id) and nothing else, so «Выйти» in one class must not sign a parent out of the other child.""" await _bind(session, school_class) - other = SchoolClass(name="5Б", join_code="OTHER1") + other = SchoolClass(name="5Б", join_code="OTHER1", diary_provider="petersburg") session.add(other) await session.flush() await _open_session(session, telegram_id=MINE, class_id=school_class.id) @@ -238,7 +242,7 @@ async def test_signing_out_of_one_class_leaves_the_other_class_alone( await handlers.diary_sign_out(CardCallback(user_id=MINE), session, school_class) - still = await handlers._session_for(session, MINE, other.id) + still = await handlers._session_for(session, MINE, other) assert still is not None assert still.id == elsewhere.id @@ -861,14 +865,22 @@ def test_the_other_three_views_escape_the_upstream_too(): def test_the_signed_out_card_promises_the_password_never_enters_the_chat(): """The one sentence the whole ``diary_web`` sign-in form exists for.""" - text = diary_render.render_signed_out() + text = diary_render.render_signed_out("Санкт-Петербурга") assert "📒 Электронный дневник" in text + assert "дневнику Санкт-Петербурга" in text assert "Пароль не вводится в чат." in text assert "никто из класса не видит его за вас" in text assert "нигде не сохраняется" in text +def test_the_signed_out_card_names_the_bound_diary(): + """The card names whichever diary the class is bound to, in the genitive, + now that there is more than one — a card that always said Petersburg would + be a lie for «Сетевого города».""" + assert "дневнику «Сетевого города»" in diary_render.render_signed_out("«Сетевого города»") + + def test_the_signed_out_card_offers_a_way_in_only_when_there_is_one(): from app.bot.diary_keyboard import signed_out_keyboard diff --git a/server/tests/test_bot_manage.py b/server/tests/test_bot_manage.py index 5a451fe3..d0478e31 100644 --- a/server/tests/test_bot_manage.py +++ b/server/tests/test_bot_manage.py @@ -42,6 +42,11 @@ class_delete_apply, class_delete_prompt, class_diary_bind, + class_diary_cancel, + class_diary_provider, + class_diary_region, + class_diary_school, + class_diary_search, class_field_apply, class_field_prompt, class_root, @@ -121,6 +126,7 @@ time_ago, ) from app.bot.middlewares import active_class, prefs_key +from app.bot.states import BindDiary from app.db import SessionLocal from app.fsm_storage import DatabaseStorage from app.models import ( @@ -192,19 +198,30 @@ class FakeMessage: text: str | None = "" user_id: int = 42 replies: list[str] = field(default_factory=list) + markups: list[Any] = field(default_factory=list) bot: Any = None @property def from_user(self): return SimpleNamespace(id=self.user_id, username="tester", full_name="Тестер") - async def answer(self, text: str, **_: Any) -> None: + async def answer(self, text: str, reply_markup: Any = None, **_: Any) -> None: self.replies.append(text) + self.markups.append(reply_markup) @property def last(self) -> str: return self.replies[-1] + @property + def last_labels(self) -> list[str]: + """Every button caption on the keyboard of the last message, so a test + can check what can be pressed as well as what is written.""" + markup = self.markups[-1] + if markup is None: + return [] + return [button.text for row in markup.inline_keyboard for button in row] + @dataclass class FakeCallback: @@ -226,8 +243,9 @@ def alerted(self) -> bool: class FakeEditable(FakeMessage): - async def edit_text(self, text: str, **_: Any) -> None: + async def edit_text(self, text: str, reply_markup: Any = None, **_: Any) -> None: self.replies.append(text) + self.markups.append(reply_markup) @@ -2281,30 +2299,248 @@ async def test_a_field_prompt_that_expired_sends_the_admin_back_to_the_card( assert state.cleared -async def test_binding_and_unbinding_the_diary_flips_one_line_of_the_card( +async def test_binding_the_diary_opens_a_chooser_rather_than_binding_at_once( session, school_class ): + """There is more than one diary now, so «📒 Привязать дневник» opens a + chooser — it must not silently pick one, and it changes nothing yet.""" + callback = FakeCallback(message=FakeEditable()) + await class_diary_bind(callback, session, school_class, Role.ADMIN) + + assert school_class.diary_provider is None + assert "Выберите, к какому дневнику" in callback.message.last + labels = callback.message.last_labels + assert any("Санкт-Петербург" in label for label in labels) + assert any("Сетевой город" in label for label in labels) + + +async def test_choosing_petersburg_binds_it_and_the_card_says_so(session, school_class): """Binding gives the class nothing and takes nothing — it puts «📒 Мой дневник» on the menu — so the card is the only place it is visible.""" callback = FakeCallback(message=FakeEditable()) - await class_diary_bind(callback, session, school_class, Role.ADMIN) + await class_diary_provider( + callback, SimpleNamespace(value="petersburg"), session, school_class, Role.ADMIN + ) - assert school_class.diary_provider is not None + assert school_class.diary_provider == "petersburg" assert "📒 Дневник: Санкт-Петербург" in callback.message.last - again = FakeCallback(message=FakeEditable()) - await class_diary_bind(again, session, school_class, Role.ADMIN) + +async def test_unbinding_clears_every_diary_column_and_flips_the_card(session, school_class): + """Unbinding removes the door and everything behind it on the class — the + region and school of a «Сетевой город» binding go with the provider, or a + later rebind to Petersburg would carry a stale region no one can see.""" + school_class.diary_provider = "netschool" + school_class.diary_region = "moscow" + school_class.diary_school_id = 123 + school_class.diary_school_name = "Гимназия № 1" + await session.commit() + + callback = FakeCallback(message=FakeEditable()) + await class_diary_bind(callback, session, school_class, Role.ADMIN) assert school_class.diary_provider is None - assert "📒 Дневник: не привязан" in again.message.last + assert school_class.diary_region is None + assert school_class.diary_school_id is None + assert school_class.diary_school_name is None + assert "📒 Дневник: не привязан" in callback.message.last async def test_an_editor_cannot_bind_the_diary(session, school_class): + for handler in ( + lambda cb: class_diary_bind(cb, session, school_class, Role.EDITOR), + lambda cb: class_diary_provider( + cb, SimpleNamespace(value="petersburg"), session, school_class, Role.EDITOR + ), + ): + callback = FakeCallback(message=FakeEditable()) + await handler(callback) + assert school_class.diary_provider is None + assert callback.alerted + + +# -------------------------------------------------------------------------- +# Binding a class to «Сетевой город»: provider → region → school +# -------------------------------------------------------------------------- + + +class _FakeNetSchool: + """Stands in for NetSchoolClient: no network, scripted answers. + + ``login_error`` is what ``login_allowed`` raises (None = the region takes a + password), and ``schools`` is what a search returns. + """ + + login_error: Exception | None = None + schools: list[dict] = [] + + def __init__(self, region: Any) -> None: + self.region = region + + async def login_allowed(self) -> None: + if type(self).login_error is not None: + raise type(self).login_error + + async def schools_search(self, query: str) -> list[dict]: + return list(type(self).schools) + + +def _patch_netschool(monkeypatch, *, login_error=None, schools=None) -> None: + _FakeNetSchool.login_error = login_error + _FakeNetSchool.schools = schools or [] + monkeypatch.setattr("app.bot.handlers.manage.NetSchoolClient", _FakeNetSchool) + + +async def test_choosing_netschool_shows_the_region_list(session, school_class): callback = FakeCallback(message=FakeEditable()) - await class_diary_bind(callback, session, school_class, Role.EDITOR) + await class_diary_provider( + callback, SimpleNamespace(value="netschool"), session, school_class, Role.ADMIN + ) + + assert school_class.diary_provider is None # nothing bound yet + assert "регион" in callback.message.last.lower() + assert "Амурская область" in callback.message.last_labels + +async def test_a_password_region_asks_for_the_school_and_arms_the_search( + session, school_class, monkeypatch +): + _patch_netschool(monkeypatch) + callback = FakeCallback(message=FakeEditable()) + state = FakeState() + await class_diary_region( + callback, SimpleNamespace(value="amur"), session, school_class, Role.ADMIN, state + ) + + assert state.state == BindDiary.school + assert state.data["diary_region"] == "amur" + assert state.data["diary_class_id"] == school_class.id + assert "названия школы" in callback.message.last assert school_class.diary_provider is None + + +async def test_a_govru_only_region_is_refused_before_the_school_step( + session, school_class, monkeypatch +): + """A region that only lets families in through Госуслуги cannot be bound — + the admin is told once, not every family at sign-in.""" + from app.providers.diary.errors import SignInUnsupported + + _patch_netschool(monkeypatch, login_error=SignInUnsupported()) + callback = FakeCallback(message=FakeEditable()) + state = FakeState() + await class_diary_region( + callback, SimpleNamespace(value="amur"), session, school_class, Role.ADMIN, state + ) + + assert state.state is None assert callback.alerted + assert "Госуслуги" in callback.answers[-1][0] + + +async def test_an_unknown_region_key_is_refused(session, school_class, monkeypatch): + _patch_netschool(monkeypatch) + callback = FakeCallback(message=FakeEditable()) + state = FakeState() + await class_diary_region( + callback, SimpleNamespace(value="atlantis"), session, school_class, Role.ADMIN, state + ) + + assert state.state is None + assert callback.alerted + + +async def test_searching_shows_the_schools_the_region_found( + session, school_class, monkeypatch +): + _patch_netschool( + monkeypatch, + schools=[{"id": 11, "name": "Гимназия № 1"}, {"id": 22, "name": "Лицей № 2"}], + ) + message = FakeMessage(text="гимназия") + state = FakeState(data={"diary_region": "amur", "diary_class_id": school_class.id}) + await class_diary_search(message, session, state, school_class, Role.ADMIN) + + assert "Гимназия № 1" in message.last_labels + assert "Лицей № 2" in message.last_labels + assert state.data["diary_schools"][0]["id"] == 11 + + +async def test_a_search_that_finds_nothing_says_so(session, school_class, monkeypatch): + _patch_netschool(monkeypatch, schools=[]) + message = FakeMessage(text="школа которой нет") + state = FakeState(data={"diary_region": "amur", "diary_class_id": school_class.id}) + await class_diary_search(message, session, state, school_class, Role.ADMIN) + + assert "не найдена" in message.last.lower() + + +async def test_picking_a_school_binds_the_class_to_netschool(session, school_class): + callback = FakeCallback(message=FakeEditable()) + state = FakeState( + data={ + "diary_region": "amur", + "diary_class_id": school_class.id, + "diary_schools": [{"id": 11, "name": "Гимназия № 1"}], + } + ) + await class_diary_school( + callback, SimpleNamespace(value=0), session, Role.ADMIN, state + ) + + assert school_class.diary_provider == "netschool" + assert school_class.diary_region == "amur" + assert school_class.diary_school_id == 11 + assert school_class.diary_school_name == "Гимназия № 1" + assert state.cleared + assert "Сетевой город" in callback.message.last + assert "Амурская область" in callback.message.last + assert "Гимназия № 1" in callback.message.last + + +async def test_a_school_index_the_list_cannot_reach_is_refused(session, school_class): + """The pick carries an index into the searched list, never an id — an index + past the list is a stale keyboard, not a school to bind.""" + callback = FakeCallback(message=FakeEditable()) + state = FakeState( + data={ + "diary_region": "amur", + "diary_class_id": school_class.id, + "diary_schools": [{"id": 11, "name": "Гимназия № 1"}], + } + ) + await class_diary_school( + callback, SimpleNamespace(value=9), session, Role.ADMIN, state + ) + + assert school_class.diary_provider is None + assert callback.alerted + + +async def test_cancelling_the_school_pick_clears_the_state(session, school_class): + callback = FakeCallback(message=FakeEditable()) + state = FakeState(data={"diary_region": "amur"}) + await class_diary_cancel(callback, session, school_class, Role.ADMIN, state) + + assert state.cleared + assert school_class.diary_provider is None + + +async def test_an_editor_cannot_walk_the_netschool_flow(session, school_class, monkeypatch): + _patch_netschool(monkeypatch) + state = FakeState() + callback = FakeCallback(message=FakeEditable()) + await class_diary_region( + callback, SimpleNamespace(value="amur"), session, school_class, Role.EDITOR, state + ) + assert callback.alerted + assert state.state is None + + message = FakeMessage(text="гимназия") + editor_state = FakeState(data={"diary_region": "amur", "diary_class_id": school_class.id}) + await class_diary_search(message, session, editor_state, school_class, Role.EDITOR) + assert editor_state.cleared + assert school_class.diary_provider is None async def test_the_switch_screen_needs_somewhere_to_switch_to(session, school_class): @@ -3543,6 +3779,43 @@ async def send(name, call, data=None): await press( "class_diary_bind", lambda cb: class_diary_bind(cb, session, school_class, viewer) ) + await press( + "class_diary_provider", + lambda cb: class_diary_provider( + cb, SimpleNamespace(value="netschool"), session, school_class, viewer + ), + ) + await press( + "class_diary_region", + lambda cb: class_diary_region( + cb, SimpleNamespace(value="amur"), session, school_class, viewer, FakeState() + ), + ) + await press( + "class_diary_school", + lambda cb: class_diary_school( + cb, + SimpleNamespace(value=0), + session, + viewer, + FakeState( + data={ + "diary_region": "amur", + "diary_class_id": school_class.id, + "diary_schools": [{"id": 11, "name": "Ш"}], + } + ), + ), + ) + await press( + "class_diary_cancel", + lambda cb: class_diary_cancel(cb, session, school_class, viewer, FakeState()), + ) + await send( + "class_diary_search", + lambda m, st: class_diary_search(m, session, st, school_class, viewer), + data={"diary_region": "amur", "diary_class_id": school_class.id}, + ) await press( "calendar_rotate", lambda cb: calendar_rotate(cb, session, school_class, viewer) ) From c146de0b42db827f612a7468d1d4ab922843be93 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 22:09:59 +0000 Subject: [PATCH 06/30] Correct four diary comments that describe behaviour the code does not have MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while mapping the diary code for the second provider, each checked by hand (#138): - `services/diary_link.py` said the bot keeps a type-it-to-the-bot fallback for a deployment with no public URL. There is no such path — without `PUBLIC_BASE_URL` the bot says the sign-in page cannot be opened and stops — and the comment invited someone to «restore» a password in the chat history. - `main.py` said deferring the provider close-imports keeps all of them off the cold-start path. Measured: the API surface already loads Petersburg's and DaData's clients at module scope, so the deferral saves nothing for them; only «Сетевой город»'s client, loaded lazily through the registry, is genuinely kept off a process that never binds a class to it. The comment now says that. - `bot/diary_keyboard.py` said `offset` is the period index for «marks». «marks» ignores `offset` and always shows the last thirty days; «homework» reads a fixed window too. - `models.DiarySession`: `login` is not «for the signed-in-as line and nothing else» — a family's corrections are keyed on it (`owner_key`); and `telegram_id` is set by the bot's sign-in ticket, not «a linked device», and is NULL for the phone's login. The class docstring no longer claims the session is Petersburg's. The two dead diary names (`DiaryService.lessons`, `providers/petersburg. DiaryAccount`) were already removed with the seam. Closes #138. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/bot/diary_keyboard.py | 6 ++++-- server/app/main.py | 11 ++++++++--- server/app/models.py | 12 ++++++++---- server/app/services/diary_link.py | 5 +++-- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/server/app/bot/diary_keyboard.py b/server/app/bot/diary_keyboard.py index 897beecd..c5f0f909 100644 --- a/server/app/bot/diary_keyboard.py +++ b/server/app/bot/diary_keyboard.py @@ -31,8 +31,10 @@ class DiaryAction(CallbackData, prefix="dry"): """A cursor into somebody's diary. ``view`` — day | week | homework | marks | students | signin | signout. - ``offset`` — days from today for «day», weeks for «week», and the period - index for «marks»; one field because only one of them is ever live. + ``offset`` — days from today for «day», weeks for «week»; one field because + only one of them is ever live. «marks» ignores it and always shows the last + thirty days, and «homework» reads a fixed window from today, so neither + carries an offset here. """ view: str diff --git a/server/app/main.py b/server/app/main.py index a5b0bce2..dd4c0ff1 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -91,9 +91,14 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: with contextlib.suppress(asyncio.CancelledError): await bot_task # Each provider holds a process-wide pooled HTTP client; closing them - # is what returns their sockets rather than leaving them to a - # finaliser. Imported here rather than at module scope so none of them - # lands on the cold-start path of a request that uses none. + # is what returns their sockets rather than leaving them to a finaliser. + # Imported in this ``finally`` because that is the only place they are + # used. It is not a cold-start saving for Petersburg or DaData — the API + # surface (`api/diary.py`, the schools directory) already loads their + # clients at module scope — but «Сетевой город»'s client is loaded + # lazily through the registry and nothing else imports it, so keeping + # this import local does keep it off the path of a process that never + # binds a class to it. from app.providers.dadata import close_client as close_directory from app.providers.netschool.client import close_client as close_netschool from app.providers.petersburg import close_client diff --git a/server/app/models.py b/server/app/models.py index ebab84f4..57f58934 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -756,7 +756,8 @@ class AuditEntry(Base): class DiarySession(Base): - """A signed-in session with the Petersburg electronic diary. + """A signed-in session with an electronic diary — Petersburg or another; + which one is in ``provider``. What is stored here is the upstream's own session token and nothing else. Not the password: the reference implementations this integration was @@ -784,10 +785,13 @@ class DiarySession(Base): # Refreshed in place (and re-sealed) whenever the upstream hands back a new # one, which it does on most calls. upstream_token: Mapped[str] = mapped_column(Text, nullable=False) - # Who signed in, for the "you are signed in as" line and nothing else. + # Who signed in. Shown on the "you are signed in as" line, and also the key + # a family's corrections hang on (`services/diary.py:owner_key`), so the + # same login re-used later lays its overrides over the same lessons. login: Mapped[str] = mapped_column(String(200), nullable=False) - # The Telegram account this session belongs to, when it was created from a - # linked device. Null for a session created by login alone. + # The Telegram account this session belongs to. Set when the session was + # opened from the bot's sign-in ticket (`api/diary_web.py`); NULL for the + # phone's `POST /api/v1/diary/login`, which has no Telegram account. telegram_id: Mapped[int | None] = mapped_column(BigInteger, index=True) # The class the session was opened from, when it was opened in the bot. # Carried so that leaving a class can take its diary session with it, and diff --git a/server/app/services/diary_link.py b/server/app/services/diary_link.py index 610fee22..db78a29d 100644 --- a/server/app/services/diary_link.py +++ b/server/app/services/diary_link.py @@ -8,8 +8,9 @@ The alternative — typing it to the bot — puts it in the chat history, on Telegram's servers, in the notification that lands on a locked screen and in whatever backs that phone up. Deleting the message afterwards undoes exactly -none of those. The bot keeps that path as a fallback for a deployment with no -public URL, and says plainly that it is the worse one. +none of those, so there is no such path: a deployment with no ``PUBLIC_BASE_URL`` +has nowhere to serve the form, and `bot/handlers/diary.py` says the page cannot +be opened and stops there rather than falling back to a password in the chat. What Telegram ever carries is the code in this module: worth one sign-in, for fifteen minutes, for one Telegram account, in one class. Stored as a hash like From 9ceef0ceb53f2379aa3825e07a5758ef3cb0605c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 22:15:46 +0000 Subject: [PATCH 07/30] Teach the agent files the second diary provider and the 0015 head MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CLAUDE.md, the migration skill and the providers agent still described a one-diary world with the head at 0014. They now carry the diary seam (`providers/diary/` with its registry and `binding()`), «Сетевой город» behind it (the region allow-list as the SSRF guard, the password sign-in, the cron keep-alive, and that nothing here has met a live server), and revision `0015`: additive, seven nullable columns for the provider, region, keep-alive clocks and the class binding, on before this batch's merge, with a NULL provider meaning Petersburg. The test count moves from 1634 to 1668. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/agents/server-providers.md | 28 ++++++++++++++++++++++------ .claude/skills/migration/SKILL.md | 2 +- CLAUDE.md | 17 ++++++++++++++--- 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/.claude/agents/server-providers.md b/.claude/agents/server-providers.md index 047bcccc..32fb22de 100644 --- a/.claude/agents/server-providers.md +++ b/.claude/agents/server-providers.md @@ -1,6 +1,6 @@ --- name: server-providers -description: The two foreign services (petersburg, dadata), plus config.py and crypto.py. Use when an upstream shape changes or a setting is added. Knows which settings are mandatory on Vercel and which refuse in view of whoever they concern. +description: The foreign services (the diary providers petersburg and netschool behind the diary seam, and dadata), plus config.py and crypto.py. Use when an upstream shape changes or a setting is added. Knows which settings are mandatory on Vercel and which refuse in view of whoever they concern. tools: Read, Glob, Grep, Bash, Edit, Write --- @@ -9,13 +9,29 @@ You own `server/app/providers/`, `server/app/config.py` and `server/app/crypto.p ## The provider shape Each foreign service is `client.py` / `mapper.py` / `models.py`, and **nothing above -`models.py` knows the upstream's vocabulary** — not `p_educations[]`, not `X-JWT-Token`. If a -word from the upstream is leaking into a service or a handler, the mapper is incomplete. +`models.py` knows the upstream's vocabulary** — not `p_educations[]`, not `X-JWT-Token`, not +`at`. If a word from the upstream is leaking into a service or a handler, the mapper is +incomplete. -- `petersburg/` is the electronic diary. Without `DIARY_SECRET` it refuses at the door: the +- **The diary seam** is `providers/diary/`: `models.py`, `errors.py` (the `DiaryError` + family; `PetersburgError` is a re-export alias so old imports still resolve), a + `DiaryProvider`/`DiaryConnection` Protocol contract in `base.py`, and `registry.py` whose + `provider_for(key)` lazily imports the implementation and `binding(school_class)` is the + **one** place that resolves a class's diary binding (bot, main menu, class card and web + form all call it). A second diary is a value in `registry.KEYS`, never a rename. +- `petersburg/` is one electronic diary, behind that seam and byte-for-byte unchanged. Its session token is the one stored credential that cannot be a hash, because it is replayed - upstream on every call, so it is sealed with Fernet. A silent plaintext fallback is - invisible and deployments stay in that state for years. + upstream on every call, so it is sealed with Fernet — and without `DIARY_SECRET` the whole + diary feature refuses at the door. A silent plaintext fallback is invisible and deployments + stay in that state for years. +- `netschool/` is «Сетевой город. Образование» (ИРТех), the main diary of ~20 regions, one + route set for all of them. `regions.py` is an **allow-list**: the only origins ever + contacted, so nothing from a client or a DB row becomes a URL. Sign-in is a windows-1251 + salted-MD5 password; a region that answers with the Госуслуги-only refusal raises + `SignInUnsupported` and is not offered. Sessions idle out in 15–60 min and are held open + from the cron tick (`services/diary_keepalive.py`) with `GET /webapi/context`. **Nothing + here has met a live server** — every shape is from open-source clients and hand-written + payloads; the first real session is the owner's (#121/#135). - `dadata/` is the school directory, a search over the ЕГРЮЛ company register, because no downloadable register of Russian schools exists. Without `DADATA_TOKEN` it refuses and the bot asks for the name to diff --git a/.claude/skills/migration/SKILL.md b/.claude/skills/migration/SKILL.md index f59add2f..b34cf9dd 100644 --- a/.claude/skills/migration/SKILL.md +++ b/.claude/skills/migration/SKILL.md @@ -5,7 +5,7 @@ description: Write and apply an Alembic revision for this project — including # A migration, start to finish -Head is **`0013`**. Nothing after `0001` may use `create_all`. +Head is **`0015`**. Nothing after `0001` may use `create_all`. ## 1. Decide the direction diff --git a/CLAUDE.md b/CLAUDE.md index 596647ab..02979ef2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,7 +45,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 1634 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 1668 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at @@ -339,7 +339,7 @@ points Hilt does not inject cleanly. a half-applied revision cannot claim to be whole. And say what a revision destroys before running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a sentence the owner needs *before* the transaction, not after. -- **Migrations are Alembic and production is at `0014`, which is the head.** `0001` is a guarded +- **Migrations are Alembic and the head is `0015`, which goes on before this batch's merge.** `0001` is a guarded `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds @@ -360,7 +360,18 @@ points Hilt does not inject cleanly. `SAEnum` stores the member **name** — the column is exactly as wide as the longest one, so adding a kind is a migration rather than a line. It is the ordinary additive shape and went on **before** the merge; it rewrites no row - and every existing value stays what it was. + and every existing value stays what it was. `0015` adds the second diary + provider's columns: `diary_sessions.provider` and `region` (which diary and + which regional server a session is on, so a session can be matched to its + class's binding and grouped per origin for the keep-alive without unsealing + the credential), three keep-alive clocks (`kept_alive_at`, + `keepalive_attempted_at`, `upstream_ok_at`), and on `classes` the binding + `diary_region`, `diary_school_id` and `diary_school_name`. All seven are + nullable and additive — the ordinary shape, on **before** the merge — and + rewrite no row; a NULL `provider` on an existing session means Petersburg, the + only diary before the column. Its downgrade expires every non-Petersburg + session before dropping the columns that tell one apart, so reverted code + cannot replay a credential at the wrong upstream. Nothing after `0001` may use `create_all`. Beware the enum: `SAEnum(SomeStrEnum)` stores the member **name**, so a `server_default` written as `.value` is a string the ORM cannot read back — which on `classes` is a From 42fdf0a9eadec85988c42f92f14df52481fe3655 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 22:28:18 +0000 Subject: [PATCH 08/30] Document the second diary provider across docs and close out HANDOVER MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brings the documents into line with the «Сетевой город» batch, in the same batch as the code the skill on this project requires: - architecture.md — rewrites "Somebody else's service behind one door" around the `providers/diary/` seam: the shared models, errors, contract and registry, the two providers behind it, why Petersburg went behind it byte-for-byte, and the region allow-list as the SSRF guard. Services count 19 → 21. - api.md — the electronic diary is provider-neutral; documents the optional provider/region/school_id on `POST /diary/login` and the tick's three keep-alive counters; warmup schema 0014 → 0015. - bot.md — the binding chooser (region probe, school search), the sign-in card naming the bound diary, the submit-time binding re-check (#137), the logout asymmetry. - deploy.md — 0015 in the chain with its downgrade caveat, head 0015, the keep-alive as a dependency of the external cron. - diaries.md / diaries/netschool.md — the platform decision is made and the server side is written, with the "never run live" caveat kept. - README.md — the electronic diary row and the honest status now name «Сетевой город» as written server-side, never run; production head 0015. Corrects the counts that drift: tests 1634 → 1668, mypy modules 84 → 97, and the `0015` docstring's summary "Seven" → "Eight" nullable columns (its own bullet list already named all eight). HANDOVER.md carries the batch's close-out. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- CLAUDE.md | 4 +- HANDOVER.md | 192 ++++++++++++++---- README.md | 25 ++- docs/README.md | 2 +- docs/api.md | 51 ++++- docs/architecture.md | 85 +++++--- docs/bot.md | 38 ++-- docs/deploy.md | 26 ++- docs/diaries.md | 11 +- docs/diaries/netschool.md | 2 + .../versions/0015_diary_provider_columns.py | 2 +- 11 files changed, 321 insertions(+), 117 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 02979ef2..791d317c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Server, from `server/`: there. That shipped once. `tests/test_test_imports.py` now refuses a test module that imports another one at all — a shared fixture belongs in `conftest.py`, which pytest loads by path rather than by import -- **`python -m mypy`** — one question, of all 84 modules, in seconds: does anything reach +- **`python -m mypy`** — one question, of all 97 modules, in seconds: does anything reach for an attribute its type does not have? Configured in `pyproject.toml`, where every other error code is switched off by name with its count and its reason. Not in CI — the owner has not been asked — but run it before you push server code @@ -366,7 +366,7 @@ points Hilt does not inject cleanly. class's binding and grouped per origin for the keep-alive without unsealing the credential), three keep-alive clocks (`kept_alive_at`, `keepalive_attempted_at`, `upstream_ok_at`), and on `classes` the binding - `diary_region`, `diary_school_id` and `diary_school_name`. All seven are + `diary_region`, `diary_school_id` and `diary_school_name`. All eight are nullable and additive — the ordinary shape, on **before** the merge — and rewrite no row; a NULL `provider` on an existing session means Petersburg, the only diary before the column. Its downgrade expires every non-Petersburg diff --git a/HANDOVER.md b/HANDOVER.md index e50030f0..7091cd35 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -4,26 +4,34 @@ A working document, not part of the reference set in `docs/`. It describes **the the moment of handover**, so that a new session — human or agent — continues from the same place without reopening or redoing anything. -Last updated: **24 September 2026**. **PRs #63 through #85, #128, #129 and #133 are -merged**; `main` is at `5a77d14`, the merge of #133. `dev` is still at `a43c6e8`, the merge -of #129, because #133 went in from a branch of its own. It is behind `main` and has -nothing `main` lacks, so bringing it level is a fast-forward. **The only thing open is the -pull request carrying this paragraph, #134**, from `claude/school-diary-api-routes-cc4o1n`. -It closes #130 with a map of every region's electronic diary and the routes its platform -exposes. The SHA of its own merge is for the next close-out to write. - -**Nothing in the code has moved since #85.** #128, #129 and #133 changed documentation and -agent configuration. #134 changes documentation only: `docs/diaries.md`, `docs/diaries/`, -and the lines that count or link them in `CLAUDE.md`, `README.md`, `docs/README.md`, -`docs/architecture.md` and the `docs-keeper` agent. So the gates are where #85 left them, -and this close-out quotes them rather than running them again. - -**Once #134 merges, twenty issues are open, and the next step is on a device.** -**#109** is the epic and **#110–#117** are its children on `v0.8.0 — On a device`. -**#118–#122** are the owner's alone, and #123–#127 are `status:someday`. **#130** was the -one item a cloud session could do end to end, and #134 closes it. What it found is -**#135**, the owner's too: three decisions that come before any second diary provider is -written. +Last updated: **24 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are +merged**; `main` is at `fa4fe0c`, the merge of #134. `dev` is still at `a43c6e8`, the merge +of #129, because #133 and #134 each went in from a branch of their own. It is behind `main` +and has nothing `main` lacks, so bringing it level is a fast-forward. **The only thing open +is the pull request carrying this paragraph, #140**, a **draft** from +`claude/school-diary-api-routes-cc4o1n`. It closes #136, #137, #138 and the feature epic +#139. It **cannot merge yet**: the owner chose a new — tenth — milestone for it, e.g. +«v0.9.0 — A second diary», and nothing in a session here can create a milestone, so it stays +a draft with **no milestone** until the owner makes it. The SHA of its own merge is for the +next close-out to write. + +**Code moves again, after four documentation-only batches.** #128, #129, #133 and #134 +changed documentation and agent configuration only, so «nothing in the code has moved since +#85» stood through all of them. #140 ends that: it adds a second electronic diary, «Сетевой +город» (ИРТех NetSchool), behind a provider-neutral seam under `server/app/providers/diary/`, +and Петербург goes behind the same seam byte-for-byte unchanged. Two new provider packages +joined and server files across the api, bot, services and models changed, so the server gates +were **run**, not quoted (below), and a migration was written (`0015`) that is **not yet +applied**. The Android app was **not** touched — it stays Petersburg-only until batch 2, the +owner's «server first» decision. + +**Once #140 merges, four issues close (#136–#139) and twenty stay open.** **#109** is the +epic and **#110–#117** are its children on `v0.8.0 — On a device`. **#118–#122** are the +owner's alone, and #123–#127 are `status:someday`. **#135** — the owner's decision about +which diary comes second, how a family signs in, and whether ТОР may be used — **stays +open**: this batch answers its first part (it is «Сетевой город», and it takes a password) +but leaves the Госуслуги and ТОР questions to the owner. #136, #137 and #138 are the three +diary defects this batch fixed, and #139 is the feature epic it delivers. **Two things changed about how this project is tracked, and they are the reason to read on before planning anything.** @@ -40,18 +48,21 @@ something, so that a later session does not re-discover it as an oversight. From found defect becomes an issue before it becomes a fix. #131 and #132 are the first two filed under that rule. -**The database is at head `0014`** and has not moved since #77. **No server code -changed in #85** — not a model, not an endpoint — but four tests joined it, so the server -gates were run rather than quoted: `ruff` clean, `pytest -q -n auto` **1634 -passed**, `python -m mypy` clean across 84 modules. There was no migration to write, let -alone to apply; that is a fact about the batch rather than a thing left undone. -`EXPECTED_REVISION` in `app/db.py` is `0014`, pinned to the real head by -`tests/test_schema_version.py`. `0014` was applied to Neon before #77 merged, as an additive -revision should be — it widened `day_overrides.kind` from `VARCHAR(9)` to `VARCHAR(10)`, -because `DayKind` gained `SELF_STUDY` and a `SAEnum` column stores the member *name*. #83 -closed the class that revision belonged to: a pinned table of the ten enum column widths now -fails when a member's **name** outgrows its column, which SQLite cannot see and production -Postgres finds at the moment somebody marks a day. +**The code now expects head `0015`; the production database is still at `0014`, and `0015` +has not been applied.** `EXPECTED_REVISION` in `app/db.py` moved to `0015` (revision +`0015_diary_provider_columns`, pinned to the real head by `tests/test_schema_version.py`). +It is **additive** — five nullable columns on `diary_sessions` (`provider`, `region`, +`kept_alive_at`, `keepalive_attempted_at`, `upstream_ok_at`) and three on `classes` +(`diary_region`, `diary_school_id`, `diary_school_name`), a `NULL` provider meaning +Петербург — so like every additive revision in this chain it is applied to Neon **before** +the merge. **This is the outstanding pre-merge action:** apply `0015` through the Neon +connector (the project named `lessons`, read the name rather than guessing an id) before +#140 merges; it destroys nothing. The server gates were run rather than quoted: `ruff` +clean, `pytest -q -n auto` **1668 passed** (was 1634), `python -m mypy` clean across 97 +modules (`files = ["app"]`, 84 before the two new provider packages). The `0014` chapter +still holds: #83's pinned table of the ten enum column widths fails when a `SAEnum` member's +**name** outgrows its `VARCHAR`, which SQLite cannot see and production Postgres finds at the +moment somebody marks a day. Production was read after #60 and again after #61, rather than assumed: `/api/v1/health` answered `{"status":"ok","api_version":1}` and `/api/v1/warmup` — which opens a real @@ -61,8 +72,9 @@ found out why.** The deployments sit behind Vercel's Deployment Protection and a redirect to a login page, so `/api/v1/warmup` cannot be read from a session here at all — this is not an omission anybody can close with one more `curl`. It still wants reading, by the owner's browser or with a bypass token: #77 moved server code and the schema together, -so the answer should now be `"schema":"0014"`, and that single line is the cheapest check -that the migration and the code actually met. It is outstanding since #61. +so the answer should read `"schema":"0014"` today — and `"schema":"0015"` once #140's +migration is applied and its code deployed — and that single line is the cheapest check that +the migration and the code actually met. It is outstanding since #61. ## Where the work happens from here: a local machine @@ -116,7 +128,79 @@ next, someday, done) and `needs:` (device, owner). **A session cannot create a G Project board** — Projects v2 is GraphQL-only and the toolset here is REST — so the board is the owner's to make, and these labels are what its views filter on. -## What the last session added: the electronic diary of every Russian region, and the routes each platform exposes +## What the last session added: a second electronic diary, «Сетевой город», behind a provider-neutral seam + +Open as the **draft** PR #140, from `claude/school-diary-api-routes-cc4o1n`, closing #136, +#137, #138 and #139. It **has no milestone yet** and cannot merge until the owner creates one +(e.g. «v0.9.0 — A second diary»). Seven commits on `fa4fe0c`, `4c34cb5` through `9ceef0c`; +the server gates were run, not quoted. **The Android app was not touched.** + +The project read one diary, Петербург's, wired straight into `services/diary.py` and +`/diary/signin`. This batch puts a seam between the service and the provider, adds a second +provider behind it, and reads either from the same bot and API. + +- **A provider-neutral diary seam** lives under `server/app/providers/diary/`: the shared + models, a `DiaryError` family (`PetersburgError` re-exported as an alias so nothing that + caught it breaks), a `DiaryProvider` / `DiaryConnection` `Protocol` contract, and a + `registry.py` whose `binding()` is the single resolver of a class's diary binding. + Петербург goes behind it **byte-for-byte unchanged**. +- **«Сетевой город»** (`server/app/providers/netschool/`) — ИРТех NetSchool, the main diary + of about twenty regions, one route set for all. It carries a region **allow-list** (the + only origins ever contacted — the SSRF guard), windows-1251 salted-MD5 password sign-in, + the weekly diary mapped onto the existing models (homework is assignment type 3), + keep-alive, and school search for binding. +- **The service dispatches by provider.** `POST /api/v1/diary/login` now accepts optional + `provider` / `region` / `school_id` (for the phone's future batch), and + `services/diary_keepalive.py` keeps every live session alive from `GET /api/v1/cron/tick` + with `GET /webapi/context`, within a batch cap and a time budget, never touching + `last_used_at`. `TickOut` gained `diary_sessions_kept_alive`, `diary_sessions_lost` and + `diary_keepalive_failed`. +- **The bot binds and reads either diary.** An admin binds a class to «Сетевой город» through + a provider chooser → region → school-name search; the read path (`bot/handlers/diary.py`) + is provider-neutral — the sign-in card names the bound diary in the genitive, and a session + is keyed on the class's current provider. +- **Three diary defects fixed (#136, #137, #138).** #136: revoking a member now drops their + diary sessions and links, not just invites and subscriptions, so a revoked member no longer + holds a live credential for thirty days. #137: `/diary/signin` re-checks the class binding + at submit and refuses **before** spending the ticket if the diary was unbound or rebound + after the ticket was issued. #138: four false diary comments corrected and two dead type + names removed. + +### Schema + +`EXPECTED_REVISION` is now `0015` (revision `0015_diary_provider_columns`), which adds the +eight nullable columns named in the opening — five on `diary_sessions`, three on `classes`. It +is **additive** and **must be applied to Neon before the merge**; it has **not** been applied +yet, and the production database is still at `0014`. A `NULL` provider means Петербург, so the +running code is happy without the columns and the code that needs them is #140's. + +### What was deliberately left alone + +- **Госуслуги (ЕСИА) sign-in.** Some regions have switched passwords off and answer with a + clear refusal, which the client surfaces as `SignInUnsupported`. Driving ЕСИА ourselves is + #135's decision, not this batch's. +- **The refresh-token grant (LoginType 9).** It exists in the client but is unverified live. +- **SignalR reports** — final marks, attendance letters — are not read. +- **Everything on the phone.** The Android app stays Petersburg-only until batch 2 (region and + school at sign-in, the zone from the server, neutral strings). That «server first» order was + the owner's decision. + +### Gates + +Run on the final head, not quoted: `ruff check app tests scripts migrations` clean; +`pytest -q -n auto` **1668 passed** (was 1634); `python -m mypy` **Success** across 97 modules +(`files = ["app"]`, 84 before the two provider packages joined). Android was not touched, so +`./gradlew test` was not re-run and stands at **968**. + +### What nobody has verified in this batch + +**No code here has met a live «Сетевой город» server with a real account.** Every upstream +shape — the salted-MD5 sign-in dance, `/webapi/context`, the weekly diary, the school search — +is from open-source clients and hand-written test payloads, never from a server seen +answering. The first live sign-in is the owner's (#121, #135), the same caveat that stands +for Петербург. + +## What the session before it added: the electronic diary of every Russian region, and the routes each platform exposes Open as PR #134, from `claude/school-diary-api-routes-cc4o1n`, in the milestone `v0.8.0 — On a device`; it closes #130. **Documentation only.** No file under `server/`, @@ -200,7 +284,7 @@ passed. What was checked instead, on the final head: - every table row has its header's column count; - the redaction scan finds no credential. -## What the session before it added: the tracker (#128), its rule (#129), and their close-out (#133) +## What the batch before added: the tracker (#128), its rule (#129), and their close-out (#133) Documentation and agent configuration only. No model, endpoint, screen or test changed, so the gates stand exactly where #85 measured them. @@ -2049,9 +2133,14 @@ released, so `versionName` is still the `0.1.0` default. | 5 | `v0.5.0 — A public repository` | #46–#49, #51, #55–#57, #59 | | 6 | `v0.6.0 — One container, and nothing cut off` | #60–#74 | | 8 | `v0.7.0 — Оптимизация` | #75–#85, #128 — the one Russian title | -| 9 | `v0.8.0 — On a device` | issues #109–#117, #130–#132; #129, #133 and #134 — **the current one** | +| 9 | `v0.8.0 — On a device` | issues #109–#117, #130–#132; #129, #133 and #134 — the latest that **exists** | | 7 | `Dependencies` | every dependabot bump; deliberately not a version | +**A tenth milestone does not exist yet, and #140 waits on it.** The second-diary work +belongs to none of the nine — it is neither «On a device» nor a dependency bump — so the +owner was asked to create a tenth, e.g. «v0.9.0 — A second diary», with the title and +description already written. Until they do, #140 is a draft with no milestone. + **Nothing in a session here can create a milestone**, only attach one — the owner created the ninth on 22 September 2026 and issues #109–#117 are on it. **It is the first milestone that groups issues rather than pull requests**, and the first whose work cannot be done @@ -2483,8 +2572,8 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 1634 tests, ~4 min (CI runs this) -cd server && python -m mypy # clean, 84 modules +cd server && pytest -q -n auto # 1668 tests, ~4 min (CI runs this) +cd server && python -m mypy # clean, 97 modules cd android && ./gradlew test # 968 tests across the five modules cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` @@ -2866,6 +2955,14 @@ an issue title cannot. ТОР «Моя школа» rests on one app build, 5.0.0.454, and its first-wave list rests on one official post. The first live session on any platform will correct its page. Whoever has it should edit the page by hand, because the generator is not in the repository. +- **The «Сетевой город» provider has never met a live server.** #140 wrote the client, the + mapper, the keep-alive and the school search from open-source clients and hand-written test + payloads; no ИРТех server answers a cloud session, so none was called. Every upstream shape + — the salted-MD5 sign-in, `/webapi/context`, the weekly diary, the school search — is what a + client sends, not what a server was seen to accept. The refresh-token grant (LoginType 9) + and the Госуслуги refusal path (`SignInUnsupported`) are the least exercised of all. The + first live sign-in on it is the owner's, #121's caveat a second time; #135 is the decision + that precedes it. - **Nothing of the tab arranging has been seen on a phone, and it is a gesture.** #84 is a long press, a wobble and a drag; #85 is the drag actually reporting where it landed. What the 39 tests prove is arithmetic and contracts: where a drag of so many pixels lands, that @@ -3672,12 +3769,21 @@ environment, #119 `/api/v1/warmup` and the bot's `/start`, #120 the external cro `DADATA_TOKEN`, #121 the real diary, #122 the widget's tick cadence and the diary credential's bound, #135 the second diary. Each carries the label `needs:owner`. -**Decide what the second diary is before anybody writes it (#135).** `docs/diaries.md` is -the map, and three things on it are decisions rather than research: +**Create the tenth milestone so #140 can leave draft.** #140 adds the second diary and closes +#136–#139, but it belongs to no existing milestone; nothing in a session here can create one, +so it stays a draft until the owner makes a tenth (e.g. «v0.9.0 — A second diary») and +attaches it, with the title and description already handed over. + +**The keep-alive is only as alive as the cron (#120).** «Сетевой город» sessions are held +open from `GET /api/v1/cron/tick`, so they lapse if the external cron does not tick; +`.github/workflows/reminders.yml` is the fallback, not the clock, exactly as for the digests. + +**#140 answered the first of #135's three questions; the other two remain.** `docs/diaries.md` +is the map: -- **Which platform.** The survey's order is «Сетевой город» first: one route set, the +- **Which platform — settled.** #140 built «Сетевой город» server-side: one route set, the largest group of regions, and a password still accepted outside the regions that allow - Госуслуги only. The МЭШ family comes after it. + Госуслуги only. The МЭШ family comes after it. Against a live server it has not been read. - **How a family signs in**, now that Госуслуги is the only door in most regions. Either the server accepts a token a person brought from a browser, which is what every durable client does, or it drives ЕСИА itself and breaks whenever Госуслуги changes its login. diff --git a/README.md b/README.md index ebc25095..bd3223c4 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ time zones from Kaliningrad to Kamchatka. | **Notifications** — the bell, the morning digest, tomorrow's homework, substitutions | local alarms, no push | [docs/design.md](docs/design.md#notifications) | | **Bot** — and the admin panel: roles, timetable, bells, subjects, the log, who may connect a phone | aiogram 3 | [docs/bot.md](docs/bot.md) | | **Server** — reads and writes over `/api/v1`, the reminder tick, the calendar | FastAPI, SQLAlchemy 2, Alembic | [docs/api.md](docs/api.md) | -| **Petersburg electronic diary** — the family's timetable, assignments and marks, with corrections laid over them | a separate account, behind one boundary | [docs/api.md](docs/api.md#the-petersburg-electronic-diary) | +| **Electronic diary** — the family's timetable, assignments and marks, with corrections laid over them; «Петербургское образование» and «Сетевой город» behind one boundary | a separate account | [docs/api.md](docs/api.md#the-electronic-diary) | One process and one database: the bot and the client-facing API live together, and the rule by which something changes lives in one place for both — @@ -175,7 +175,7 @@ The index is [docs/README.md](docs/README.md). In short: * [docs/guide.md](docs/guide.md) — how to use it: first run, widget, notifications, bot, diary * [docs/architecture.md](docs/architecture.md) — how it is all put together and why exactly so -* [docs/api.md](docs/api.md) — the `/api/v1` contract, including the Petersburg diary +* [docs/api.md](docs/api.md) — the `/api/v1` contract, including the electronic diary * [docs/bot.md](docs/bot.md) — roles, invitations by phone number, editing the timetable * [docs/widget.md](docs/widget.md) — sizes, states, the update schedule * [docs/build.md](docs/build.md) — building the APK, signing, releases, pointing it at a server @@ -197,8 +197,8 @@ Read this before planning a release. | Check | Result | | --- | --- | | `ruff check app tests scripts migrations` | clean | -| `python -m mypy` | clean, 84 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 1634 tests, green, about four minutes — the command CI runs | +| `python -m mypy` | clean, 97 modules — asks whether anything reaches for an attribute that does not exist | +| `pytest -q -n auto` | 1668 tests, green, about four minutes — the command CI runs | | `./gradlew test` | 968 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | @@ -230,11 +230,16 @@ nothing about what happens on the screen. Covered by nothing: Material 3 Expressive and Glance 1.3.0-alpha02 are alphas. They compile, but nobody has measured how they behave across Android versions. -The electronic diary in the bot has never once been opened against the real -dnevnik2.petersburgedu.ru — neither the sign-in page nor any of the four screens. The -tests run a hand-written stub in place of the diary: that is the only honest way to check -an integration with an undocumented service, but it says nothing about what that service -actually answers. No browser has ever opened the sign-in page. +The electronic diary has never once been opened against a real server. Not Petersburg's +dnevnik2.petersburgedu.ru — neither the sign-in page nor any of the four screens — and not +«Сетевой город. Образование», the second provider, which is **written server-side only and +has never met a live regional server**: its password sign-in, its keep-alive, its region +allow-list and its weekly-diary mapping are read from open-source clients and exercised on +hand-written payloads, exactly as Petersburg's were. The tests run a hand-written stub in +place of each: that is the only honest way to check an integration with an undocumented +service, but it says nothing about what that service actually answers. No browser has ever +opened the sign-in page for either, and the first live session, for both, is the owner's +(#121, #135). **Week parity was computed from the ISO week number, and that broke once every five or six years.** In an ISO year with 53 weeks, week 53 and week 1 stand next to each other and are @@ -396,7 +401,7 @@ one of them is proved by a test rather than by a screen. Robolectric, against a fake. Which of the four a phone shows when pointed at production, nobody has watched. * **`/api/v1/warmup` itself has not been read since #61**, when it answered - `{"status":"ok","api_version":1,"schema":"0013"}`. Production is at `0014` now, so it + `{"status":"ok","api_version":1,"schema":"0013"}`. Production is at `0015` now, so it should say so, and that one request is the cheapest check of whether the migration and the code that needs it actually met — but the deployment previews sit behind Vercel's protection, and nobody has made the check against production either. diff --git a/docs/README.md b/docs/README.md index 8b489ab8..c5a8e82f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,7 +26,7 @@ answer is not here it is in the code, and there is usually a link to it. | [widget.md](widget.md) | twelve sizes, seven states, the update schedule, why not a tick once a minute | | [build.md](build.md) | standing the project up from a clone and how much of `server/.env` each step needs, the eight secrets Actions holds and what reads them, building the APK in Actions and locally, signing with your own key, a release from a tag, Actions minutes and where they go, the bundled typeface, pointing the app at a server | | [deploy.md](deploy.md) | Vercel plus Neon or your own server, the webhook, migrations, why the server has no clock of its own | -| [api.md](api.md) | the whole `/api/v1` contract: reads, writes, class management, the Petersburg diary | +| [api.md](api.md) | the whole `/api/v1` contract: reads, writes, class management, the electronic diary — Петербург and «Сетевой город» behind one contract | | [architecture.md](architecture.md) | why the bot is the backend, the timetable resolution model, the five Android modules, the service layer, the tests | | [design.md](design.md) | the design system: what was taken from Essentials, what was fixed, and the reasoning behind every visible decision in the interface | | [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from | diff --git a/docs/api.md b/docs/api.md index 37f3ffd3..089c47b8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -922,7 +922,7 @@ minutes but is only the fallback, for the measured reason in | `404` | `CRON_SECRET` is unset: the endpoint does not exist, like the webhook without its secret | | `403` | Wrong or missing header (constant-time comparison) | | `503` | `BOT_TOKEN` is unset: nothing to send with | -| `200` | `{"morning": 1, "evening": 0, "tasks": 2, "failed": 0, "fsm_purged": 0, "join_attempts_purged": 3, "diary_sessions_purged": 0, "device_tokens_purged": 0, "diary_links_purged": 0, "device_invites_purged": 0}` | +| `200` | `{"morning": 1, "evening": 0, "tasks": 2, "failed": 0, "fsm_purged": 0, "join_attempts_purged": 3, "diary_sessions_purged": 0, "device_tokens_purged": 0, "diary_links_purged": 0, "device_invites_purged": 0, "diary_sessions_kept_alive": 4, "diary_sessions_lost": 1, "diary_keepalive_failed": false}` | What is due is decided from each class's own clock and from what was already sent today, never from when the last tick ran - so a tick that runs twice in @@ -944,6 +944,18 @@ runs between requests: has to work in September. A device in use is marked no less than once every 15 minutes, on any read. +The same tick also **keeps «Сетевой город» sessions alive**. That diary idles a session out +in 15–60 minutes and this project stores no password to sign back in with, so the tick pings +each live one with `GET /webapi/context`, within a batch cap and a time budget, and never +touches `last_used_at` — a ping must not look like the family using the session, or the +30-day purge above would never fire. `diary_sessions_kept_alive` is how many were pinged +alive, `diary_sessions_lost` how many the upstream had already dropped (they are expired, and +the app is told to sign in again), and `diary_keepalive_failed` is `true` when the keep-alive +itself raised — isolated so a diary fault never fails the whole tick and reddens the fallback +clock. Petersburg sessions are not pinged; they refresh from their own answers. This depends +on the external cron, not GitHub's fallback clock, which is too sparse to keep a session +alive; [deploy.md](deploy.md#the-clock-the-server-has-none-and-githubs-will-not-do) says why. + ## `GET /api/v1/health` and `GET /api/v1/warmup` Both unauthenticated. `/health` returns `{"status": "ok", "api_version": 1}` and @@ -957,7 +969,7 @@ whether the schema is the one this code was written against. Three answers: | | Body | Meaning | | --- | --- | --- | -| `200` | `{"status": "ok", "api_version": 1, "schema": "0014"}` | the database is reachable and at the revision the code expects | +| `200` | `{"status": "ok", "api_version": 1, "schema": "0015"}` | the database is reachable and at the revision the code expects | | `200` | `{"status": "degraded", …, "schema": …, "expected_schema": …, "detail": …}` | both revisions named, and `detail` says **which way** they diverge | | `503` | `{"status": "down", "api_version": 1, "detail": "База недоступна."}` | the database could not be reached | @@ -977,18 +989,25 @@ The app draws all of this as a badge on **Настройки → О прилож the one place in the interface that tells those four apart. See [design.md](design.md#the-about-footer). -## The Petersburg electronic diary +## The electronic diary A separate surface under `/api/v1/diary`. Separate because it is a different thing: `/api/v1` hands out the class's timetable, which the bot fills in, while this is one -family's account in somebody else's service, `dnevnik2.petersburgedu.ru`. They have nothing -in common but the server. - -**The app never talks to dnevnik2.petersburgedu.ru directly.** Not one of that service's -parameters — `p_educations[]`, `p_datetime_from`, `X-JWT-Token`, `estimate_type_code`, -`hash_uid` — crosses the boundary of our API. If a field is renamed up there tomorrow, one -directory is what gets fixed, `app/providers/petersburg/`, and neither the app nor this -document changes. +family's account in a service this project does not run. They have nothing in common but the +server. + +There are two such services behind this one surface — «Петербургское образование» +(`dnevnik2.petersburgedu.ru`) and «Сетевой город. Образование», the diary of about twenty +regions — and **the API does not change between them.** Which one a session is with is +decided at sign-in and stored on the session; every endpoint below is provider-neutral, and +the client reads the same shapes whichever diary answered. «Сетевой город» is server-side +only and has never been tried against a live server (see the README's honest status). + +**The app never talks to either service directly.** None of an upstream's parameters — +Petersburg's `p_educations[]`, `X-JWT-Token`, `estimate_type_code`, or «Сетевой город»'s `at` +bearer and `scid` — crosses the boundary of our API. If a field is renamed up there tomorrow, +one directory is what gets fixed (`app/providers/petersburg/` or `app/providers/netschool/`), +and neither the app nor this document changes. ### Signing in @@ -1001,6 +1020,16 @@ POST /api/v1/diary/login { "token": "…", "login": "parent@example.com" } ``` +`provider`, `region` and `school_id` are optional. Absent `provider` means Petersburg, so a +phone that sends only a login and a password signs in there exactly as before. For «Сетевой +город», `provider` is `"netschool"`, `region` is a key into the server's own allow-list and +`school_id` the upstream's school id; both are validated in the route before any upstream +call, so an unknown region or a missing school is a `422`, and a region that takes only +Госуслуги — or one whose server refuses this deployment's address — answers `503`, which the +sign-in limiter does not count because nothing there looked at the password. The bot already +binds a class to a region and a school for its own web sign-in form; these fields are for a +phone that will one day sign in to «Сетевой город» directly. + **The password is not stored.** It is needed for exactly one request — the login to somebody else's service — after which it is forgotten. Only the diary's own session is stored, and it is refreshed on the fly: the service hands back a fresh token on almost every diff --git a/docs/architecture.md b/docs/architecture.md index 92da83ac..000887cb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -62,8 +62,8 @@ on serving every webhook. What it deliberately does *not* hold is written out at the top of the module: the engine, which is built at import so that an unusable `DATABASE_URL` fails -at the door rather than on the first query, and the two providers' HTTP -clients, which are already process-wide singletons closed in the lifespan. +at the door rather than on the first query, and the provider HTTP clients, +which are already process-wide singletons closed in the lifespan. Two things to know before adding to it. The container is built with `STRICT_VALIDATION`, so declaring a second provider for a type that already has @@ -299,7 +299,7 @@ can swap wholesale. ## The service layer, and why the phone does not log in -`server/app/services/` is nineteen modules of pure async functions over a session, and +`server/app/services/` is twenty-one modules of pure async functions over a session, and they exist for exactly one reason: every feature of the product now has two entrances, the bot and the app. Homework is added by a command in a chat and by a button on a phone; so are a substitution, an event and a special day. Two implementations of one rule would have @@ -339,26 +339,59 @@ lifetimes and the reasoning behind them are in `api.md`, in the section about ## Somebody else's service behind one door -`server/app/providers/petersburg/` is the integration with St Petersburg's electronic -diary. The service is undocumented: its addresses, its parameter names and the shapes of -its answers were established from the open clients that talk to it, and used as a map -rather than copied. Everything else about how this directory is arranged follows from that. -What every other region runs, and the routes of each of those platforms as their open clients -call them, is surveyed in [diaries.md](diaries.md) — the map a second provider would be -written from. - -The boundary is drawn in three files and held by them: +An electronic diary is a family's account in a service this project does not run, does not +document and cannot change. There are two of them now, and the shape they meet is the point +of the whole integration. `server/app/providers/diary/` holds what every provider shares: +the models the rest of the application reads, the error family a route turns into a status +code, the `DiaryProvider` / `DiaryConnection` contract a provider implements, an HTTP client +whose cookie jar keeps nothing (so two families' sessions can never meet), and a `registry`. +`services/diary.py` opens whichever provider a session row names and calls it through that +contract; it never learns which upstream is behind it. + +- **`app/providers/petersburg/`** — «Петербургское образование» (`dnevnik2.petersburgedu.ru`), + the first provider and still the only one that signs in with an email and a password alone. +- **`app/providers/netschool/`** — «Сетевой город. Образование», the diary of about twenty + regions on one route set (`/webapi`) served from a different regional host in each. It is + server-side only, and **it has never met a live server**: every upstream shape is read from + open-source clients and hand-written payloads, exactly as Petersburg's was (#121, #135). + +What every region of the country runs, and the routes of each platform as its open clients +call them, is surveyed in [diaries.md](diaries.md); [diaries/netschool.md](diaries/netschool.md) +is the reference page «Сетевой город» was written from. + +Petersburg pre-dates the seam and went behind it **byte-for-byte**. Every public name it had +— `PetersburgError`, the mapper functions, `today` — is now a re-export of the object defined +in `diary/`, so `PetersburgError` *is* `DiaryError` and nothing that imported the old names +broke; a thin `petersburg/provider.py` wraps the existing client and mapper behind the +contract. Rewriting the one provider a real account has been promised against, for behaviour +no reader would see, was the change deliberately not made. + +`registry.py` answers two questions in one place. `provider_for(key)` maps a stored key to an +implementation, importing the provider module lazily so neither upstream's HTTP client lands +on the cold-start path of a request that does not use it. `binding(school_class)` resolves +what a class is bound to; the bot menu, the class card and the web form all call it, so "is +this class bound, and to what" has a single answer, and a class bound to a «Сетевой город» +region since dropped from the allow-list reads as unbound rather than as a dead name. + +The boundary each provider draws is three files, and it holds them: | File | Knows | | --- | --- | -| `client.py` | the addresses, the parameters, the session cookie, the date formats | +| `client.py` | the addresses, the parameters, the session token, the date formats | | `mapper.py` | what the fields in the answers are called, and what code 30000 means | -| `models.py` | none of the above — these are our own application's models | +| the shared `diary/models.py` | none of the above — these are our own application's models | + +Above the models, nobody knows the words `p_educations[]`, `X-JWT-Token`, `weekDays` or the +`at` bearer. When a field is renamed upstream, that provider's `mapper.py` is what gets +fixed; when an endpoint moves, its `client.py` is. The public API and the Android app do not +change, and that is what the whole arrangement was for. -Above `models.py`, nobody knows the words `p_educations[]`, `estimate_value_name` or -`X-JWT-Token`. When a field is renamed upstream, `mapper.py` is what gets fixed; when an -endpoint moves, `client.py` is. The public API and the Android app do not change, and that -is what the whole arrangement was for. +**Nothing turns free text into a host.** «Сетевой город» is one route set proxied to a server +chosen by region, so its `regions.py` is an allow-list first and a directory second: a region +key that reaches sign-in — from a client body, a class row or a sealed credential — is looked +up there, and one not in the table is refused before any network call. That is the whole SSRF +guard. The shared client follows no redirect and never turns TLS verification off, so the +session bearer cannot ride a cross-origin 30x to another host. The mapper is deliberately lenient: a field is looked for under every name it has ever appeared under, and a row that could not be read is dropped rather than failing the @@ -374,15 +407,19 @@ that is not a bad row any more, it is a changed response shape, and a `WARNING` with the list of keys that arrived: an empty week caused by a renamed field and an empty week caused by the holidays look identical from above otherwise. -The password is not stored. A login is needed for one request, after which the service's own -session is what lives on, refreshed from its own answers. When it dies, the request answers -`401` with `X-Diary-Reauth: required`, and the app asks for the password again. The price is -that a background sync of the diary does not outlive the session; the price of the -alternative is every family's password in the database. +The password is not stored, for either diary. A login is needed for one request, after which +the upstream's own session is what lives on. Petersburg refreshes it from its own answers and +we simply keep the newest; «Сетевой город» idles a session out in 15–60 minutes, so the cron +tick keeps each live one alive with `GET /webapi/context` (the mechanism is in +[deploy.md](deploy.md#the-clock-the-server-has-none-and-githubs-will-not-do), the counters in +[api.md](api.md)). When a session dies either way, the request answers `401` with +`X-Diary-Reauth: required` and the app asks for the password again. The price is that a +background sync of the diary does not outlive the session; the price of the alternative is +every family's password in the database. ## Testing -1634 tests on the server, 968 on Android; `pytest -q -n auto` and `./gradlew test`, both +1668 tests on the server, 968 on Android; `pytest -q -n auto` and `./gradlew test`, both offline, both in CI. On Android that is `:core:model` 125, `:core:data` 286, `:core:designsystem` 95, `:widget` 90, `:app` 368. diff --git a/docs/bot.md b/docs/bot.md index 6484497d..d73cf6d1 100644 --- a/docs/bot.md +++ b/docs/bot.md @@ -472,10 +472,15 @@ replaces SQLite's ASCII-only version with Python's on every connection, so ## The electronic diary — «📒 Мой дневник» -An admin binds the class in **⚙️ Класс → 📒 Привязать дневник**. Binding gives -the class *nothing*: it puts one button on every member's menu, and behind that -button is each member's own dnevnik2 account. Nobody in the class sees anybody -else's child. +An admin binds the class in **⚙️ Класс → 📒 Привязать дневник**. That is no longer a +single toggle: with a second diary it opens a chooser. «Петербургское образование» +binds in one press; «Сетевой город» asks for the **region**, then the **school**. The +region step probes that region's sign-in options first, so an admin learns once that a +Госуслуги-only region cannot be bound, rather than every family finding out at sign-in; +the school step searches the region's own server by name and offers what it found. Binding +gives the class *nothing*: it puts one button on every member's menu, and behind that button +is each member's own account with the bound diary. Nobody in the class sees anybody else's +child. That is enforced rather than asserted. Every lookup in `handlers/diary.py` starts from `callback.from_user.id`, and a session is found by @@ -484,11 +489,17 @@ presser's own diary or nothing at all. The class half matters too: a parent in two classes must not read one child's diary from the other class's screen. **The password never enters Telegram.** «🔐 Войти в дневник» hands out a link to -`/diary/signin/`, a page this app serves itself. The password goes from -that browser straight to dnevnik2 and is written down nowhere — not in the chat +`/diary/signin/`, a page this app serves itself. Its subtitle names the bound +diary — and, for «Сетевой город», its region and school (the school name escaped, because +it came from the upstream's search) — so the family can see where the password is going. +The password goes from that browser straight to the bound diary (dnevnik2 for Петербург, +the region's own server for «Сетевой город») and is written down nowhere — not in the chat history, not on Telegram's servers, not in the notification on a locked screen, -not in the phone's backup. A ticket is worth **one** sign-in for fifteen -minutes for one Telegram account in one class; a GET checks it without spending +not in the phone's backup. The form re-reads the class's binding at both the GET and the +submit, so a class unbound or rebound since the link was made refuses before the password +is sent, rather than sending it to a diary the family is no longer looking at. A ticket is +worth **one** sign-in for fifteen minutes for one Telegram account in one class; a GET +checks it without spending it (Telegram fetches link previews by itself), a POST spends it before attempting the sign-in, and a malformed form does not spend it at all. The one failure that hands the ticket back is a diary that did not answer — a transport @@ -511,8 +522,8 @@ with several children is asked once, in **👥 Ребёнок**, and the answer the session. **Выйти** drops every session this account holds in this class — one row is one sign-in and nothing expires an earlier one, so «вышли» that dropped only the newest left the next press walking straight back in; the other -class of a parent with two children is untouched. The upstream is not told, -because it has no logout that can be called without a browser. +class of a parent with two children is untouched. The upstream is told goodbye where it +can be: «Сетевой город» has a logout that works without a browser, Петербург does not. An empty answer is always said, never drawn as a blank: the upstream returns nothing for the holidays, for a day it has no data for, and for a register a teacher @@ -659,9 +670,10 @@ renderer. a row is only a number. * **Cut before escaping, never after.** Cutting an escaped string can leave «&am», which is a refused message of its own. -* **Everything from outside is escaped.** Anything the Petersburg diary sends, - anything typed into the bot or pasted into the timetable grammar (a subject - really can be «Алгебра <7>»), and anything out of the schools registry. +* **Everything from outside is escaped.** Anything a diary sends — Петербург's or + «Сетевого города»'s, down to a school name from its search — anything typed into the bot + or pasted into the timetable grammar (a subject really can be «Алгебра <7>»), and + anything out of the schools registry. * **An alert is not a card.** `answerCallbackQuery` takes no parse mode, so a card built for a message shows its own tags in the popup, and Telegram answers 400 past 200 characters — which means the press answers nothing at all. diff --git a/docs/deploy.md b/docs/deploy.md index f559c681..00543123 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -299,11 +299,16 @@ from `create_all` — on ours it does not, because the DDL for `0009` came from no-op: all eight really were nullable, and all eight held no nulls, so it tightened them and rewrote nothing. `0013` adds `uq_homework_per_subject_per_day`. `0014` widens `day_overrides.kind` to `VARCHAR(10)`: `DayKind` gained `SELF_STUDY`, and a `SAEnum` -stores the member name, so the column is as wide as the longest of them. +stores the member name, so the column is as wide as the longest of them. `0015` adds the +columns a second diary provider needs: `diary_sessions.provider` and `region` and the three +keep-alive clocks, and `classes.diary_region`, `diary_school_id` and `diary_school_name` — +eight nullable columns, additive, applied before the merge. Its downgrade expires every +non-Petersburg session first, so code rolled back past this revision cannot read a «Сетевой +город» credential as Petersburg's and replay it at the wrong upstream. Everything up to `0012` checks with an inspector what is not in the database yet and does not rewrite existing tables, so those can be applied to a live class in the middle of a -school day. The head is `0014`. +school day. The head is `0015`. ### A migration goes BEFORE the deploy, not after @@ -336,7 +341,7 @@ into the database by hand: curl -s https://.vercel.app/api/v1/warmup ``` -`{"status":"ok","schema":"0014"}` means it all lines up. `"status":"degraded"` together with +`{"status":"ok","schema":"0015"}` means it all lines up. `"status":"degraded"` together with `expected_schema` names both revisions and says which way they diverged: «База отстала от кода» — the database is behind the code — is an incident, while «База впереди кода» — the database is ahead — is the normal window between steps 1 and 2, which the deploy closes. @@ -346,7 +351,7 @@ a ping meant to warm things up would keep waking a sleeping Neon. ### What to apply them with In practice this project's migrations are applied **through the Neon connector** rather than -with the `alembic` command — that is how `0005`–`0014` were applied. The Neon project is +with the `alembic` command — that is how `0005`–`0015` were applied. The Neon project is called `lessons`; its identifier is not kept in the repository — anybody with access sees it in the Neon console anyway, and in a public repository it is just the address of somebody else's database. @@ -490,7 +495,7 @@ stack instead of being buried in the API's log, and so that a migration can be r with `docker compose run --rm migrate`. It needs only `DATABASE_URL`: `get_settings()` is never called there, so `BOT_TOKEN` and `OWNER_IDS` are not its business. `GET /api/v1/warmup` is what confirms the result, and it is the endpoint that can: it says -`{"status": "ok", "schema": "0014"}` when the two agree and names both revisions when they +`{"status": "ok", "schema": "0015"}` when the two agree and names both revisions when they do not. The app on the phone needs to reach the API. The options are a public IP with a forwarded @@ -577,6 +582,11 @@ Without those secrets the workflow does not fail: it writes a notice and exits z Actions tab would go red for everybody who cloned the repository. The same tick also sweeps up abandoned bot dialogues and expired records of failed code -attempts — on serverless that is the only moment anything can be swept up at all. For the -sweeping, whatever GitHub deigns to run is enough; for the digests it is not, which is why -the external cron is not a nice-to-have but the condition of what the bot says. +attempts — on serverless that is the only moment anything can be swept up at all — and it +holds **«Сетевой город» sessions open**, pinging each live one before its 15-to-60-minute +idle window runs out, because this project stores no password to sign back in with. For the +sweeping, whatever GitHub deigns to run is enough; for the digests and the keep-alive it is +not — a session dies in the gaps GitHub leaves — which is why the external cron is not a +nice-to-have but the condition of both what the bot promises and whether a «Сетевой город» +family stays signed in. The keep-alive runs last in the tick and inside its own guard, so a +diary that is slow or down never fails the tick and reddens the clock. diff --git a/docs/diaries.md b/docs/diaries.md index 0a51e5b7..c3c5aba5 100644 --- a/docs/diaries.md +++ b/docs/diaries.md @@ -310,10 +310,13 @@ made ЕСИА the only way a family signs in: Дневник.ру per region, « WebView. Until that is judged acceptable — technically and under the service's terms — the manual half of this product, the class kept by hand in the bot, is the only half for those regions, which is what #127 already says about every region that is not Петербург. -- **Three decisions come before any of it, and they are the owner's: #135.** Which platform - comes second, how a family signs in to it, and whether ТОР may be used at all. Whichever - platform it is, the first step is one real session against it. Not one route in these - pages has been seen answering. +- **The platform that came second is «Сетевой город» (#135, #139), and its server side is now + written.** The owner chose it, and `server/app/providers/netschool/` reads it behind the + shared diary contract, from [its reference page](diaries/netschool.md). What #135 still + leaves to the owner is how a family signs in where a region offers only Госуслуги, and + whether ТОР «Моя школа» may be used at all. And the first step nothing has taken for any + platform is one real session against it: not one route in these pages has been seen + answering, «Сетевой город» included. ## What is not covered diff --git a/docs/diaries/netschool.md b/docs/diaries/netschool.md index 5c8b4cec..a22567a4 100644 --- a/docs/diaries/netschool.md +++ b/docs/diaries/netschool.md @@ -2,6 +2,8 @@ *Part of [the electronic diaries of Russia’s regions](../diaries.md). Verification: extracted, checked against the code, and dated. Confidence of the whole: medium. Nothing here has been tried against the live service.* +**This project now reads «Сетевой город» server-side, from this page.** `server/app/providers/netschool/` implements the password flow of the section below — `GET /webapi/logindata` to check the region takes a password, `POST /webapi/auth/getdata` for the one-shot salt, the windows-1251 salted MD5 into `POST /webapi/login` (with the staff-and-parent role re-login), then the bootstrap (`student/diary/init`, `years/current`, `context`, `grade/assignment/types`), the weekly `student/diary` walk with homework as assignment `typeId == 3`, `schools/search` for binding a class, `terms/search` for the academic periods, and `POST /webapi/auth/logout` on sign-out. Sessions are held open from the cron tick with `GET /webapi/context`. The regional servers it will ever contact are a fixed allow-list (`app/providers/netschool/regions.py`) — nothing from a client, a class row or a stored credential ever becomes a URL — over `https` only, and the ЕСИА-only rows in it are marked `password=False` and never offered. The `at` bearer, the cookies and the salted password travel only in headers and form bodies, never in a URL, because this deployment logs every request URL. **None of it has been run against a live server**; it is written from the open clients surveyed here and exercised on hand-written payloads, the same caveat Петербург carries (#121, #135). + **One product, one route set, a different server in every region.** Each regional installation — `asurso.ru` in Самарская, `giseo.rkomi.ru` in Коми, `sgo.e-mordovia.ru` in Мордовия and some fifty more listed below — runs the same `/webapi` JSON API, at whatever diff --git a/server/migrations/versions/0015_diary_provider_columns.py b/server/migrations/versions/0015_diary_provider_columns.py index 12510005..0474a221 100644 --- a/server/migrations/versions/0015_diary_provider_columns.py +++ b/server/migrations/versions/0015_diary_provider_columns.py @@ -30,7 +30,7 @@ because it is a foreign system's id, so ``BigInteger``. - ``diary_school_name`` — what the class card and the sign-in form show. -**Destroys nothing.** Seven nullable columns with no default and no constraint. +**Destroys nothing.** Eight nullable columns with no default and no constraint. The running code neither writes nor reads them, so every row inserted in the window before the deploy lands has a ``NULL`` provider, which is Petersburg — exactly what that code already assumes. From 17c04734284ce7c58bd3f6d693f3ea34f9fb64b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 14:48:55 +0000 Subject: [PATCH 09/30] Generate a catalog of all 89 regions and the diaries each one runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone's new first run needs to list every region, find one by a nickname or a city, say which diary its schools use and which of those can be signed into. None of that existed outside prose. `scripts/region_catalog.py` now builds `server/app/catalog/data/regions.json` from the survey's evidence file (`docs/diaries/regions.md`, cross-checked against the table in `docs/diaries.md`) plus a hand overlay, `scripts/region_catalog.toml`, for what the survey does not carry: keys, two-digit subject codes, English names, zones, aliases, cities, and the spellings DaData uses. - The 19 «Сетевой город» keys are the allow-list's own, byte for byte: they are already stored in `classes.diary_region`, `diary_sessions.region` and the sealed credential. Origin, password and verified are copied from `regions.py`, never typed, so the phone and the server read one allow-list. - `action` and the recommendation are worked out here and nowhere else. Only Петербург and the 16 password «Сетевой город» regions are `signin`. ТОР «Моя школа» and the three Госуслуги-only «Сетевой город» regions are a `handoff` to the browser, never a sign-in, because a Госуслуги session is the person's whole state-services account (#135). A test fails if any field or text about an in-page sign-in reaches the catalog. - Region names live in the JSON, with `name_en` mandatory and tested, so the 89 × 2 names do not become string resources; the why-texts will be resources keyed by the reason codes this emits. - `--check` and `test_the_committed_catalog_is_what_the_generator_writes` fail when the survey or the allow-list changes without a regeneration. Unverified: the subject codes 90, 93, 94 and 95 (marked in the overlay), every DaData spelling, and that each `web_url` host answers on https. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/catalog/__init__.py | 131 + server/app/catalog/data/regions.json | 6293 ++++++++++++++++++++++++++ server/pyproject.toml | 9 + server/scripts/region_catalog.py | 859 ++++ server/scripts/region_catalog.toml | 1325 ++++++ server/tests/test_region_catalog.py | 658 +++ 6 files changed, 9275 insertions(+) create mode 100644 server/app/catalog/__init__.py create mode 100644 server/app/catalog/data/regions.json create mode 100644 server/scripts/region_catalog.py create mode 100644 server/scripts/region_catalog.toml create mode 100644 server/tests/test_region_catalog.py diff --git a/server/app/catalog/__init__.py b/server/app/catalog/__init__.py new file mode 100644 index 00000000..aad6ad95 --- /dev/null +++ b/server/app/catalog/__init__.py @@ -0,0 +1,131 @@ +"""The region catalog, as the server reads it. + +``data/regions.json`` is generated from the survey of every region's diary by +``scripts/region_catalog.py`` and committed; nothing here writes it, and a +change to a region belongs in the survey or in ``scripts/region_catalog.toml``, +never in the JSON. The phone bundles the same file and reads everything in it. +The server reads four things: a region's key, its two-digit subject code, its +names, and the spellings DaData uses for it — which is what turning a school +found in the company register into «this region» needs, and nothing more. + +The file is read on first use, not at import: the directory endpoint is the one +caller on a request path, and every other cold start should not pay for +parsing eighty-nine regions it will never look at. +""" + +from __future__ import annotations + +import functools +import json +import re +from dataclasses import dataclass +from pathlib import Path + +#: Beside this module, so that it ships wherever ``app`` does: Vercel uploads +#: ``server/app`` whole, and a wheel carries it as package data (pyproject.toml). +DATA = Path(__file__).resolve().parent / "data" / "regions.json" + +#: Anything that is not a letter or a digit. DaData writes «Респ Саха /Якутия/» +#: and «Кемеровская область - Кузбасс», the survey «Республика Саха (Якутия)» +#: and «Кемеровская область — Кузбасс»; the punctuation is where they differ. +_NOT_ALNUM = re.compile(r"[\W_]+") + + +@dataclass(frozen=True) +class CatalogRegion: + key: str + code: str + name_ru: str + name_en: str + dadata_names: tuple[str, ...] + + +@dataclass(frozen=True) +class _Catalog: + regions: tuple[CatalogRegion, ...] + by_key: dict[str, CatalogRegion] + by_code: dict[str, CatalogRegion] + by_dadata_name: dict[str, CatalogRegion] + school_words: tuple[str, ...] + + +def normalise_name(text: str) -> str: + """A region's name reduced to what two spellings of it have in common. + + Case, ``ё`` and every run of punctuation and spaces are dropped, so + «Респ Саха /Якутия/» and «респ саха якутия» are one name. It is the rule + ``dadata_names`` are compared by, here and in the generator that refuses a + spelling two regions would share — one function, so the two cannot disagree. + """ + folded = text.casefold().replace("ё", "е") + return " ".join(_NOT_ALNUM.sub(" ", folded).split()) + + +@functools.cache +def _load() -> _Catalog: + raw = json.loads(DATA.read_text(encoding="utf-8")) + regions = tuple( + CatalogRegion( + key=entry["key"], + code=entry["code"], + name_ru=entry["name_ru"], + name_en=entry["name_en"], + dadata_names=tuple(entry["dadata_names"]), + ) + for entry in raw["regions"] + ) + return _Catalog( + regions=regions, + by_key={region.key: region for region in regions}, + by_code={region.code: region for region in regions}, + by_dadata_name={ + normalise_name(name): region for region in regions for name in region.dadata_names + }, + school_words=tuple(raw["search"]["school_words"]), + ) + + +def regions() -> tuple[CatalogRegion, ...]: + """Every region, in the survey's order (Constitution Art. 65).""" + return _load().regions + + +def get(key: str | None) -> CatalogRegion | None: + """The region stored under ``key``, or ``None`` for an unknown one.""" + if not key: + return None + return _load().by_key.get(key) + + +def by_code(code: str | None) -> CatalogRegion | None: + """The region whose two-digit subject code this is. + + Only two digits: DaData's ``region_kladr_id`` is thirteen, and the caller + cuts it, because «is this a code at all» is a question about DaData's answer + rather than about the catalog. + """ + if code is None or len(code) != 2 or not code.isdigit(): + return None + return _load().by_code.get(code) + + +def by_dadata_name(text: str | None) -> CatalogRegion | None: + """The region DaData means by ``text`` («Респ Татарстан», «г Москва»). + + An exact match after :func:`normalise_name`, never a partial one: «Алтай» + is a republic and «Алтайский» a krai, and a guess between them would put a + school in the wrong region without anybody seeing it happen. A name the + catalog does not know answers ``None`` and the caller shows DaData's label. + """ + if not text: + return None + return _load().by_dadata_name.get(normalise_name(text)) + + +def school_words() -> tuple[str, ...]: + """The words a school's name is made of rather than told apart by. + + The phone reads the same list out of the same file, so «too common to look + up» means one thing on both sides of the directory call. + """ + return _load().school_words diff --git a/server/app/catalog/data/regions.json b/server/app/catalog/data/regions.json new file mode 100644 index 00000000..07011e8c --- /dev/null +++ b/server/app/catalog/data/regions.json @@ -0,0 +1,6293 @@ +{ + "platforms": { + "avers": { + "handoff": null, + "kind": "diary", + "name_en": "Avers", + "name_ru": "Аверс", + "origin": null, + "page": null, + "provider": null, + "signin": "unknown" + }, + "bars": { + "handoff": null, + "kind": "diary", + "name_en": "BARS", + "name_ru": "БАРС", + "origin": null, + "page": "bars", + "provider": null, + "signin": "mixed" + }, + "dnevnik-ru": { + "handoff": null, + "kind": "diary", + "name_en": "Dnevnik.ru", + "name_ru": "Дневник.ру", + "origin": null, + "page": "dnevnik-ru", + "provider": null, + "signin": "mixed" + }, + "dnevnik76": { + "handoff": null, + "kind": "diary", + "name_en": "Dnevnik76", + "name_ru": "Дневник76", + "origin": null, + "page": "dnevnik76", + "provider": null, + "signin": "retired" + }, + "e-uslugi": { + "handoff": null, + "kind": "admissions", + "name_en": "E-uslugi. Education", + "name_ru": "Е-услуги. Образование", + "origin": null, + "page": null, + "provider": null, + "signin": "none" + }, + "edu-tatar": { + "handoff": null, + "kind": "diary", + "name_en": "edu.tatar.ru", + "name_ru": "edu.tatar.ru", + "origin": null, + "page": "edu-tatar", + "provider": null, + "signin": "retired" + }, + "egov66": { + "handoff": null, + "kind": "diary", + "name_en": "Sverdlovsk Oblast Unified Digital Platform", + "name_ru": "ГИС СО «ЕЦП»", + "origin": null, + "page": "egov66", + "provider": null, + "signin": "retired" + }, + "eljur": { + "handoff": null, + "kind": "diary", + "name_en": "ElJur", + "name_ru": "ЭлЖур", + "origin": null, + "page": "eljur", + "provider": null, + "signin": "mixed" + }, + "elschool": { + "handoff": null, + "kind": "diary", + "name_en": "ELSCHOOL", + "name_ru": "ELSCHOOL", + "origin": null, + "page": "elschool", + "provider": null, + "signin": "mixed" + }, + "epos": { + "handoff": null, + "kind": "diary", + "name_en": "EPOS.School", + "name_ru": "ЭПОС.Школа", + "origin": null, + "page": "epos", + "provider": null, + "signin": "esia_only" + }, + "eschool-center": { + "handoff": null, + "kind": "diary", + "name_en": "eSchool", + "name_ru": "eSchool", + "origin": null, + "page": "eschool-center", + "provider": null, + "signin": "password" + }, + "fgis-myschool": { + "handoff": null, + "kind": "portal", + "name_en": "My School federal portal", + "name_ru": "ФГИС «Моя школа»", + "origin": null, + "page": "myschool-federal", + "provider": null, + "signin": "none" + }, + "it-school-penza": { + "handoff": null, + "kind": "diary", + "name_en": "IT School (Penza)", + "name_ru": "АйТи Школа", + "origin": null, + "page": null, + "provider": null, + "signin": "mixed" + }, + "kiasuo": { + "handoff": null, + "kind": "diary", + "name_en": "KIASUO", + "name_ru": "КИАСУО", + "origin": null, + "page": "kiasuo", + "provider": null, + "signin": "esia_only" + }, + "mesh-moscow": { + "handoff": null, + "kind": "diary", + "name_en": "Moscow Electronic School", + "name_ru": "МЭШ", + "origin": null, + "page": "mesh-moscow", + "provider": null, + "signin": "oauth" + }, + "mesh-myschool": { + "handoff": null, + "kind": "diary", + "name_en": "My School (MESH)", + "name_ru": "Моя школа (МЭШ)", + "origin": null, + "page": "mesh-myschool", + "provider": null, + "signin": "esia_only" + }, + "mrko": { + "handoff": null, + "kind": "diary", + "name_en": "MRKO (Moscow)", + "name_ru": "МРКО", + "origin": null, + "page": null, + "provider": null, + "signin": "retired" + }, + "netschool": { + "handoff": null, + "kind": "diary", + "name_en": "Setevoy Gorod (NetSchool)", + "name_ru": "Сетевой город. Образование", + "origin": null, + "page": "netschool", + "provider": "netschool", + "signin": "mixed" + }, + "one-x1": { + "handoff": null, + "kind": "diary", + "name_en": "one.", + "name_ru": "one.", + "origin": null, + "page": "one-x1", + "provider": null, + "signin": "mixed" + }, + "paper": { + "handoff": null, + "kind": "none", + "name_en": "Paper registers and diaries", + "name_ru": "Бумажные журналы и дневники", + "origin": null, + "page": null, + "provider": null, + "signin": "none" + }, + "petersburg": { + "handoff": null, + "kind": "diary", + "name_en": "Petersburg Education", + "name_ru": "Петербургское образование", + "origin": "https://dnevnik2.petersburgedu.ru", + "page": "petersburg", + "provider": "petersburg", + "signin": "password" + }, + "ruobr": { + "handoff": null, + "kind": "diary", + "name_en": "Electronic School 2.0", + "name_ru": "Электронная школа 2.0", + "origin": null, + "page": "ruobr", + "provider": null, + "signin": "mixed" + }, + "tor-myschool": { + "handoff": "https://www.gosuslugi.ru/school", + "kind": "diary", + "name_en": "Gosuslugi My School", + "name_ru": "Госуслуги Моя школа", + "origin": null, + "page": "myschool-federal", + "provider": null, + "signin": "esia_only" + }, + "virtual-school": { + "handoff": null, + "kind": "diary", + "name_en": "Virtual School", + "name_ru": "Виртуальная школа", + "origin": null, + "page": "virtual-school", + "provider": null, + "signin": "oauth" + }, + "web2edu": { + "handoff": null, + "kind": "diary", + "name_en": "Web2edu", + "name_ru": "Web2edu", + "origin": null, + "page": null, + "provider": null, + "signin": "unknown" + } + }, + "regions": [ + { + "aliases": [ + "Адыгея", + "Республика Адыгея (Адыгея)" + ], + "cities": [ + "Майкоп" + ], + "code": "01", + "dadata_names": [ + "Респ Адыгея", + "Адыгея" + ], + "iso": "RU-AD", + "key": "adygea", + "mandatory": false, + "name_en": "Republic of Adygea", + "name_ru": "Республика Адыгея", + "order": 1, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Горный Алтай", + "Алтай" + ], + "cities": [ + "Горно-Алтайск" + ], + "code": "04", + "dadata_names": [ + "Респ Алтай", + "Алтай" + ], + "iso": "RU-AL", + "key": "altai-republic", + "mandatory": false, + "name_en": "Altai Republic", + "name_ru": "Республика Алтай", + "order": 2, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.altaiobr04.ru", + "poo.altaiobr04.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.altaiobr04.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sosh.mon-ra.ru", + "spo.mon-ra.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://sosh.mon-ra.ru" + } + ], + "tor": "primary", + "zone": "Asia/Barnaul" + }, + { + "aliases": [ + "Башкирия", + "Башкортостан" + ], + "cities": [ + "Уфа", + "Стерлитамак", + "Салават", + "Нефтекамск" + ], + "code": "02", + "dadata_names": [ + "Респ Башкортостан", + "Башкортостан" + ], + "iso": "RU-BA", + "key": "bashkortostan", + "mandatory": true, + "name_en": "Republic of Bashkortostan", + "name_ru": "Республика Башкортостан", + "order": 3, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.edurb.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://dnevnik.edurb.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "elschool.ru", + "api.elschool.ru", + "file.elschool.ru", + "edu.brsc.ru" + ], + "netschool": null, + "platform": "elschool", + "role": "secondary", + "web_url": "https://elschool.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [ + "Бурятия" + ], + "cities": [ + "Улан-Удэ" + ], + "code": "03", + "dadata_names": [ + "Респ Бурятия", + "Бурятия" + ], + "iso": "RU-BU", + "key": "buryatia", + "mandatory": false, + "name_en": "Republic of Buryatia", + "name_ru": "Республика Бурятия", + "order": 4, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "deti.obr03.ru" + ], + "netschool": { + "origin": "https://deti.obr03.ru", + "password": true, + "region": "buryatia", + "verified": false, + "zone": "Asia/Irkutsk" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://deti.obr03.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "maou-37.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://maou-37.eljur.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Irkutsk" + }, + { + "aliases": [ + "Дагестан" + ], + "cities": [ + "Махачкала", + "Дербент", + "Хасавюрт", + "Каспийск" + ], + "code": "05", + "dadata_names": [ + "Респ Дагестан", + "Дагестан" + ], + "iso": "RU-DA", + "key": "dagestan", + "mandatory": true, + "name_en": "Republic of Dagestan", + "name_ru": "Республика Дагестан", + "order": 5, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.05edu.ru", + "education.05edu.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://myschool.05edu.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru", + "05.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "ДНР", + "Донецкая республика", + "Донбасс" + ], + "cities": [ + "Донецк", + "Макеевка", + "Горловка", + "Мариуполь" + ], + "code": "93", + "dadata_names": [ + "Донецкая Народная Респ", + "Донецкая Народная" + ], + "iso": null, + "key": "dnr", + "mandatory": false, + "name_en": "Donetsk People's Republic", + "name_ru": "Донецкая Народная Республика", + "order": 6, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "donschool47.eljur.ru", + "*.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://donschool47.eljur.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Ингушетия" + ], + "cities": [ + "Магас", + "Назрань" + ], + "code": "06", + "dadata_names": [ + "Респ Ингушетия", + "Ингушетия" + ], + "iso": "RU-IN", + "key": "ingushetia", + "mandatory": false, + "name_en": "Republic of Ingushetia", + "name_ru": "Республика Ингушетия", + "order": 7, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.edu-ri.ru", + "poo.edu-ri.ru", + "sad06.ru:82" + ], + "netschool": { + "origin": "https://sgo.edu-ri.ru", + "password": true, + "region": "ingushetia", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.edu-ri.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "ri-sch2.eljur.ru", + "ri-sch3.eljur.ru", + "ri-sch11.eljur.ru", + "ri-sch15.eljur.ru", + "ri-sch22.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://ri-sch2.eljur.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "КБР", + "Кабардино-Балкария", + "Кабарда" + ], + "cities": [ + "Нальчик" + ], + "code": "07", + "dadata_names": [ + "Кабардино-Балкарская Респ", + "Кабардино-Балкарская" + ], + "iso": "RU-KB", + "key": "kbr", + "mandatory": false, + "name_en": "Kabardino-Balkarian Republic", + "name_ru": "Кабардино-Балкарская Республика", + "order": 8, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.07.edu.o7.com" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://school.07.edu.o7.com" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Калмыкия" + ], + "cities": [ + "Элиста" + ], + "code": "08", + "dadata_names": [ + "Респ Калмыкия", + "Калмыкия" + ], + "iso": "RU-KL", + "key": "kalmykia", + "mandatory": false, + "name_en": "Republic of Kalmykia", + "name_ru": "Республика Калмыкия", + "order": 9, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "08.dnevnik.ru", + "login.dnevnik.ru/login/esia/kalmykia", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.monrk.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.monrk.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "КЧР", + "Карачаево-Черкесия" + ], + "cities": [ + "Черкесск" + ], + "code": "09", + "dadata_names": [ + "Карачаево-Черкесская Респ", + "Карачаево-Черкесская" + ], + "iso": "RU-KC", + "key": "kchr", + "mandatory": false, + "name_en": "Karachay-Cherkess Republic", + "name_ru": "Карачаево-Черкесская Республика", + "order": 10, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.kchgov.ru", + "poo.kchgov.ru", + "dnevnik-kchr.ru" + ], + "netschool": { + "origin": "https://sgo.kchgov.ru", + "password": true, + "region": "kchr", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.kchgov.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Карелия" + ], + "cities": [ + "Петрозаводск" + ], + "code": "10", + "dadata_names": [ + "Респ Карелия", + "Карелия" + ], + "iso": "RU-KR", + "key": "karelia", + "mandatory": true, + "name_en": "Republic of Karelia", + "name_ru": "Республика Карелия", + "order": 11, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "karelia.minedu.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://karelia.minedu.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.karelia.ru", + "college.karelia.ru", + "contingent.karelia.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://school.karelia.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Коми" + ], + "cities": [ + "Сыктывкар", + "Ухта", + "Воркута" + ], + "code": "11", + "dadata_names": [ + "Респ Коми", + "Коми" + ], + "iso": "RU-KO", + "key": "komi", + "mandatory": false, + "name_en": "Komi Republic", + "name_ru": "Республика Коми", + "order": 12, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "giseo.rkomi.ru" + ], + "netschool": { + "origin": "https://giseo.rkomi.ru", + "password": true, + "region": "komi", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://giseo.rkomi.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Крым" + ], + "cities": [ + "Симферополь", + "Керчь", + "Евпатория", + "Ялта" + ], + "code": "91", + "dadata_names": [ + "Респ Крым", + "Крым" + ], + "iso": null, + "key": "crimea", + "mandatory": false, + "name_en": "Republic of Crimea", + "name_ru": "Республика Крым", + "order": 13, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "eljur", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.rk.gov.ru", + "*.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://edu.rk.gov.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Simferopol" + }, + { + "aliases": [ + "ЛНР", + "Луганская республика", + "Донбасс" + ], + "cities": [ + "Луганск", + "Алчевск" + ], + "code": "94", + "dadata_names": [ + "Луганская Народная Респ", + "Луганская Народная" + ], + "iso": null, + "key": "lnr", + "mandatory": false, + "name_en": "Luhansk People's Republic", + "name_ru": "Луганская Народная Республика", + "order": 14, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "lnr0487.eljur.ru", + "lnr0523.eljur.ru", + "lnr0488.eljur.ru", + "*.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://lnr0487.eljur.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Марий Эл" + ], + "cities": [ + "Йошкар-Ола" + ], + "code": "12", + "dadata_names": [ + "Респ Марий Эл", + "Марий Эл" + ], + "iso": "RU-ME", + "key": "mari-el", + "mandatory": false, + "name_en": "Mari El Republic", + "name_ru": "Республика Марий Эл", + "order": 15, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.mari-el.gov.ru" + ], + "netschool": { + "origin": "https://sgo.mari-el.gov.ru", + "password": true, + "region": "mari-el", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.mari-el.gov.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Мордовия" + ], + "cities": [ + "Саранск" + ], + "code": "13", + "dadata_names": [ + "Респ Мордовия", + "Мордовия" + ], + "iso": "RU-MO", + "key": "mordovia", + "mandatory": false, + "name_en": "Republic of Mordovia", + "name_ru": "Республика Мордовия", + "order": 16, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.e-mordovia.ru" + ], + "netschool": { + "origin": "https://sgo.e-mordovia.ru", + "password": true, + "region": "mordovia", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.e-mordovia.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Якутия", + "Саха" + ], + "cities": [ + "Якутск", + "Нерюнгри" + ], + "code": "14", + "dadata_names": [ + "Респ Саха /Якутия/", + "Саха /Якутия/" + ], + "iso": "RU-SA", + "key": "yakutia", + "mandatory": false, + "name_en": "Sakha (Yakutia) Republic", + "name_ru": "Республика Саха (Якутия)", + "order": 17, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.e-yakutia.ru" + ], + "netschool": { + "origin": "https://sgo.e-yakutia.ru", + "password": true, + "region": "yakutia", + "verified": false, + "zone": "Asia/Yakutsk" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.e-yakutia.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Yakutsk" + }, + { + "aliases": [ + "РСО", + "РСО-Алания", + "Северная Осетия", + "Осетия", + "Алания" + ], + "cities": [ + "Владикавказ" + ], + "code": "15", + "dadata_names": [ + "Респ Северная Осетия - Алания", + "Северная Осетия - Алания" + ], + "iso": "RU-SE", + "key": "north-ossetia", + "mandatory": false, + "name_en": "Republic of North Ossetia–Alania", + "name_ru": "Республика Северная Осетия — Алания", + "order": 18, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "15.dnevnik.ru", + "login.dnevnik.ru/login/esia/rsoa", + "dnevnik.ru/v2/soc/r/rsoa" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Татарстан", + "Татария", + "Республика Татарстан (Татарстан)" + ], + "cities": [ + "Казань", + "Набережные Челны", + "Нижнекамск", + "Альметьевск" + ], + "code": "16", + "dadata_names": [ + "Респ Татарстан", + "Татарстан" + ], + "iso": "RU-TA", + "key": "tatarstan", + "mandatory": true, + "name_en": "Republic of Tatarstan", + "name_ru": "Республика Татарстан", + "order": 19, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "ms-edu.tatar.ru", + "school-edu.tatar.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://ms-edu.tatar.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.tatar.ru" + ], + "netschool": null, + "platform": "edu-tatar", + "role": "legacy", + "web_url": "https://edu.tatar.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Тыва", + "Тува" + ], + "cities": [ + "Кызыл" + ], + "code": "17", + "dadata_names": [ + "Респ Тыва", + "Тыва" + ], + "iso": "RU-TY", + "key": "tuva", + "mandatory": false, + "name_en": "Tuva Republic", + "name_ru": "Республика Тыва", + "order": 20, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "17.dnevnik.ru", + "login.dnevnik.ru/login/esia/tuva", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.rtyva.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://school.rtyva.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "unclear", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Krasnoyarsk" + }, + { + "aliases": [ + "Удмуртия" + ], + "cities": [ + "Ижевск", + "Сарапул", + "Глазов", + "Воткинск" + ], + "code": "18", + "dadata_names": [ + "Удмуртская Респ", + "Удмуртская" + ], + "iso": "RU-UD", + "key": "udmurtia", + "mandatory": false, + "name_en": "Udmurt Republic", + "name_ru": "Удмуртская Республика", + "order": 21, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "es.ciur.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://es.ciur.ru" + } + ], + "tor": "primary", + "zone": "Europe/Samara" + }, + { + "aliases": [ + "Хакасия" + ], + "cities": [ + "Абакан", + "Черногорск" + ], + "code": "19", + "dadata_names": [ + "Респ Хакасия", + "Хакасия" + ], + "iso": "RU-KK", + "key": "khakassia", + "mandatory": false, + "name_en": "Republic of Khakassia", + "name_ru": "Республика Хакасия", + "order": 22, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "bars", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.r-19.ru" + ], + "netschool": null, + "platform": "bars", + "role": "primary", + "web_url": "https://school.r-19.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "unclear", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "unclear", + "zone": "Asia/Krasnoyarsk" + }, + { + "aliases": [ + "Чечня" + ], + "cities": [ + "Грозный", + "Гудермес" + ], + "code": "20", + "dadata_names": [ + "Чеченская Респ", + "Чеченская" + ], + "iso": "RU-CE", + "key": "chechnya", + "mandatory": false, + "name_en": "Chechen Republic", + "name_ru": "Чеченская Республика", + "order": 23, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "mvd1.eljur.ru", + "gimn12.eljur.ru", + "chesu.eljur.ru", + "sssh1.eljur.ru", + "davsosh.eljur.ru", + "sosh5.eljur.ru", + "chervlen.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://mvd1.eljur.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.mon95.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "unclear", + "web_url": "https://school.mon95.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Чувашия", + "Чувашская Республика — Чувашия" + ], + "cities": [ + "Чебоксары", + "Новочебоксарск" + ], + "code": "21", + "dadata_names": [ + "Чувашская Республика - Чувашия", + "Чувашская Респ", + "Чувашская Республика" + ], + "iso": "RU-CU", + "key": "chuvashia", + "mandatory": false, + "name_en": "Chuvash Republic", + "name_ru": "Чувашская Республика", + "order": 24, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "net-school.cap.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://net-school.cap.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [], + "netschool": null, + "platform": "e-uslugi", + "role": "legacy", + "web_url": null + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Барнаул", + "Бийск", + "Рубцовск" + ], + "code": "22", + "dadata_names": [ + "Алтайский край", + "Алтайский" + ], + "iso": "RU-ALT", + "key": "altai-krai", + "mandatory": false, + "name_en": "Altai Krai", + "name_ru": "Алтайский край", + "order": 25, + "recommended": { + "confidence": "high", + "modifiers": [ + "esia_only" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://netschool.edu22.info", + "hosts": [ + "netschool.edu22.info", + "neteducation.edu22.info" + ], + "netschool": { + "origin": "https://netschool.edu22.info", + "password": false, + "region": "altai-krai", + "verified": false, + "zone": "Asia/Barnaul" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://netschool.edu22.info" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Barnaul" + }, + { + "aliases": [ + "Забайкалье", + "Читинская область" + ], + "cities": [ + "Чита", + "Краснокаменск" + ], + "code": "75", + "dadata_names": [ + "Забайкальский край", + "Забайкальский" + ], + "iso": "RU-ZAB", + "key": "zabaikalsky", + "mandatory": false, + "name_en": "Zabaykalsky Krai", + "name_ru": "Забайкальский край", + "order": 26, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "region.zabedu.ru" + ], + "netschool": { + "origin": "https://region.zabedu.ru", + "password": true, + "region": "zabaikalsky", + "verified": false, + "zone": "Asia/Chita" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://region.zabedu.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "es.zabedu.ru" + ], + "netschool": null, + "platform": "e-uslugi", + "role": "secondary", + "web_url": "https://es.zabedu.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Chita" + }, + { + "aliases": [ + "Камчатка" + ], + "cities": [ + "Петропавловск-Камчатский", + "Елизово" + ], + "code": "41", + "dadata_names": [ + "Камчатский край", + "Камчатский" + ], + "iso": "RU-KAM", + "key": "kamchatka", + "mandatory": false, + "name_en": "Kamchatka Krai", + "name_ru": "Камчатский край", + "order": 27, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.sgo41.ru", + "sgo41.ru" + ], + "netschool": { + "origin": "https://school.sgo41.ru", + "password": true, + "region": "kamchatka", + "verified": false, + "zone": "Asia/Kamchatka" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://school.sgo41.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [], + "netschool": null, + "platform": "e-uslugi", + "role": "secondary", + "web_url": null + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Kamchatka" + }, + { + "aliases": [ + "Кубань" + ], + "cities": [ + "Краснодар", + "Сочи", + "Новороссийск", + "Армавир" + ], + "code": "23", + "dadata_names": [ + "Краснодарский край", + "Краснодарский" + ], + "iso": "RU-KDA", + "key": "krasnodar", + "mandatory": false, + "name_en": "Krasnodar Krai", + "name_ru": "Краснодарский край", + "order": 28, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.rso23.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.rso23.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Красноярье" + ], + "cities": [ + "Красноярск", + "Норильск", + "Ачинск" + ], + "code": "24", + "dadata_names": [ + "Красноярский край", + "Красноярский" + ], + "iso": "RU-KYA", + "key": "krasnoyarsk", + "mandatory": false, + "name_en": "Krasnoyarsk Krai", + "name_ru": "Красноярский край", + "order": 29, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "kiasuo", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.kiasuo.ru", + "pwa.kiasuo.ru", + "diaryapi.kiasuo.ru", + "010860.kiasuo.ru", + "050760.kiasuo.ru", + "support.kiasuo.ru" + ], + "netschool": null, + "platform": "kiasuo", + "role": "primary", + "web_url": "https://dnevnik.kiasuo.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "*.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": null + } + ], + "tor": "unlisted", + "zone": "Asia/Krasnoyarsk" + }, + { + "aliases": [ + "Прикамье", + "Пермская область" + ], + "cities": [ + "Пермь", + "Березники", + "Соликамск" + ], + "code": "59", + "dadata_names": [ + "Пермский край", + "Пермский" + ], + "iso": "RU-PER", + "key": "perm", + "mandatory": false, + "name_en": "Perm Krai", + "name_ru": "Пермский край", + "order": 30, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "epos", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.permkrai.ru", + "epos.permkrai.ru", + "cabinet.permkrai.ru" + ], + "netschool": null, + "platform": "epos", + "role": "primary", + "web_url": "https://school.permkrai.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "web2edu.ru" + ], + "netschool": null, + "platform": "web2edu", + "role": "legacy", + "web_url": "https://web2edu.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [ + "Приморье" + ], + "cities": [ + "Владивосток", + "Уссурийск", + "Находка" + ], + "code": "25", + "dadata_names": [ + "Приморский край", + "Приморский" + ], + "iso": "RU-PRI", + "key": "primorye", + "mandatory": false, + "name_en": "Primorsky Krai", + "name_ru": "Приморский край", + "order": 31, + "recommended": { + "confidence": "medium", + "modifiers": [ + "esia_only" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://sgo.prim-edu.ru", + "hosts": [ + "sgo.prim-edu.ru" + ], + "netschool": { + "origin": "https://sgo.prim-edu.ru", + "password": false, + "region": "primorye", + "verified": false, + "zone": "Asia/Vladivostok" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.prim-edu.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Vladivostok" + }, + { + "aliases": [ + "Ставрополье" + ], + "cities": [ + "Ставрополь", + "Пятигорск", + "Кисловодск", + "Невинномысск" + ], + "code": "26", + "dadata_names": [ + "Ставропольский край", + "Ставропольский" + ], + "iso": "RU-STA", + "key": "stavropol", + "mandatory": false, + "name_en": "Stavropol Krai", + "name_ru": "Ставропольский край", + "order": 32, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.stavminobr.ru", + "portal.stavminobr.ru", + "passport.stavminobr.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.stavminobr.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "unclear", + "web_url": "https://login.dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Хабаровск", + "Комсомольск-на-Амуре" + ], + "code": "27", + "dadata_names": [ + "Хабаровский край", + "Хабаровский" + ], + "iso": "RU-KHA", + "key": "khabarovsk", + "mandatory": false, + "name_en": "Khabarovsk Krai", + "name_ru": "Хабаровский край", + "order": 33, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "27.dnevnik.ru", + "login.dnevnik.ru/login/esia/khabarovsk", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Vladivostok" + }, + { + "aliases": [ + "Приамурье" + ], + "cities": [ + "Благовещенск", + "Белогорск", + "Свободный" + ], + "code": "28", + "dadata_names": [ + "Амурская обл", + "Амурская" + ], + "iso": "RU-AMU", + "key": "amur", + "mandatory": false, + "name_en": "Amur Oblast", + "name_ru": "Амурская область", + "order": 34, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "region.obramur.ru", + "portal.obramur.ru" + ], + "netschool": { + "origin": "https://region.obramur.ru", + "password": true, + "region": "amur", + "verified": false, + "zone": "Asia/Yakutsk" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://region.obramur.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "front_end", + "zone": "Asia/Yakutsk" + }, + { + "aliases": [ + "Поморье" + ], + "cities": [ + "Архангельск", + "Северодвинск", + "Котлас" + ], + "code": "29", + "dadata_names": [ + "Архангельская обл", + "Архангельская" + ], + "iso": "RU-ARK", + "key": "arkhangelsk", + "mandatory": false, + "name_en": "Arkhangelsk Oblast", + "name_ru": "Архангельская область", + "order": 35, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "29.dnevnik.ru", + "login.dnevnik.ru/login/esia/dvinaland" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "3329.eljur.ru", + "sulfat51.eljur.ru", + "arh26.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://3329.eljur.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Астрахань" + ], + "code": "30", + "dadata_names": [ + "Астраханская обл", + "Астраханская" + ], + "iso": "RU-AST", + "key": "astrakhan", + "mandatory": false, + "name_en": "Astrakhan Oblast", + "name_ru": "Астраханская область", + "order": 36, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru/login/esia/astrakhan" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.astrobl.ru", + "dnevnik.astrobl.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://one.astrobl.ru" + } + ], + "tor": "primary", + "zone": "Europe/Astrakhan" + }, + { + "aliases": [ + "Белгородчина" + ], + "cities": [ + "Белгород", + "Старый Оскол", + "Губкин" + ], + "code": "31", + "dadata_names": [ + "Белгородская обл", + "Белгородская" + ], + "iso": "RU-BEL", + "key": "belgorod", + "mandatory": false, + "name_en": "Belgorod Oblast", + "name_ru": "Белгородская область", + "order": 37, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "vs.belregion.ru", + "belgorod.vsopen.ru", + "www.vsopen.ru/app/esia" + ], + "netschool": null, + "platform": "virtual-school", + "role": "primary", + "web_url": "https://vs.belregion.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Брянщина" + ], + "cities": [ + "Брянск" + ], + "code": "32", + "dadata_names": [ + "Брянская обл", + "Брянская" + ], + "iso": "RU-BRY", + "key": "bryansk", + "mandatory": false, + "name_en": "Bryansk Oblast", + "name_ru": "Брянская область", + "order": 38, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "bryansk.vsopen.ru", + "obr.b-edu.ru" + ], + "netschool": null, + "platform": "virtual-school", + "role": "legacy", + "web_url": "https://bryansk.vsopen.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Владимир", + "Ковров", + "Муром" + ], + "code": "33", + "dadata_names": [ + "Владимирская обл", + "Владимирская" + ], + "iso": "RU-VLA", + "key": "vladimir", + "mandatory": false, + "name_en": "Vladimir Oblast", + "name_ru": "Владимирская область", + "order": 39, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "bars", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "школа.образование33.рф", + "образование33.рф" + ], + "netschool": null, + "platform": "bars", + "role": "primary", + "web_url": "https://xn--80atdl2c.xn--33-6kcadhwnl3cfdx.xn--p1ai" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Волгоград", + "Волжский", + "Камышин" + ], + "code": "34", + "dadata_names": [ + "Волгоградская обл", + "Волгоградская" + ], + "iso": "RU-VGG", + "key": "volgograd", + "mandatory": false, + "name_en": "Volgograd Oblast", + "name_ru": "Волгоградская область", + "order": 40, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "netschool", + "reason": "unreachable", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": "http-only", + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.volganet.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "primary", + "web_url": null + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Volgograd" + }, + { + "aliases": [ + "Вологодчина" + ], + "cities": [ + "Вологда", + "Череповец" + ], + "code": "35", + "dadata_names": [ + "Вологодская обл", + "Вологодская" + ], + "iso": "RU-VLG", + "key": "vologda", + "mandatory": true, + "name_en": "Vologda Oblast", + "name_ru": "Вологодская область", + "order": 41, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 2 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.edu35.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://dnevnik.edu35.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "ssuz.vip.edu35.ru" + ], + "netschool": null, + "platform": "bars", + "role": "secondary", + "web_url": "https://ssuz.vip.edu35.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.vip.edu35.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://school.vip.edu35.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Воронеж" + ], + "code": "36", + "dadata_names": [ + "Воронежская обл", + "Воронежская" + ], + "iso": "RU-VOR", + "key": "voronezh", + "mandatory": false, + "name_en": "Voronezh Oblast", + "name_ru": "Воронежская область", + "order": 42, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "36.dnevnik.ru", + "login.dnevnik.ru/login/esia/voronej" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Запорожье" + ], + "cities": [ + "Мелитополь", + "Бердянск", + "Энергодар" + ], + "code": "90", + "dadata_names": [ + "Запорожская обл", + "Запорожская" + ], + "iso": null, + "key": "zaporozhye", + "mandatory": false, + "name_en": "Zaporozhye Oblast", + "name_ru": "Запорожская область", + "order": 43, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.umnik-zo.ru", + "passport.umnik-zo.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.umnik-zo.ru" + } + ], + "tor": "absent", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Иваново", + "Кинешма" + ], + "code": "37", + "dadata_names": [ + "Ивановская обл", + "Ивановская" + ], + "iso": "RU-IVA", + "key": "ivanovo", + "mandatory": false, + "name_en": "Ivanovo Oblast", + "name_ru": "Ивановская область", + "order": 44, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 2 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "37.dnevnik.ru", + "login.dnevnik.ru/login/esia/ivanovskaya", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "iklp.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://iklp.eljur.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Приангарье" + ], + "cities": [ + "Иркутск", + "Братск", + "Ангарск" + ], + "code": "38", + "dadata_names": [ + "Иркутская обл", + "Иркутская" + ], + "iso": "RU-IRK", + "key": "irkutsk", + "mandatory": false, + "name_en": "Irkutsk Oblast", + "name_ru": "Иркутская область", + "order": 45, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "login.dnevnik.ru/login/esia/irkutsk", + "38.dnevnik.ru", + "dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://login.dnevnik.ru/login/esia/irkutsk" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "fec.eljur.ru", + "sh28irk.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "secondary", + "web_url": "https://fec.eljur.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [], + "netschool": null, + "platform": "netschool", + "role": "unclear", + "web_url": null + } + ], + "tor": "front_end", + "zone": "Asia/Irkutsk" + }, + { + "aliases": [], + "cities": [ + "Калининград", + "Советск" + ], + "code": "39", + "dadata_names": [ + "Калининградская обл", + "Калининградская" + ], + "iso": "RU-KGD", + "key": "kaliningrad", + "mandatory": false, + "name_en": "Kaliningrad Oblast", + "name_ru": "Калининградская область", + "order": 46, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "keo.gov39.ru", + "klgd.eljur.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://keo.gov39.ru" + } + ], + "tor": "primary", + "zone": "Europe/Kaliningrad" + }, + { + "aliases": [], + "cities": [ + "Калуга", + "Обнинск" + ], + "code": "40", + "dadata_names": [ + "Калужская обл", + "Калужская" + ], + "iso": "RU-KLU", + "key": "kaluga", + "mandatory": true, + "name_en": "Kaluga Oblast", + "name_ru": "Калужская область", + "order": 47, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "education.admoblkaluga.ru", + "dnevnik.admoblkaluga.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://education.admoblkaluga.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.admoblkaluga.ru:444", + "es.admoblkaluga.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://edu.admoblkaluga.ru:444" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Кузбасс", + "Кемеровская область" + ], + "cities": [ + "Кемерово", + "Новокузнецк", + "Прокопьевск" + ], + "code": "42", + "dadata_names": [ + "Кемеровская область - Кузбасс", + "Кемеровская обл - Кузбасс", + "Кемеровская обл", + "Кемеровская" + ], + "iso": "RU-KEM", + "key": "kemerovo", + "mandatory": false, + "name_en": "Kemerovo Oblast — Kuzbass", + "name_ru": "Кемеровская область — Кузбасс", + "order": 48, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "ruobr", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "ruobr.ru", + "cabinet.ruobr.ru", + "api3d.ruobr.ru", + "newapp.ruobr.ru" + ], + "netschool": null, + "platform": "ruobr", + "role": "primary", + "web_url": "https://ruobr.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Novokuznetsk" + }, + { + "aliases": [ + "Вятка" + ], + "cities": [ + "Киров" + ], + "code": "43", + "dadata_names": [ + "Кировская обл", + "Кировская" + ], + "iso": "RU-KIR", + "key": "kirov", + "mandatory": false, + "name_en": "Kirov Oblast", + "name_ru": "Кировская область", + "order": 49, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.43edu.ru", + "passport.43edu.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.43edu.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [], + "netschool": null, + "platform": "avers", + "role": "legacy", + "web_url": null + } + ], + "tor": "front_end", + "zone": "Europe/Kirov" + }, + { + "aliases": [], + "cities": [ + "Кострома" + ], + "code": "44", + "dadata_names": [ + "Костромская обл", + "Костромская" + ], + "iso": "RU-KOS", + "key": "kostroma", + "mandatory": false, + "name_en": "Kostroma Oblast", + "name_ru": "Костромская область", + "order": 50, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "netschool.eduportal44.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://netschool.eduportal44.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Зауралье" + ], + "cities": [ + "Курган", + "Шадринск" + ], + "code": "45", + "dadata_names": [ + "Курганская обл", + "Курганская" + ], + "iso": "RU-KGN", + "key": "kurgan", + "mandatory": false, + "name_en": "Kurgan Oblast", + "name_ru": "Курганская область", + "order": 51, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "eljur", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "eschool.gov45.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://eschool.gov45.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [], + "cities": [ + "Курск", + "Железногорск" + ], + "code": "46", + "dadata_names": [ + "Курская обл", + "Курская" + ], + "iso": "RU-KRS", + "key": "kursk", + "mandatory": false, + "name_en": "Kursk Oblast", + "name_ru": "Курская область", + "order": 52, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.kurskobr.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://edu.kurskobr.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Ленобласть", + "ЛО" + ], + "cities": [ + "Гатчина", + "Всеволожск", + "Выборг", + "Мурино" + ], + "code": "47", + "dadata_names": [ + "Ленинградская обл", + "Ленинградская" + ], + "iso": "RU-LEN", + "key": "leningrad", + "mandatory": false, + "name_en": "Leningrad Oblast", + "name_ru": "Ленинградская область", + "order": 53, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "e-school.obr.lenreg.ru", + "obr.lenreg.ru" + ], + "netschool": { + "origin": "https://e-school.obr.lenreg.ru", + "password": true, + "region": "leningrad", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://e-school.obr.lenreg.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "47.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://47.dnevnik.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Липецк", + "Елец" + ], + "code": "48", + "dadata_names": [ + "Липецкая обл", + "Липецкая" + ], + "iso": "RU-LIP", + "key": "lipetsk", + "mandatory": false, + "name_en": "Lipetsk Oblast", + "name_ru": "Липецкая область", + "order": 54, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.schools48.ru", + "schools48.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://edu.schools48.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "schools48.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://schools48.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Колыма" + ], + "cities": [ + "Магадан" + ], + "code": "49", + "dadata_names": [ + "Магаданская обл", + "Магаданская" + ], + "iso": "RU-MAG", + "key": "magadan", + "mandatory": false, + "name_en": "Magadan Oblast", + "name_ru": "Магаданская область", + "order": 55, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "bars", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "eschool.49gov.ru", + "openschool.49gov.ru", + "eschool.49edu.ru" + ], + "netschool": null, + "platform": "bars", + "role": "primary", + "web_url": "https://eschool.49gov.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Magadan" + }, + { + "aliases": [ + "Подмосковье", + "МО" + ], + "cities": [ + "Балашиха", + "Подольск", + "Химки", + "Мытищи", + "Королёв" + ], + "code": "50", + "dadata_names": [ + "Московская обл", + "Московская" + ], + "iso": "RU-MOS", + "key": "moscow-oblast", + "mandatory": true, + "name_en": "Moscow Oblast", + "name_ru": "Московская область", + "order": 56, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "authedu.mosreg.ru", + "myschool.mosreg.ru", + "api.myschool.mosreg.ru", + "food.myschool.mosreg.ru", + "help.myschool.mosreg.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://authedu.mosreg.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.mosreg.ru", + "login.school.mosreg.ru", + "api.school.mosreg.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://school.mosreg.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Мурманск", + "Апатиты", + "Североморск" + ], + "code": "51", + "dadata_names": [ + "Мурманская обл", + "Мурманская" + ], + "iso": "RU-MUR", + "key": "murmansk", + "mandatory": true, + "name_en": "Murmansk Oblast", + "name_ru": "Мурманская область", + "order": 57, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.mso51.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://edu.mso51.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "s51.edu.o7.com" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://s51.edu.o7.com" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Нижний Новгород", + "Дзержинск", + "Арзамас" + ], + "code": "52", + "dadata_names": [ + "Нижегородская обл", + "Нижегородская" + ], + "iso": "RU-NIZ", + "key": "nizhny-novgorod", + "mandatory": false, + "name_en": "Nizhny Novgorod Oblast", + "name_ru": "Нижегородская область", + "order": 58, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "eljur", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.gounn.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://edu.gounn.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Великий Новгород", + "Боровичи" + ], + "code": "53", + "dadata_names": [ + "Новгородская обл", + "Новгородская" + ], + "iso": "RU-NGR", + "key": "novgorod", + "mandatory": false, + "name_en": "Novgorod Oblast", + "name_ru": "Новгородская область", + "order": 59, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "53.dnevnik.ru", + "dnevnik.ru", + "login.dnevnik.ru", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://53.dnevnik.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru", + "gosuslugi.ru/myschool" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "legacy", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Новосибирск", + "Бердск" + ], + "code": "54", + "dadata_names": [ + "Новосибирская обл", + "Новосибирская" + ], + "iso": "RU-NVS", + "key": "novosibirsk", + "mandatory": false, + "name_en": "Novosibirsk Oblast", + "name_ru": "Новосибирская область", + "order": 60, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.nso.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://school.nso.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "legacy", + "web_url": "https://myschool.edu.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "shkola.nso.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://shkola.nso.ru" + } + ], + "tor": "front_end", + "zone": "Asia/Novosibirsk" + }, + { + "aliases": [], + "cities": [ + "Омск" + ], + "code": "55", + "dadata_names": [ + "Омская обл", + "Омская" + ], + "iso": "RU-OMS", + "key": "omsk", + "mandatory": false, + "name_en": "Omsk Oblast", + "name_ru": "Омская область", + "order": 61, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "55.dnevnik.ru", + "login.dnevnik.ru/login/esia/omsk", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Omsk" + }, + { + "aliases": [ + "Оренбуржье" + ], + "cities": [ + "Оренбург", + "Орск", + "Новотроицк" + ], + "code": "56", + "dadata_names": [ + "Оренбургская обл", + "Оренбургская" + ], + "iso": "RU-ORE", + "key": "orenburg", + "mandatory": false, + "name_en": "Orenburg Oblast", + "name_ru": "Оренбургская область", + "order": 62, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "moving_to", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "de.edu.orb.ru", + "edu.orb.ru", + "profile.de.edu.orb.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://de.edu.orb.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "migrating_to", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "moving_to", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [ + "Орловщина" + ], + "cities": [ + "Орёл", + "Ливны" + ], + "code": "57", + "dadata_names": [ + "Орловская обл", + "Орловская" + ], + "iso": "RU-ORL", + "key": "oryol", + "mandatory": false, + "name_en": "Oryol Oblast", + "name_ru": "Орловская область", + "order": 63, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.obr57.ru", + "passport.obr57.ru", + "mp2.obr57.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.obr57.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "vsopen.obr57.ru" + ], + "netschool": null, + "platform": "virtual-school", + "role": "legacy", + "web_url": "https://vsopen.obr57.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Пенза", + "Кузнецк" + ], + "code": "58", + "dadata_names": [ + "Пензенская обл", + "Пензенская" + ], + "iso": "RU-PNZ", + "key": "penza", + "mandatory": false, + "name_en": "Penza Oblast", + "name_ru": "Пензенская область", + "order": 64, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.edu-penza.ru", + "school.edu-penza.ru/login", + "school.edu-penza.ru/esia/auth/login", + "dnevnik.edu-penza.ru" + ], + "netschool": null, + "platform": "it-school-penza", + "role": "primary", + "web_url": "https://school.edu-penza.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "uko.edu-penza.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://uko.edu-penza.ru" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Псковщина" + ], + "cities": [ + "Псков", + "Великие Луки" + ], + "code": "60", + "dadata_names": [ + "Псковская обл", + "Псковская" + ], + "iso": "RU-PSK", + "key": "pskov", + "mandatory": false, + "name_en": "Pskov Oblast", + "name_ru": "Псковская область", + "order": 65, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.pskovedu.ru", + "passport.pskovedu.ru", + "gosuslugi.pskovedu.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.pskovedu.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Ростов-на-Дону", + "Таганрог", + "Шахты", + "Волгодонск" + ], + "code": "61", + "dadata_names": [ + "Ростовская обл", + "Ростовская" + ], + "iso": "RU-ROS", + "key": "rostov", + "mandatory": false, + "name_en": "Rostov Oblast", + "name_ru": "Ростовская область", + "order": 66, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sh-open.ris61edu.ru", + "col-open.ris61edu.ru", + "sh-open.rostobr.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://sh-open.ris61edu.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Рязанщина" + ], + "cities": [ + "Рязань" + ], + "code": "62", + "dadata_names": [ + "Рязанская обл", + "Рязанская" + ], + "iso": "RU-RYA", + "key": "ryazan", + "mandatory": false, + "name_en": "Ryazan Oblast", + "name_ru": "Рязанская область", + "order": 67, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "e-school.ryazan.gov.ru" + ], + "netschool": { + "origin": "https://e-school.ryazan.gov.ru", + "password": true, + "region": "ryazan", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://e-school.ryazan.gov.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "e-school.ryazangov.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://e-school.ryazangov.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Самара", + "Тольятти", + "Сызрань" + ], + "code": "63", + "dadata_names": [ + "Самарская обл", + "Самарская" + ], + "iso": "RU-SAM", + "key": "samara", + "mandatory": false, + "name_en": "Samara Oblast", + "name_ru": "Самарская область", + "order": 68, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "asurso.ru", + "spo.asurso.ru" + ], + "netschool": { + "origin": "https://asurso.ru", + "password": true, + "region": "samara", + "verified": false, + "zone": "Europe/Samara" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://asurso.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Samara" + }, + { + "aliases": [], + "cities": [ + "Саратов", + "Энгельс", + "Балаково" + ], + "code": "64", + "dadata_names": [ + "Саратовская обл", + "Саратовская" + ], + "iso": "RU-SAR", + "key": "saratov", + "mandatory": false, + "name_en": "Saratov Oblast", + "name_ru": "Саратовская область", + "order": 69, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru", + "64.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Saratov" + }, + { + "aliases": [ + "Сахалин" + ], + "cities": [ + "Южно-Сахалинск", + "Корсаков" + ], + "code": "65", + "dadata_names": [ + "Сахалинская обл", + "Сахалинская" + ], + "iso": "RU-SAK", + "key": "sakhalin", + "mandatory": false, + "name_en": "Sakhalin Oblast", + "name_ru": "Сахалинская область", + "order": 70, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "netcity.admsakhalin.ru:11111", + "netcity.admsakhalin.ru" + ], + "netschool": { + "origin": "https://netcity.admsakhalin.ru:11111", + "password": true, + "region": "sakhalin", + "verified": false, + "zone": "Asia/Sakhalin" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://netcity.admsakhalin.ru:11111" + } + ], + "tor": "unlisted", + "zone": "Asia/Sakhalin" + }, + { + "aliases": [ + "Средний Урал" + ], + "cities": [ + "Екатеринбург", + "Нижний Тагил", + "Каменск-Уральский" + ], + "code": "66", + "dadata_names": [ + "Свердловская обл", + "Свердловская" + ], + "iso": "RU-SVE", + "key": "sverdlovsk", + "mandatory": false, + "name_en": "Sverdlovsk Oblast", + "name_ru": "Свердловская область", + "order": 71, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.egov66.ru", + "jurnal.egov66.ru", + "lk.ecp.egov66.ru" + ], + "netschool": null, + "platform": "egov66", + "role": "legacy", + "web_url": "https://dnevnik.egov66.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "netcity.eimc.ru", + "sgo.egov66.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://netcity.eimc.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "primary", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [ + "Смоленщина" + ], + "cities": [ + "Смоленск", + "Вязьма" + ], + "code": "67", + "dadata_names": [ + "Смоленская обл", + "Смоленская" + ], + "iso": "RU-SMO", + "key": "smolensk", + "mandatory": false, + "name_en": "Smolensk Oblast", + "name_ru": "Смоленская область", + "order": 72, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.admin-smolensk.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://dnevnik.admin-smolensk.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Тамбовщина" + ], + "cities": [ + "Тамбов", + "Мичуринск" + ], + "code": "68", + "dadata_names": [ + "Тамбовская обл", + "Тамбовская" + ], + "iso": "RU-TAM", + "key": "tambov", + "mandatory": false, + "name_en": "Tambov Oblast", + "name_ru": "Тамбовская область", + "order": 73, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "dnevnik-ru", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru", + "schools.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "primary", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Тверь", + "Ржев" + ], + "code": "69", + "dadata_names": [ + "Тверская обл", + "Тверская" + ], + "iso": "RU-TVE", + "key": "tver", + "mandatory": true, + "name_en": "Tver Oblast", + "name_ru": "Тверская область", + "order": 74, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.tvobr.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://dnevnik.tvobr.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.tvobr.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.tvobr.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Томск", + "Северск" + ], + "code": "70", + "dadata_names": [ + "Томская обл", + "Томская" + ], + "iso": "RU-TOM", + "key": "tomsk", + "mandatory": false, + "name_en": "Tomsk Oblast", + "name_ru": "Томская область", + "order": 75, + "recommended": { + "confidence": "medium", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.tomedu.ru", + "poo.tomedu.ru" + ], + "netschool": { + "origin": "https://sgo.tomedu.ru", + "password": true, + "region": "tomsk", + "verified": false, + "zone": "Asia/Tomsk" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.tomedu.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Tomsk" + }, + { + "aliases": [], + "cities": [ + "Тула", + "Новомосковск" + ], + "code": "71", + "dadata_names": [ + "Тульская обл", + "Тульская" + ], + "iso": "RU-TUL", + "key": "tula", + "mandatory": false, + "name_en": "Tula Oblast", + "name_ru": "Тульская область", + "order": 76, + "recommended": { + "confidence": "medium", + "modifiers": [ + "esia_only" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": "https://sgo1.edu71.ru", + "hosts": [ + "sgo1.edu71.ru", + "sgo.edu71.ru" + ], + "netschool": { + "origin": "https://sgo1.edu71.ru", + "password": false, + "region": "tula", + "verified": false, + "zone": "Europe/Moscow" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo1.edu71.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Тюмень", + "Тобольск", + "Ишим" + ], + "code": "72", + "dadata_names": [ + "Тюменская обл", + "Тюменская" + ], + "iso": "RU-TYU", + "key": "tyumen", + "mandatory": true, + "name_en": "Tyumen Oblast", + "name_ru": "Тюменская область", + "order": 77, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-myschool", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.72to.ru", + "school.72to.ru", + "education.72to.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://myschool.72to.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "old-school.72to.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://old-school.72to.ru" + } + ], + "tor": "unlisted", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [], + "cities": [ + "Ульяновск", + "Димитровград" + ], + "code": "73", + "dadata_names": [ + "Ульяновская обл", + "Ульяновская" + ], + "iso": "RU-ULY", + "key": "ulyanovsk", + "mandatory": false, + "name_en": "Ulyanovsk Oblast", + "name_ru": "Ульяновская область", + "order": 78, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "netschool", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.cit73.ru", + "spo.cit73.ru" + ], + "netschool": { + "origin": "https://sgo.cit73.ru", + "password": true, + "region": "ulyanovsk", + "verified": false, + "zone": "Europe/Ulyanovsk" + }, + "platform": "netschool", + "role": "primary", + "web_url": "https://sgo.cit73.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Europe/Ulyanovsk" + }, + { + "aliases": [ + "Херсонщина" + ], + "cities": [ + "Геническ", + "Новая Каховка", + "Скадовск" + ], + "code": "95", + "dadata_names": [ + "Херсонская обл", + "Херсонская" + ], + "iso": null, + "key": "kherson", + "mandatory": false, + "name_en": "Kherson Oblast", + "name_ru": "Херсонская область", + "order": 79, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.edu.khogov.ru", + "passport.edu.khogov.ru", + "wp.edu.khogov.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.edu.khogov.ru" + } + ], + "tor": "absent", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Южный Урал" + ], + "cities": [ + "Челябинск", + "Магнитогорск", + "Златоуст", + "Миасс" + ], + "code": "74", + "dadata_names": [ + "Челябинская обл", + "Челябинская" + ], + "iso": "RU-CHE", + "key": "chelyabinsk", + "mandatory": false, + "name_en": "Chelyabinsk Oblast", + "name_ru": "Челябинская область", + "order": 80, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.edu-74.ru", + "es.edu-74.ru", + "poo.edu-74.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.edu-74.ru" + } + ], + "tor": "primary", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [], + "cities": [ + "Ярославль", + "Рыбинск" + ], + "code": "76", + "dadata_names": [ + "Ярославская обл", + "Ярославская" + ], + "iso": "RU-YAR", + "key": "yaroslavl", + "mandatory": false, + "name_en": "Yaroslavl Oblast", + "name_ru": "Ярославская область", + "order": 81, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.yarcloud.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://school.yarcloud.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "my.dnevnik76.ru", + "dnevnik76.ru" + ], + "netschool": null, + "platform": "dnevnik76", + "role": "legacy", + "web_url": "https://my.dnevnik76.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Мск" + ], + "cities": [ + "Зеленоград" + ], + "code": "77", + "dadata_names": [ + "г Москва", + "Москва" + ], + "iso": "RU-MOW", + "key": "moscow", + "mandatory": true, + "name_en": "Moscow", + "name_ru": "Москва", + "order": 82, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "mesh-moscow", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.mos.ru", + "dnevnik.mos.ru", + "login.mos.ru", + "uchebnik.mos.ru", + "myschool.mos.ru" + ], + "netschool": null, + "platform": "mesh-moscow", + "role": "primary", + "web_url": "https://school.mos.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "mrko.mos.ru", + "pgu.mos.ru" + ], + "netschool": null, + "platform": "mrko", + "role": "legacy", + "web_url": "https://mrko.mos.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "Питер", + "СПб", + "Петербург", + "Ленинград" + ], + "cities": [ + "Колпино", + "Пушкин", + "Петергоф", + "Кронштадт" + ], + "code": "78", + "dadata_names": [ + "г Санкт-Петербург", + "Санкт-Петербург" + ], + "iso": "RU-SPE", + "key": "saint-petersburg", + "mandatory": true, + "name_en": "Saint Petersburg", + "name_ru": "Санкт-Петербург", + "order": 83, + "recommended": { + "confidence": "high", + "modifiers": [ + "unverified" + ], + "platform": "petersburg", + "reason": "primary", + "system": 0 + }, + "systems": [ + { + "action": "signin", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik2.petersburgedu.ru", + "petersburgedu.ru" + ], + "netschool": null, + "platform": "petersburg", + "role": "primary", + "web_url": "https://dnevnik2.petersburgedu.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "app.eschool.center" + ], + "netschool": null, + "platform": "eschool-center", + "role": "secondary", + "web_url": "https://app.eschool.center" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "netschool.school.ioffe.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "secondary", + "web_url": "https://netschool.school.ioffe.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "secondary", + "web_url": "https://dnevnik.ru" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "petersburgedu.ru" + ], + "netschool": null, + "platform": "petersburg", + "role": "legacy", + "web_url": "https://dnevnik2.petersburgedu.ru" + } + ], + "tor": "unlisted", + "zone": "Europe/Moscow" + }, + { + "aliases": [], + "cities": [ + "Балаклава", + "Инкерман" + ], + "code": "92", + "dadata_names": [ + "г Севастополь", + "Севастополь" + ], + "iso": null, + "key": "sevastopol", + "mandatory": false, + "name_en": "Sevastopol", + "name_ru": "Севастополь", + "order": 84, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "paper", + "reason": "no_diary", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [], + "netschool": null, + "platform": "paper", + "role": "primary", + "web_url": null + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "riso.sev.gov.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://riso.sev.gov.ru" + } + ], + "tor": "absent", + "zone": "Europe/Simferopol" + }, + { + "aliases": [ + "ЕАО" + ], + "cities": [ + "Биробиджан" + ], + "code": "79", + "dadata_names": [ + "Еврейская Аобл", + "Еврейская" + ], + "iso": "RU-YEV", + "key": "eao", + "mandatory": false, + "name_en": "Jewish Autonomous Oblast", + "name_ru": "Еврейская автономная область", + "order": 85, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school", + "edu.gosuslugi.ru" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "dnevnik.ru", + "login.dnevnik.ru" + ], + "netschool": null, + "platform": "dnevnik-ru", + "role": "legacy", + "web_url": "https://dnevnik.ru" + } + ], + "tor": "primary", + "zone": "Asia/Vladivostok" + }, + { + "aliases": [ + "НАО" + ], + "cities": [ + "Нарьян-Мар" + ], + "code": "83", + "dadata_names": [ + "Ненецкий АО", + "Ненецкий" + ], + "iso": "RU-NEN", + "key": "nao", + "mandatory": false, + "name_en": "Nenets Autonomous Okrug", + "name_ru": "Ненецкий автономный округ", + "order": 86, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "tor-myschool", + "reason": "tor_primary", + "system": 0 + }, + "systems": [ + { + "action": "handoff", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "primary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "edu.adm-nao.ru" + ], + "netschool": null, + "platform": "bars", + "role": "legacy", + "web_url": "https://edu.adm-nao.ru" + } + ], + "tor": "primary", + "zone": "Europe/Moscow" + }, + { + "aliases": [ + "ХМАО", + "Югра", + "ХМАО — Югра" + ], + "cities": [ + "Ханты-Мансийск", + "Сургут", + "Нижневартовск", + "Нефтеюганск" + ], + "code": "86", + "dadata_names": [ + "Ханты-Мансийский Автономный округ - Югра", + "Ханты-Мансийский АО - Югра" + ], + "iso": "RU-KHM", + "key": "khmao", + "mandatory": false, + "name_en": "Khanty-Mansi Autonomous Okrug — Yugra", + "name_ru": "Ханты-Мансийский автономный округ — Югра", + "order": 87, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "eljur", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "cop.admhmao.ru", + "cop-sh.admhmao.ru", + "cop-spo.admhmao.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "primary", + "web_url": "https://cop.admhmao.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Yekaterinburg" + }, + { + "aliases": [ + "Чукотка", + "ЧАО" + ], + "cities": [ + "Анадырь", + "Билибино" + ], + "code": "87", + "dadata_names": [ + "Чукотский АО", + "Чукотский" + ], + "iso": "RU-CHU", + "key": "chukotka", + "mandatory": false, + "name_en": "Chukotka Autonomous Okrug", + "name_ru": "Чукотский автономный округ", + "order": 88, + "recommended": { + "confidence": "high", + "modifiers": [], + "platform": "one-x1", + "reason": "unsupported", + "system": 0 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "one.edu87.ru", + "passport.edu87.ru" + ], + "netschool": null, + "platform": "one-x1", + "role": "primary", + "web_url": "https://one.edu87.ru" + }, + { + "action": "handoff", + "confidence": "low", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + } + ], + "tor": "front_end", + "zone": "Asia/Anadyr" + }, + { + "aliases": [ + "ЯНАО", + "Ямал" + ], + "cities": [ + "Салехард", + "Новый Уренгой", + "Ноябрьск" + ], + "code": "89", + "dadata_names": [ + "Ямало-Ненецкий АО", + "Ямало-Ненецкий" + ], + "iso": "RU-YAN", + "key": "yanao", + "mandatory": true, + "name_en": "Yamalo-Nenets Autonomous Okrug", + "name_ru": "Ямало-Ненецкий автономный округ", + "order": 89, + "recommended": { + "confidence": "medium", + "modifiers": [], + "platform": "tor-myschool", + "reason": "front_end", + "system": 1 + }, + "systems": [ + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.yanao.ru" + ], + "netschool": null, + "platform": "mesh-myschool", + "role": "primary", + "web_url": "https://school.yanao.ru" + }, + { + "action": "handoff", + "confidence": "medium", + "excluded": null, + "front_end": true, + "handoff_url": "https://www.gosuslugi.ru/school", + "hosts": [ + "gosuslugi.ru/school" + ], + "netschool": null, + "platform": "tor-myschool", + "role": "secondary", + "web_url": "https://www.gosuslugi.ru/school" + }, + { + "action": "none", + "confidence": "medium", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "myschool.edu.ru" + ], + "netschool": null, + "platform": "fgis-myschool", + "role": "secondary", + "web_url": "https://myschool.edu.ru" + }, + { + "action": "none", + "confidence": "high", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "sgo.yanao.ru" + ], + "netschool": null, + "platform": "netschool", + "role": "legacy", + "web_url": "https://sgo.yanao.ru" + }, + { + "action": "none", + "confidence": "low", + "excluded": null, + "front_end": false, + "handoff_url": null, + "hosts": [ + "school.yanao.ru" + ], + "netschool": null, + "platform": "eljur", + "role": "legacy", + "web_url": "https://school.yanao.ru" + } + ], + "tor": "front_end", + "zone": "Asia/Yekaterinburg" + } + ], + "schema": 1, + "search": { + "cyrillic_layout": "ёйцукенгшщзхъфывапролджэячсмитьбю", + "fold": { + "-": " ", + "ё": "е", + "‐": " ", + "‑": " ", + "‒": " ", + "–": " ", + "—": " ", + "−": " " + }, + "latin_layout": "`qwertyuiop[]asdfghjkl;'zxcvbnm,.", + "school_words": [ + "школа", + "сош", + "оош", + "нош", + "гимназия", + "лицей", + "центр", + "образования", + "мбоу", + "маоу", + "моу", + "мкоу", + "гбоу", + "гоу", + "чоу", + "средняя", + "основная", + "общеобразовательная", + "№", + "n", + "no", + "номер" + ], + "stop_words": [ + "республика", + "респ", + "область", + "обл", + "край", + "автономный", + "автономная", + "автономной", + "округ", + "ао", + "аобл", + "город", + "г", + "федерального", + "значения" + ], + "translit": [ + [ + "shch", + "щ" + ], + [ + "sch", + "щ" + ], + [ + "zh", + "ж" + ], + [ + "kh", + "х" + ], + [ + "ts", + "ц" + ], + [ + "ch", + "ч" + ], + [ + "sh", + "ш" + ], + [ + "yo", + "ё" + ], + [ + "yu", + "ю" + ], + [ + "ya", + "я" + ], + [ + "ye", + "е" + ], + [ + "a", + "а" + ], + [ + "b", + "б" + ], + [ + "c", + "к" + ], + [ + "d", + "д" + ], + [ + "e", + "е" + ], + [ + "f", + "ф" + ], + [ + "g", + "г" + ], + [ + "h", + "х" + ], + [ + "i", + "и" + ], + [ + "j", + "й" + ], + [ + "k", + "к" + ], + [ + "l", + "л" + ], + [ + "m", + "м" + ], + [ + "n", + "н" + ], + [ + "o", + "о" + ], + [ + "p", + "п" + ], + [ + "q", + "к" + ], + [ + "r", + "р" + ], + [ + "s", + "с" + ], + [ + "t", + "т" + ], + [ + "u", + "у" + ], + [ + "v", + "в" + ], + [ + "w", + "в" + ], + [ + "x", + "кс" + ], + [ + "y", + "ы" + ], + [ + "z", + "з" + ] + ] + }, + "source": "docs/diaries/regions.md", + "survey": { + "month": "2026-09", + "school_year": "2026/27" + } +} diff --git a/server/pyproject.toml b/server/pyproject.toml index 6a0b67a3..24087a50 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -65,6 +65,15 @@ dependencies = [ [tool.setuptools.packages.find] include = ["app*", "scripts*"] +# The region catalog is data, not a module, and setuptools packages only modules +# unless told otherwise. An editable install and Vercel both read it straight out +# of the source tree, so nothing here would notice it missing — a wheel would ship +# `app.catalog` without the file it opens, and the directory endpoint would fail on +# its first request. It is generated by `scripts/region_catalog.py`; the overlay it +# is generated from stays out of the package, because nothing at runtime reads it. +[tool.setuptools.package-data] +app = ["catalog/data/*.json"] + [project.optional-dependencies] dev = [ "pytest>=8.0", diff --git a/server/scripts/region_catalog.py b/server/scripts/region_catalog.py new file mode 100644 index 00000000..0f2e148c --- /dev/null +++ b/server/scripts/region_catalog.py @@ -0,0 +1,859 @@ +"""Generate ``app/catalog/data/regions.json`` from the survey of every region's diary. + +The phone asks «which region are you in» before it asks anything else, and the +answer decides what it offers: a sign-in, a hand-off to Госуслуги, or a class +code. That answer is the survey's (``docs/diaries/regions.md``), which is +markdown written for people. This turns it into data once, at build time, so +that neither the phone nor the server ever parses prose, and the survey stays +the one place a region's diary is written down. + +Three inputs, and what each is trusted for: + +- ``docs/diaries/regions.md`` — which systems a region runs, in what role, on + which hosts, how sure the survey is. ``docs/diaries.md``'s tables are read + only to cross-check it: they are a tool's summary and cut names off with «…». +- ``app/providers/netschool/regions.py`` and the Petersburg client's + ``BASE_URL`` — every origin a sign-in may go to. Never the survey's hosts: + the allow-list is the server's one guard against being pointed at somebody's + address, and a hand-typed copy on the phone would be a second allow-list. +- ``region_catalog.toml`` beside this file — what nothing in the repository + derives: keys, codes, English names, zones, aliases, cities, DaData's + spellings, the platforms' names, and the phone's search lexicon. + +``action`` and ``recommended`` are decided here and nowhere else. The phone +reads them rather than re-deriving them, because two implementations of «which +diary should this family use» disagree within a month. + +Run from ``server/``: ``python -m scripts.region_catalog`` writes the file; +``--check`` fails when the committed one is not what this would write, which is +what ``tests/test_region_catalog.py`` runs so a survey edit cannot ship without +the catalog it implies. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +import tomllib +from collections import Counter +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from app.catalog import normalise_name +from app.providers.diary import registry +from app.providers.netschool import regions as allow_list +from app.providers.petersburg.client import BASE_URL as PETERSBURG_ORIGIN + +SERVER = Path(__file__).resolve().parents[1] +ROOT = SERVER.parent +REGIONS_MD = ROOT / "docs" / "diaries" / "regions.md" +DIARIES_MD = ROOT / "docs" / "diaries.md" +PAGES = ROOT / "docs" / "diaries" +OVERLAY = Path(__file__).resolve().with_name("region_catalog.toml") +OUTPUT = SERVER / "app" / "catalog" / "data" / "regions.json" + +SCHEMA = 1 +SOURCE = "docs/diaries/regions.md" + +#: The survey's role words, mapped onto the research's own vocabulary, which +#: shows through in regions.md's «Corrected during verification» prose. +ROLES = { + "in use now": "primary", + "alongside": "secondary", + "previous": "legacy", + "moving to": "migrating_to", + "unclear": "unclear", +} +#: Roles a family is never offered: a system the region has left, and one the +#: survey could not place. Their ``action`` is ``none`` whatever the platform. +NEVER_OFFERED = ("legacy", "unclear") +CONFIDENCE = ("low", "medium", "high") + +TOR = "tor-myschool" +PETERSBURG = registry.PETERSBURG +NETSCHOOL = registry.NETSCHOOL +#: Where every ТОР row hands off to. Госуслуги's own page, opened in whatever +#: the phone opens links with — never signed into from here (the decision +#: record, §1: a Госуслуги session is a session to the whole state account). +TOR_HANDOFF = "https://www.gosuslugi.ru/school" + +#: The words the phone decodes. It has a string resource per reason and per +#: modifier (its «почему» sheet) and a branch per state, so a new word here is a +#: phone change first and a generator change second, never the other way round. +REASONS = ( + "primary", "tor_primary", "front_end", "moving_to", "unreachable", "unsupported", "no_diary", +) +MODIFIERS = ("unverified", "esia_only") +KINDS = ("diary", "portal", "admissions", "none") +SIGNIN = ("password", "mixed", "esia_only", "oauth", "retired", "unknown", "none") +TOR_STATES = ("primary", "moving_to", "front_end", "unclear", "absent", "unlisted") +EXCLUSIONS = ("http-only",) + +_KEY = re.compile(r"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$") +_MANDATORY = "*Mandatory region.*" +_ROLE_START = re.compile(r"^- \*\*(?:in use now|alongside|previous|moving to|unclear):") +_BULLET = re.compile(r"^- \*\*(in use now|alongside|previous|moving to|unclear): (.+?)\*\* — (.*)$") +_LINK = re.compile(r"^\[([^\]]+)\]\(([a-z0-9-]+)\.md\)( as a front end)?$") +# Anchored on the labels, never on the first full stop: «Since» carries +# «01.12.2016», a label can be «Е-услуги. Образование», and every host is dots. +_HOSTS = re.compile(r"Hosts: (`[^`]+`(?:, `[^`]+`)*)\. (?=Since: |Confidence: )") +_CONFIDENCE = re.compile(r"Confidence: (high|medium|low)\.$") +_TABLE_LINK = re.compile(r"^\[[^\]]+\]\(diaries/([a-z0-9-]+)\.md\)") +_MONTHS = ( + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", +) +_SURVEY_MONTH = re.compile(r"In use now \((" + "|".join(_MONTHS) + r") (\d{4})\)") + + +class CatalogError(Exception): + """The survey, the overlay and the allow-list do not add up to a catalog.""" + + +# -------------------------------------------------------------------------- +# The survey +# -------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Host: + """One address from a bullet's ``Hosts:``, taken apart. + + ``name`` is the Unicode form and ``ascii`` the one a URL is built from, so + that «школа.образование33.рф» and its punycode twin are one host, not two. + ``*.eljur.ru`` stays a pattern: it names every school's subdomain and is + never somewhere to send anybody. + """ + + name: str + ascii: str + port: int | None + path: str + + @property + def pattern(self) -> bool: + return self.name.startswith("*.") + + def display(self) -> str: + port = f":{self.port}" if self.port is not None else "" + return f"{self.name}{port}{self.path}" + + def url(self) -> str | None: + if self.pattern: + return None + port = f":{self.port}" if self.port is not None else "" + return f"https://{self.ascii}{port}{self.path}" + + +@dataclass(frozen=True) +class SurveySystem: + role: str + label: str + page: str | None + front_end: bool + hosts: tuple[Host, ...] + confidence: str + + +@dataclass(frozen=True) +class SurveyRegion: + name: str + mandatory: bool + systems: tuple[SurveySystem, ...] + + +def parse_host(token: str) -> Host: + """``netcity.admsakhalin.ru:11111`` → name, port; ``gosuslugi.ru/school`` → name, path.""" + text = token.strip().replace("\\|", "|").lower() + head, slash, rest = text.partition("/") + name, colon, port = head.partition(":") + if colon and not port.isdigit(): + raise CatalogError(f"host «{token}» has a port that is not a number") + if not name: + raise CatalogError(f"host «{token}» has no name") + if name.startswith("*."): + ascii_name = name + else: + try: + ascii_name = name.encode("idna").decode("ascii") + except UnicodeError as exc: + raise CatalogError(f"host «{token}» is not a hostname: {exc}") from exc + name = ascii_name.encode("ascii").decode("idna") + return Host( + name=name, + ascii=ascii_name, + port=int(port) if colon else None, + path=slash + rest if slash else "", + ) + + +def _hosts(tokens: Sequence[str]) -> tuple[Host, ...]: + """Parsed, with an IDN and its punycode twin folded into the first seen.""" + seen: set[tuple[str, int | None, str]] = set() + kept: list[Host] = [] + for token in tokens: + host = parse_host(token) + identity = (host.ascii, host.port, host.path) + if identity in seen: + continue + seen.add(identity) + kept.append(host) + return tuple(kept) + + +def _system(line: str, region: str) -> SurveySystem: + match = _BULLET.match(line) + if match is None: + raise CatalogError(f"{region}: a system bullet this cannot read: {line[:120]}") + role_words, label, body = match.groups() + label = label.replace("\\|", "|") + + page: str | None = None + front_end = False + link = _LINK.match(label) + if link is not None: + label, page, front = link.groups() + front_end = front is not None + + if body.count("Confidence: ") != 1 or (confidence := _CONFIDENCE.search(body)) is None: + raise CatalogError(f"{region}: «{label}» must end on exactly one «Confidence: …».") + tokens: list[str] = [] + if "Hosts: " in body: + hosts = _HOSTS.findall(body) + if len(hosts) != 1 or body.count("Hosts: ") != 1: + raise CatalogError(f"{region}: «{label}» has a «Hosts:» field this cannot read.") + tokens = re.findall(r"`([^`]+)`", hosts[0]) + + return SurveySystem( + role=ROLES[role_words], + label=label, + page=page, + front_end=front_end, + hosts=_hosts(tokens), + confidence=confidence.group(1), + ) + + +def parse_survey(text: str) -> list[SurveyRegion]: + """Every ``## `` block of regions.md, with its system bullets, in file order. + + The other bullets of a block — «Open-source clients», «Notes.», «Checked:» + — and the indented evidence under each system are not read. A bullet that + *starts* like a system but does not parse stops the build rather than + leaving a region one system short. + """ + parsed: list[SurveyRegion] = [] + for block in re.split(r"^## ", text, flags=re.MULTILINE)[1:]: + lines = block.splitlines() + name = lines[0].strip() + systems = tuple( + _system(line, name) for line in lines[1:] if _ROLE_START.match(line) + ) + mandatory = any(line.strip() == _MANDATORY for line in lines[1:]) + parsed.append(SurveyRegion(name=name, mandatory=mandatory, systems=systems)) + return parsed + + +def _table(text: str, header_start: str) -> list[list[str]]: + """The rows of the markdown table whose header line starts with ``header_start``.""" + lines = text.splitlines() + starts = [index for index, line in enumerate(lines) if line.startswith(header_start)] + if len(starts) != 1: + raise CatalogError(f"docs/diaries.md has {len(starts)} tables headed «{header_start}»") + rows: list[list[str]] = [] + # Past the header and the «| --- |» line under it. + for line in lines[starts[0] + 2 :]: + if not line.startswith("|"): + break + cells = re.split(r"(? dict[str, tuple[int, int]]: + """docs/diaries.md's platforms table: page → (regions on it now, moving to it).""" + def number(cell: str) -> int: + return 0 if cell == "—" else int(cell) + + counts: dict[str, tuple[int, int]] = {} + for cells in _table(text, "| Platform | Regions on it now |"): + link = _TABLE_LINK.match(cells[0]) + if link is None: + raise CatalogError(f"the platforms table has a row with no page: {cells[0]}") + counts[link.group(1)] = (number(cells[1]), number(cells[2])) + return counts + + +def survey_month(text: str) -> str: + """«In use now (September 2026)» in the regions table's header, as ``2026-09``.""" + match = _SURVEY_MONTH.search(text) + if match is None: + raise CatalogError("docs/diaries.md's regions table does not say which month it is") + return f"{match.group(2)}-{_MONTHS.index(match.group(1)) + 1:02d}" + + +def cross_check(survey: Sequence[SurveyRegion], table_md: str) -> None: + """Hold regions.md to the summary table in docs/diaries.md, row by row. + + The table is a tool's summary and truncates, so it is never read for data — + but it is what a reader looks at first, and a survey edit that leaves the two + disagreeing about a region's diary is one of them being wrong. + """ + rows = _table(table_md, "| Region | In use now (") + names = [region.name for region in survey] + table_names = [cells[0].strip("*") for cells in rows] + if table_names != names: + raise CatalogError("docs/diaries.md's regions table and regions.md list different regions") + for region, cells in zip(survey, rows, strict=True): + where = f"docs/diaries.md, {region.name}" + if cells[0].startswith("**") != region.mandatory: + raise CatalogError(f"{where}: bold in the table and «{_MANDATORY}» disagree") + primary = _primary(region) + link = _TABLE_LINK.match(cells[1]) + if primary.page is None: + if link is not None or not cells[1].startswith(primary.label): + raise CatalogError(f"{where}: the table's first system is not «{primary.label}»") + elif link is None or link.group(1) != primary.page: + raise CatalogError(f"{where}: the table's first system is not on {primary.page}.md") + if cells[4] != primary.confidence: + raise CatalogError(f"{where}: the table's confidence is not the primary's") + moving = [system for system in region.systems if system.role == "migrating_to"] + moving_link = _TABLE_LINK.match(cells[2]) + if [system.page for system in moving] != ([moving_link.group(1)] if moving_link else []): + raise CatalogError(f"{where}: «Moving to» and the «moving to» bullets disagree") + + +def _primary(region: SurveyRegion) -> SurveySystem: + primaries = [system for system in region.systems if system.role == "primary"] + if len(primaries) != 1: + raise CatalogError(f"{region.name}: {len(primaries)} «in use now» systems, not one") + return primaries[0] + + +# -------------------------------------------------------------------------- +# The overlay +# -------------------------------------------------------------------------- + + +def _fields(entry: dict[str, Any], required: set[str], optional: set[str], where: str) -> None: + missing = required - entry.keys() + unknown = entry.keys() - required - optional + if missing or unknown: + raise CatalogError( + f"{where}: missing {sorted(missing)}, unknown {sorted(unknown)} in the overlay" + ) + + +@dataclass(frozen=True) +class Platform: + key: str + page: str | None + host: str | None + name_ru: str + name_en: str + kind: str + signin: str + verified: bool + + @property + def provider(self) -> str | None: + return self.key if self.key in registry.KEYS else None + + def out(self) -> dict[str, Any]: + return { + "name_ru": self.name_ru, + "name_en": self.name_en, + "page": self.page, + "provider": self.provider, + "kind": self.kind, + "signin": self.signin, + "origin": PETERSBURG_ORIGIN if self.key == PETERSBURG else None, + "handoff": TOR_HANDOFF if self.key == TOR else None, + } + + +def _platforms(overlay: dict[str, Any]) -> dict[str, Platform]: + platforms: dict[str, Platform] = {} + for entry in overlay.get("platform", []): + where = f"[[platform]] {entry.get('key')!r}" + _fields(entry, {"key", "name_ru", "name_en", "kind", "signin"}, + {"page", "host", "verified"}, where) + key = entry["key"] + if key in platforms or not _KEY.match(key): + raise CatalogError(f"{where}: a platform key must be a unique slug") + if entry["kind"] not in KINDS or entry["signin"] not in SIGNIN: + raise CatalogError(f"{where}: kind must be one of {KINDS}, signin one of {SIGNIN}") + page = entry.get("page") + if page is not None and not (PAGES / f"{page}.md").is_file(): + raise CatalogError(f"{where}: docs/diaries/{page}.md does not exist") + if "verified" in entry and key != PETERSBURG: + # «Сетевой город»'s answer is per region and lives in the allow-list. + raise CatalogError(f"{where}: only Petersburg's `verified` is kept here") + _names(entry, where) + platforms[key] = Platform( + key=key, + page=page, + host=entry.get("host"), + name_ru=entry["name_ru"], + name_en=entry["name_en"], + kind=entry["kind"], + signin=entry["signin"], + verified=bool(entry.get("verified", False)), + ) + for needed in (PETERSBURG, NETSCHOOL, TOR): + if needed not in platforms: + raise CatalogError(f"the overlay has no [[platform]] {needed!r}") + return platforms + + +def _names(entry: dict[str, Any], where: str) -> None: + """Both names, and the English one really English — it is the only twin they get. + + Names in the JSON escape ``ResourceTranslationTest``, which is what holds + every other Russian string on the phone to an English one. + """ + ru, en = entry["name_ru"].strip(), entry["name_en"].strip() + if not ru or not en or re.search(r"[Ѐ-ӿ]", en): + raise CatalogError(f"{where}: needs a Russian name and an English one without Cyrillic") + + +def _platform_of( + system: SurveySystem, platforms: dict[str, Platform], unlinked: dict[str, str], region: str +) -> Platform: + if system.page is None: + key = unlinked.get(system.label) + if key is None: + raise CatalogError(f"{region}: «{system.label}» links no page and is not in [unlinked]") + return platforms[key] + candidates = [platform for platform in platforms.values() if platform.page == system.page] + if len(candidates) > 1: + # One page, several platforms: myschool-federal.md is both ТОР and the + # federal portal, and only the host says which a bullet means. + shown = {host.display() for host in system.hosts} + candidates = [platform for platform in candidates if platform.host in shown] + if len(candidates) != 1: + raise CatalogError(f"{region}: «{system.label}» maps to {len(candidates)} platforms") + return candidates[0] + + +@dataclass(frozen=True) +class RegionSpec: + name_ru: str + key: str + code: str + iso: str | None + name_en: str + zone: str + aliases: tuple[str, ...] + cities: tuple[str, ...] + dadata_names: tuple[str, ...] + tor_absent: bool + netschool_excluded: str | None + + +def _region_specs(overlay: dict[str, Any], survey: Sequence[SurveyRegion]) -> dict[str, RegionSpec]: + specs: dict[str, RegionSpec] = {} + keys: set[str] = set() + codes: set[str] = set() + dadata: dict[str, str] = {} + for entry in overlay.get("region", []): + where = f"[[region]] {entry.get('name_ru')!r}" + _fields( + entry, + {"name_ru", "key", "code", "name_en", "zone", "aliases", "cities", "dadata_names"}, + {"iso", "tor", "netschool_excluded"}, + where, + ) + key, code = entry["key"], entry["code"] + if not _KEY.match(key) or len(key) > 32 or key in keys: + # 32: the width of classes.diary_region and diary_sessions.region. + raise CatalogError(f"{where}: key must be a unique slug of at most 32 characters") + if not re.fullmatch(r"\d\d", code) or code in codes: + raise CatalogError(f"{where}: code must be two digits and unique") + try: + ZoneInfo(entry["zone"]) + except (ZoneInfoNotFoundError, ValueError) as exc: + raise CatalogError(f"{where}: zone {entry['zone']!r} is not an IANA zone") from exc + if entry.get("tor") not in (None, "absent"): + raise CatalogError(f"{where}: `tor` can only say «absent»; the survey says the rest") + if entry.get("netschool_excluded") not in (None, *EXCLUSIONS): + raise CatalogError(f"{where}: netschool_excluded must be one of {EXCLUSIONS}") + if not entry["dadata_names"]: + raise CatalogError(f"{where}: needs at least one of DaData's spellings") + for name in entry["dadata_names"]: + other = dadata.setdefault(normalise_name(name), key) + if other != key: + raise CatalogError(f"{where}: DaData's «{name}» already places {other!r}") + _names(entry, where) + keys.add(key) + codes.add(code) + if entry["name_ru"] in specs: + raise CatalogError(f"{where}: listed twice") + specs[entry["name_ru"]] = RegionSpec( + name_ru=entry["name_ru"], + key=key, + code=code, + iso=entry.get("iso"), + name_en=entry["name_en"], + zone=entry["zone"], + aliases=tuple(entry["aliases"]), + cities=tuple(entry["cities"]), + dadata_names=tuple(entry["dadata_names"]), + tor_absent=entry.get("tor") == "absent", + netschool_excluded=entry.get("netschool_excluded"), + ) + headings = {region.name for region in survey} + if set(specs) != headings: + raise CatalogError( + "the overlay's regions are not regions.md's headings: " + f"missing {sorted(headings - set(specs))}, unknown {sorted(set(specs) - headings)}" + ) + return specs + + +def _search(overlay: dict[str, Any]) -> dict[str, Any]: + search = overlay.get("search", {}) + _fields( + search, + {"fold", "stop_words", "latin_layout", "cyrillic_layout", "translit", "school_words"}, + set(), + "[search]", + ) + latin, cyrillic = search["latin_layout"], search["cyrillic_layout"] + if len(latin) != len(cyrillic) or len(set(latin)) != len(latin) or len(set(cyrillic)) != len( + cyrillic + ): + raise CatalogError("[search]: the two layouts must pair key for key, each key once") + if any(len(source) != 1 or len(target) != 1 for source, target in search["fold"].items()): + raise CatalogError("[search]: fold maps one character to one character") + pairs = [tuple(pair) for pair in search["translit"]] + if any(len(pair) != 2 or not pair[0].isascii() for pair in pairs): + raise CatalogError("[search]: translit is a list of [latin, cyrillic] pairs") + if [len(pair[0]) for pair in pairs] != sorted((len(pair[0]) for pair in pairs), reverse=True): + raise CatalogError("[search]: translit must list longer Latin spellings first") + return { + "fold": dict(search["fold"]), + "stop_words": list(search["stop_words"]), + "latin_layout": latin, + "cyrillic_layout": cyrillic, + "translit": [list(pair) for pair in pairs], + "school_words": list(search["school_words"]), + } + + +def _survey_block(overlay: dict[str, Any], table_md: str) -> dict[str, str]: + block = overlay.get("survey", {}) + _fields(block, {"month"}, set(), "[survey]") + month = block["month"] + if month != survey_month(table_md): + raise CatalogError(f"[survey] month {month} is not the month docs/diaries.md describes") + year, number = (int(part) for part in month.split("-")) + # A survey from September onwards describes the year that has just begun. + start = year if number >= 9 else year - 1 + return {"month": month, "school_year": f"{start}/{(start + 1) % 100:02d}"} + + +# -------------------------------------------------------------------------- +# Deciding +# -------------------------------------------------------------------------- + + +def _netschool_block( + region: RegionSpec, system: SurveySystem, platform: Platform +) -> dict[str, Any] | None: + """The allow-list row this system is, or ``None`` if the phone may not go there. + + Linked by the region's key and nothing else — the survey's hosts only have + to *agree* with the allow-list's origin, which catches a region whose server + moved in one file and not the other. + """ + if platform.key != NETSCHOOL or system.role in NEVER_OFFERED: + return None + row = allow_list.get(region.key) + if row is None: + return None + origin = urlsplit(row.origin) + shown = {(host.ascii, host.port) for host in system.hosts if not host.path} + if (origin.hostname, origin.port) not in shown: + raise CatalogError( + f"{region.name_ru}: the allow-list's {row.origin} is not among the survey's hosts" + ) + if row.title != region.name_ru: + raise CatalogError(f"{region.name_ru}: the allow-list calls {row.key!r} «{row.title}»") + return { + "region": row.key, + "origin": row.origin, + "password": row.password, + "verified": row.verified, + "zone": row.zone, + } + + +def _system_out(region: RegionSpec, system: SurveySystem, platform: Platform) -> dict[str, Any]: + netschool = _netschool_block(region, system, platform) + excluded = None + if platform.key == NETSCHOOL and system.role == "primary" and region.netschool_excluded: + excluded = region.netschool_excluded + + action, handoff = "none", None + if system.role not in NEVER_OFFERED: + if platform.key == PETERSBURG: + action = "signin" + elif netschool is not None: + # A password region is signed into on the phone; a Госуслуги-only one + # is its own origin's page, whose Госуслуги button the family presses + # in the browser (K19) — not ТОР's, which is a different diary. + action, handoff = ("signin", None) if netschool["password"] else ( + "handoff", netschool["origin"] + ) + elif platform.key == TOR: + action, handoff = "handoff", TOR_HANDOFF + + if platform.key == PETERSBURG: + web_url: str | None = PETERSBURG_ORIGIN + elif netschool is not None: + web_url = netschool["origin"] + elif platform.key == TOR: + web_url = TOR_HANDOFF + elif excluded is not None: + # An origin that serves only http is not somewhere this app sends anybody. + web_url = None + else: + web_url = next((url for host in system.hosts if (url := host.url())), None) + + return { + "platform": platform.key, + "role": system.role, + "front_end": system.front_end, + "confidence": system.confidence, + "hosts": [host.display() for host in system.hosts], + "action": action, + "handoff_url": handoff, + "web_url": web_url, + "netschool": netschool, + "excluded": excluded, + } + + +def recommend(systems: Sequence[dict[str, Any]], platforms: dict[str, Platform]) -> dict[str, Any]: + """Which one system the phone puts first for a region, and why. First match wins. + + 1. The primary, if it can be signed into here: ``primary``, plus + ``unverified`` while nobody has signed into it for real. + 2. The primary, if it is ТОР: ``tor_primary``. + 3. The primary, if it is a Госуслуги-only «Сетевой город»: ``primary`` + + ``esia_only``. + 4. The primary, if it is a «Сетевой город» the allow-list leaves out + (Волгоград): ``unreachable``. It sits above the front-end rule on + purpose: Волгоград also has «Госуслуги Моя школа» in front of it, and the + family should first be told why their own diary cannot be opened. + 5. ТОР in front of the regional system, sure at least to «medium»: + ``front_end``. + 6. ТОР as where the region is moving: ``moving_to``. + 7. Otherwise the primary, which the app cannot read: ``unsupported`` — or + ``no_diary`` where it is paper. + + The JSON carries only these codes; the sentences are the phone's string + resources, so every one of them has its English twin checked. + """ + primary_index = next(i for i, system in enumerate(systems) if system["role"] == "primary") + primary = systems[primary_index] + + def pick(index: int, reason: str, modifiers: Sequence[str] = ()) -> dict[str, Any]: + return { + "system": index, + "platform": systems[index]["platform"], + "confidence": systems[index]["confidence"], + "reason": reason, + "modifiers": list(modifiers), + } + + def verified(system: dict[str, Any]) -> bool: + if system["netschool"] is not None: + return bool(system["netschool"]["verified"]) + return platforms[system["platform"]].verified + + if primary["action"] == "signin": + return pick(primary_index, "primary", () if verified(primary) else ("unverified",)) + if primary["platform"] == TOR: + return pick(primary_index, "tor_primary") + if primary["platform"] == NETSCHOOL and primary["action"] == "handoff": + return pick(primary_index, "primary", ("esia_only",)) + if primary["excluded"] is not None: + return pick(primary_index, "unreachable") + for index, system in enumerate(systems): + if ( + system["platform"] == TOR + and system["front_end"] + and system["role"] == "secondary" + and CONFIDENCE.index(system["confidence"]) >= CONFIDENCE.index("medium") + ): + return pick(index, "front_end") + for index, system in enumerate(systems): + if system["platform"] == TOR and system["role"] == "migrating_to": + return pick(index, "moving_to") + if platforms[primary["platform"]].kind == "none": + return pick(primary_index, "no_diary") + return pick(primary_index, "unsupported") + + +def _tor_state(systems: Sequence[dict[str, Any]], spec: RegionSpec) -> str: + """Where ТОР stands in a region: the phone never offers it where this is «absent».""" + tor = [system for system in systems if system["platform"] == TOR] + roles = {system["role"] for system in tor} + if spec.tor_absent: + if tor: + raise CatalogError(f"{spec.name_ru}: `tor` says absent, and the survey lists ТОР") + return "absent" + if "primary" in roles: + return "primary" + if "migrating_to" in roles: + return "moving_to" + if any(system["front_end"] and system["role"] == "secondary" for system in tor): + return "front_end" + if "unclear" in roles: + return "unclear" + # The survey lists no ТОР row here. docs/diaries.md says the app is offered + # in front of every regional system but two, without evidence per region; + # «unlisted» says exactly that much and no more. + return "unlisted" + + +# -------------------------------------------------------------------------- +# Building +# -------------------------------------------------------------------------- + + +def build(regions_md: str, table_md: str, overlay: dict[str, Any]) -> dict[str, Any]: + """The whole catalog, as a JSON-ready dict, or a :class:`CatalogError` saying why not.""" + survey = parse_survey(regions_md) + cross_check(survey, table_md) + platforms = _platforms(overlay) + unlinked = dict(overlay.get("unlinked", {})) + for label, key in unlinked.items(): + if key not in platforms or platforms[key].page is not None: + raise CatalogError(f"[unlinked] «{label}» names {key!r}, not a page-less platform") + specs = _region_specs(overlay, survey) + + out_regions: list[dict[str, Any]] = [] + for order, surveyed in enumerate(survey, start=1): + spec = specs[surveyed.name] + _primary(surveyed) + systems = [ + _system_out(spec, system, _platform_of(system, platforms, unlinked, surveyed.name)) + for system in surveyed.systems + ] + if spec.netschool_excluded and not any(system["excluded"] for system in systems): + raise CatalogError(f"{spec.name_ru}: excluded, and no primary «Сетевой город»") + if spec.netschool_excluded and allow_list.get(spec.key) is not None: + raise CatalogError(f"{spec.name_ru}: excluded, yet the allow-list has it") + recommended = recommend(systems, platforms) + tor = _tor_state(systems, spec) + if tor == "absent" and recommended["platform"] == TOR: + raise CatalogError(f"{spec.name_ru}: ТОР recommended where the survey has none") + out_regions.append( + { + "key": spec.key, + "order": order, + "code": spec.code, + "iso": spec.iso, + "name_ru": spec.name_ru, + "name_en": spec.name_en, + "mandatory": surveyed.mandatory, + "zone": spec.zone, + "aliases": list(spec.aliases), + "cities": list(spec.cities), + "dadata_names": list(spec.dadata_names), + "systems": systems, + "recommended": recommended, + "tor": tor, + } + ) + + _check_allow_list(out_regions) + used = {system["platform"] for region in out_regions for system in region["systems"]} + if unused := sorted(set(platforms) - used): + raise CatalogError(f"platforms no region uses: {unused}; take them out of the overlay") + return { + "schema": SCHEMA, + "source": SOURCE, + "survey": _survey_block(overlay, table_md), + "search": _search(overlay), + "platforms": {key: platforms[key].out() for key in sorted(used)}, + "regions": out_regions, + } + + +def _check_allow_list(regions: Sequence[dict[str, Any]]) -> None: + """Every allow-listed region reached exactly once, under its own key, in its own zone.""" + linked = Counter( + system["netschool"]["region"] + for region in regions + for system in region["systems"] + if system["netschool"] is not None + ) + by_key = {region["key"]: region for region in regions} + for row in allow_list.listed(password_only=False): + if linked[row.key] != 1: + raise CatalogError(f"allow-listed {row.key!r} is linked {linked[row.key]} times") + region = by_key.get(row.key) + if region is None or region["zone"] != row.zone: + raise CatalogError(f"the allow-list's {row.key!r} has no region of that key and zone") + + +def render(catalog: dict[str, Any]) -> str: + """Deterministic text: sorted keys, the survey's region order, one trailing newline. + + Regions are never sorted by name — Russian collation files every + «Республика …» under Р, and the order the phone lists is the survey's. + """ + return json.dumps(catalog, ensure_ascii=False, indent=1, sort_keys=True) + "\n" + + +def build_from_repository() -> dict[str, Any]: + return build( + REGIONS_MD.read_text(encoding="utf-8"), + DIARIES_MD.read_text(encoding="utf-8"), + tomllib.loads(OVERLAY.read_text(encoding="utf-8")), + ) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="python -m scripts.region_catalog", description=__doc__) + parser.add_argument( + "--check", + action="store_true", + help="exit 1 if the committed catalog is not what this would write", + ) + args = parser.parse_args(argv) + try: + text = render(build_from_repository()) + except CatalogError as exc: + print(f"region catalog: {exc}", file=sys.stderr) + return 1 + relative = OUTPUT.relative_to(ROOT) + if args.check: + current = OUTPUT.read_text(encoding="utf-8") if OUTPUT.is_file() else "" + if current != text: + print( + f"{relative} is not what the survey implies; run " + "`python -m scripts.region_catalog` from server/ and commit the result", + file=sys.stderr, + ) + return 1 + print(f"{relative} is current") + return 0 + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + OUTPUT.write_text(text, encoding="utf-8") + print(f"wrote {relative}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/server/scripts/region_catalog.toml b/server/scripts/region_catalog.toml new file mode 100644 index 00000000..7cef140c --- /dev/null +++ b/server/scripts/region_catalog.toml @@ -0,0 +1,1325 @@ +# What the survey of every region's diary does not say, and the region catalog needs. +# +# `scripts/region_catalog.py` reads this beside `docs/diaries/regions.md` and writes +# `app/catalog/data/regions.json`. Everything the survey *does* say — which systems a +# region runs, in what role, on which hosts, how sure the survey is — comes from the +# survey and is never repeated here. Everything the allow-list says — which «Сетевой +# город» origins exist, whether a password gets in, whether an origin has been seen +# to answer — comes from `app/providers/netschool/regions.py` and is never repeated +# here either. This file is only what nothing in the repository derives. +# +# After an edit, from `server/`: +# +# python -m scripts.region_catalog # rewrites the JSON +# python -m scripts.region_catalog --check # what the test runs +# +# Rules the generator enforces, so that this file cannot drift quietly: +# +# - `name_ru` of every [[region]] is a `## ` heading of regions.md, character for +# character, and every heading has exactly one [[region]]. The order of the catalog +# is the survey's (Constitution Art. 65), not this file's. +# - `key` is what the database stores (`classes.diary_region`, `diary_sessions.region`, +# the sealed credential). The nineteen «Сетевой город» regions MUST keep the +# allow-list's key byte for byte — renaming one here orphans every class bound to it. +# The other seventy are slugs in the same style. Never rename a key once shipped. +# - `code` is the two-digit subject code (КЛАДР/ФНС numbering, the one DaData's +# `region_kladr_id` starts with). 91 Крым and 92 Севастополь are the long-standing +# ones. The four subjects admitted in 2022 are NOT VERIFIED: Запорожская 90, +# ДНР 93, ЛНР 94 and Херсонская 95 are what the survey's author believed the ФНС +# assigned, and nothing here has checked it against a live DaData answer or a +# primary source. `by_code` then misses, and the name fallback (`dadata_names`) is +# what places a school there. +# - `iso` is ISO 3166-2:RU, which has no code for the six subjects above; it is left +# out for them rather than invented. +# - `zone` is the IANA zone of the region's administrative centre. For a «Сетевой +# город» region it must equal the allow-list's zone. The four 2022 subjects keep +# Europe/Moscow: tzdata's own names for Запорожье and Херсон are links to Kyiv time. +# - `dadata_names` are the spellings DaData's `region_with_type` and `region` use for +# the region — «Респ Татарстан», «г Москва», «Ленинградская обл». They are compared +# after `app.catalog.normalise_name` (case, ё, punctuation, spaces) and must place +# exactly one region each. None of them has been checked against a live answer. +# - `aliases` are what people type instead of the name: official long forms and the +# informal ones. `cities` are a few large towns, so that «Тольятти» finds Самарская. +# Both are search hints for the phone, never shown as a region's name. +# +# Nothing in this file may describe signing in on a diary's own page inside the app: +# there is no such surface (the decision record, §1), and +# `test_only_petersburg_and_password_netschool_are_signable` reads this file too. + +[survey] +# The month the survey describes; `docs/diaries.md`'s regions table says it in its +# header («In use now (September 2026)») and the generator holds the two equal. +month = "2026-09" + +# --------------------------------------------------------------------------------- +# The lexicon the phone's region search is built from. +# +# It is data rather than Kotlin because every entry is Cyrillic, and `:app` keeps +# Russian out of its source (the `grep` check in CLAUDE.md). The phone lower-cases, +# applies `fold`, turns any other punctuation into a space, drops `stop_words`, and +# also tries the query through the keyboard-layout swap and, for a Latin query, +# through `translit`. `school_words` are what make a query look like a school's name +# rather than a region's — and «школа 5», with nothing distinctive left once they are +# gone, is too common to look up at all. +# --------------------------------------------------------------------------------- +[search] +stop_words = [ + "республика", "респ", "область", "обл", "край", "автономный", "автономная", + "автономной", "округ", "ао", "аобл", "город", "г", "федерального", "значения", +] +# The same keys in the same places: a query typed with the wrong layout is +# «cfvfhf» for «самара». Position n of one string is position n of the other. +latin_layout = "`qwertyuiop[]asdfghjkl;'zxcvbnm,." +cyrillic_layout = "ёйцукенгшщзхъфывапролджэячсмитьбю" +# Longest first: the phone takes the first pair that matches at each position. +# Best effort, not a standard — «moskva», «kazan», «samara» and «tatarstan» come +# out whole, and a prefix is enough for the search to land. +translit = [ + ["shch", "щ"], ["sch", "щ"], ["zh", "ж"], ["kh", "х"], ["ts", "ц"], ["ch", "ч"], + ["sh", "ш"], ["yo", "ё"], ["yu", "ю"], ["ya", "я"], ["ye", "е"], + ["a", "а"], ["b", "б"], ["c", "к"], ["d", "д"], ["e", "е"], ["f", "ф"], ["g", "г"], + ["h", "х"], ["i", "и"], ["j", "й"], ["k", "к"], ["l", "л"], ["m", "м"], ["n", "н"], + ["o", "о"], ["p", "п"], ["q", "к"], ["r", "р"], ["s", "с"], ["t", "т"], ["u", "у"], + ["v", "в"], ["w", "в"], ["x", "кс"], ["y", "ы"], ["z", "з"], +] +# The words a school's name is made of rather than distinguished by. The server's +# directory answers «too common to place» for a query that is nothing else plus a +# number of one or two digits, and the phone asks the same question before it spends +# a search; this is the one list both read. +school_words = [ + "школа", "сош", "оош", "нош", "гимназия", "лицей", "центр", "образования", "мбоу", + "маоу", "моу", "мкоу", "гбоу", "гоу", "чоу", "средняя", "основная", + "общеобразовательная", "№", "n", "no", "номер", +] + +[search.fold] +"ё" = "е" +"‐" = " " +"‑" = " " +"‒" = " " +"–" = " " +"—" = " " +"−" = " " +"-" = " " + +# --------------------------------------------------------------------------------- +# Platforms: one per page under docs/diaries/, except myschool-federal.md, which +# describes two different things under three labels — ТОР «Моя школа», the diary +# reached through Госуслуги, and ФГИС «Моя школа», the federal portal that is not a +# diary at all. A system linking that page is told apart by `host`, never by label. +# +# `kind`: diary | portal | admissions | none (Севастополь's paper registers). +# `signin`: how the platform's own users get in, for reading only — password, mixed +# (it depends on the region), esia_only, oauth, retired, unknown, none. +# It never decides anything; `action` in the output does, and it comes +# from the provider registry and the allow-list, not from this word. +# `provider` is not written here: a platform is backed by a provider exactly when its +# key is one of `app.providers.diary.registry.KEYS`. +# Names carry no guillemets: the phone's sentences put their own around them. +# --------------------------------------------------------------------------------- + +[[platform]] +key = "petersburg" +page = "petersburg" +name_ru = "Петербургское образование" +name_en = "Petersburg Education" +kind = "diary" +signin = "password" +# The one provider-backed platform whose `verified` has no allow-list to live in. +# Nothing under providers/petersburg/ has been opened with a real account (#121). +verified = false + +[[platform]] +key = "netschool" +page = "netschool" +name_ru = "Сетевой город. Образование" +name_en = "Setevoy Gorod (NetSchool)" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "tor-myschool" +page = "myschool-federal" +host = "gosuslugi.ru/school" +name_ru = "Госуслуги Моя школа" +name_en = "Gosuslugi My School" +kind = "diary" +signin = "esia_only" + +[[platform]] +key = "fgis-myschool" +page = "myschool-federal" +host = "myschool.edu.ru" +name_ru = "ФГИС «Моя школа»" +name_en = "My School federal portal" +kind = "portal" +signin = "none" + +[[platform]] +key = "mesh-moscow" +page = "mesh-moscow" +name_ru = "МЭШ" +name_en = "Moscow Electronic School" +kind = "diary" +signin = "oauth" + +[[platform]] +key = "mesh-myschool" +page = "mesh-myschool" +name_ru = "Моя школа (МЭШ)" +name_en = "My School (MESH)" +kind = "diary" +signin = "esia_only" + +[[platform]] +key = "dnevnik-ru" +page = "dnevnik-ru" +name_ru = "Дневник.ру" +name_en = "Dnevnik.ru" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "eljur" +page = "eljur" +name_ru = "ЭлЖур" +name_en = "ElJur" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "bars" +page = "bars" +name_ru = "БАРС" +name_en = "BARS" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "one-x1" +page = "one-x1" +name_ru = "one." +name_en = "one." +kind = "diary" +signin = "mixed" + +[[platform]] +key = "kiasuo" +page = "kiasuo" +name_ru = "КИАСУО" +name_en = "KIASUO" +kind = "diary" +signin = "esia_only" + +[[platform]] +key = "epos" +page = "epos" +name_ru = "ЭПОС.Школа" +name_en = "EPOS.School" +kind = "diary" +signin = "esia_only" + +[[platform]] +key = "ruobr" +page = "ruobr" +name_ru = "Электронная школа 2.0" +name_en = "Electronic School 2.0" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "virtual-school" +page = "virtual-school" +name_ru = "Виртуальная школа" +name_en = "Virtual School" +kind = "diary" +signin = "oauth" + +[[platform]] +key = "elschool" +page = "elschool" +name_ru = "ELSCHOOL" +name_en = "ELSCHOOL" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "eschool-center" +page = "eschool-center" +name_ru = "eSchool" +name_en = "eSchool" +kind = "diary" +signin = "password" + +[[platform]] +key = "egov66" +page = "egov66" +name_ru = "ГИС СО «ЕЦП»" +name_en = "Sverdlovsk Oblast Unified Digital Platform" +kind = "diary" +signin = "retired" + +[[platform]] +key = "edu-tatar" +page = "edu-tatar" +name_ru = "edu.tatar.ru" +name_en = "edu.tatar.ru" +kind = "diary" +signin = "retired" + +[[platform]] +key = "dnevnik76" +page = "dnevnik76" +name_ru = "Дневник76" +name_en = "Dnevnik76" +kind = "diary" +signin = "retired" + +# Systems the survey names without a page of their own. Each is reached through the +# exact label in [unlinked] below, never by guessing from the words. + +[[platform]] +key = "e-uslugi" +name_ru = "Е-услуги. Образование" +name_en = "E-uslugi. Education" +kind = "admissions" +signin = "none" + +[[platform]] +key = "web2edu" +name_ru = "Web2edu" +name_en = "Web2edu" +kind = "diary" +signin = "unknown" + +[[platform]] +key = "avers" +name_ru = "Аверс" +name_en = "Avers" +kind = "diary" +signin = "unknown" + +[[platform]] +key = "mrko" +name_ru = "МРКО" +name_en = "MRKO (Moscow)" +kind = "diary" +signin = "retired" + +[[platform]] +key = "it-school-penza" +name_ru = "АйТи Школа" +name_en = "IT School (Penza)" +kind = "diary" +signin = "mixed" + +[[platform]] +key = "paper" +name_ru = "Бумажные журналы и дневники" +name_en = "Paper registers and diaries" +kind = "none" +signin = "none" + +# The survey's own words for a system with no page, as they stand in the bullet's bold +# label — truncations and all, because a label that changes should stop the build +# rather than fall through to a platform nobody chose. +[unlinked] +"Е-услуги. Образование" = "e-uslugi" +"Web2edu" = "web2edu" +"«Аверс»" = "avers" +"МРКО — «Электронный дневник школьника» (Московский регистр качества об…" = "mrko" +"«АйТи Школа» («АйТи Софт - Цифровая школа») — образовательный сервис Г…" = "it-school-penza" +"paper journals and diaries; no electronic diary" = "paper" + +# --------------------------------------------------------------------------------- +# The eighty-nine regions, in the survey's order for the reader's sake only. +# --------------------------------------------------------------------------------- + +[[region]] +name_ru = "Республика Адыгея" +key = "adygea" +code = "01" +iso = "RU-AD" +name_en = "Republic of Adygea" +zone = "Europe/Moscow" +aliases = ["Адыгея", "Республика Адыгея (Адыгея)"] +cities = ["Майкоп"] +dadata_names = ["Респ Адыгея", "Адыгея"] + +[[region]] +name_ru = "Республика Алтай" +key = "altai-republic" +code = "04" +iso = "RU-AL" +name_en = "Altai Republic" +zone = "Asia/Barnaul" +aliases = ["Горный Алтай", "Алтай"] +cities = ["Горно-Алтайск"] +dadata_names = ["Респ Алтай", "Алтай"] + +[[region]] +name_ru = "Республика Башкортостан" +key = "bashkortostan" +code = "02" +iso = "RU-BA" +name_en = "Republic of Bashkortostan" +zone = "Asia/Yekaterinburg" +aliases = ["Башкирия", "Башкортостан"] +cities = ["Уфа", "Стерлитамак", "Салават", "Нефтекамск"] +dadata_names = ["Респ Башкортостан", "Башкортостан"] + +[[region]] +name_ru = "Республика Бурятия" +key = "buryatia" +code = "03" +iso = "RU-BU" +name_en = "Republic of Buryatia" +zone = "Asia/Irkutsk" +aliases = ["Бурятия"] +cities = ["Улан-Удэ"] +dadata_names = ["Респ Бурятия", "Бурятия"] + +[[region]] +name_ru = "Республика Дагестан" +key = "dagestan" +code = "05" +iso = "RU-DA" +name_en = "Republic of Dagestan" +zone = "Europe/Moscow" +aliases = ["Дагестан"] +cities = ["Махачкала", "Дербент", "Хасавюрт", "Каспийск"] +dadata_names = ["Респ Дагестан", "Дагестан"] + +[[region]] +name_ru = "Донецкая Народная Республика" +key = "dnr" +code = "93" # not verified: see the header +name_en = "Donetsk People's Republic" +zone = "Europe/Moscow" +aliases = ["ДНР", "Донецкая республика", "Донбасс"] +cities = ["Донецк", "Макеевка", "Горловка", "Мариуполь"] +dadata_names = ["Донецкая Народная Респ", "Донецкая Народная"] + +[[region]] +name_ru = "Республика Ингушетия" +key = "ingushetia" +code = "06" +iso = "RU-IN" +name_en = "Republic of Ingushetia" +zone = "Europe/Moscow" +aliases = ["Ингушетия"] +cities = ["Магас", "Назрань"] +dadata_names = ["Респ Ингушетия", "Ингушетия"] + +[[region]] +name_ru = "Кабардино-Балкарская Республика" +key = "kbr" +code = "07" +iso = "RU-KB" +name_en = "Kabardino-Balkarian Republic" +zone = "Europe/Moscow" +aliases = ["КБР", "Кабардино-Балкария", "Кабарда"] +cities = ["Нальчик"] +dadata_names = ["Кабардино-Балкарская Респ", "Кабардино-Балкарская"] + +[[region]] +name_ru = "Республика Калмыкия" +key = "kalmykia" +code = "08" +iso = "RU-KL" +name_en = "Republic of Kalmykia" +zone = "Europe/Moscow" +aliases = ["Калмыкия"] +cities = ["Элиста"] +dadata_names = ["Респ Калмыкия", "Калмыкия"] + +[[region]] +name_ru = "Карачаево-Черкесская Республика" +key = "kchr" +code = "09" +iso = "RU-KC" +name_en = "Karachay-Cherkess Republic" +zone = "Europe/Moscow" +aliases = ["КЧР", "Карачаево-Черкесия"] +cities = ["Черкесск"] +dadata_names = ["Карачаево-Черкесская Респ", "Карачаево-Черкесская"] + +[[region]] +name_ru = "Республика Карелия" +key = "karelia" +code = "10" +iso = "RU-KR" +name_en = "Republic of Karelia" +zone = "Europe/Moscow" +aliases = ["Карелия"] +cities = ["Петрозаводск"] +dadata_names = ["Респ Карелия", "Карелия"] + +[[region]] +name_ru = "Республика Коми" +key = "komi" +code = "11" +iso = "RU-KO" +name_en = "Komi Republic" +zone = "Europe/Moscow" +aliases = ["Коми"] +cities = ["Сыктывкар", "Ухта", "Воркута"] +dadata_names = ["Респ Коми", "Коми"] + +[[region]] +name_ru = "Республика Крым" +key = "crimea" +code = "91" +name_en = "Republic of Crimea" +zone = "Europe/Simferopol" +aliases = ["Крым"] +cities = ["Симферополь", "Керчь", "Евпатория", "Ялта"] +dadata_names = ["Респ Крым", "Крым"] + +[[region]] +name_ru = "Луганская Народная Республика" +key = "lnr" +code = "94" # not verified: see the header +name_en = "Luhansk People's Republic" +zone = "Europe/Moscow" +aliases = ["ЛНР", "Луганская республика", "Донбасс"] +cities = ["Луганск", "Алчевск"] +dadata_names = ["Луганская Народная Респ", "Луганская Народная"] + +[[region]] +name_ru = "Республика Марий Эл" +key = "mari-el" +code = "12" +iso = "RU-ME" +name_en = "Mari El Republic" +zone = "Europe/Moscow" +aliases = ["Марий Эл"] +cities = ["Йошкар-Ола"] +dadata_names = ["Респ Марий Эл", "Марий Эл"] + +[[region]] +name_ru = "Республика Мордовия" +key = "mordovia" +code = "13" +iso = "RU-MO" +name_en = "Republic of Mordovia" +zone = "Europe/Moscow" +aliases = ["Мордовия"] +cities = ["Саранск"] +dadata_names = ["Респ Мордовия", "Мордовия"] + +[[region]] +name_ru = "Республика Саха (Якутия)" +key = "yakutia" +code = "14" +iso = "RU-SA" +name_en = "Sakha (Yakutia) Republic" +zone = "Asia/Yakutsk" +aliases = ["Якутия", "Саха"] +cities = ["Якутск", "Нерюнгри"] +dadata_names = ["Респ Саха /Якутия/", "Саха /Якутия/"] + +[[region]] +name_ru = "Республика Северная Осетия — Алания" +key = "north-ossetia" +code = "15" +iso = "RU-SE" +name_en = "Republic of North Ossetia–Alania" +zone = "Europe/Moscow" +aliases = ["РСО", "РСО-Алания", "Северная Осетия", "Осетия", "Алания"] +cities = ["Владикавказ"] +dadata_names = ["Респ Северная Осетия - Алания", "Северная Осетия - Алания"] + +[[region]] +name_ru = "Республика Татарстан" +key = "tatarstan" +code = "16" +iso = "RU-TA" +name_en = "Republic of Tatarstan" +zone = "Europe/Moscow" +aliases = ["Татарстан", "Татария", "Республика Татарстан (Татарстан)"] +cities = ["Казань", "Набережные Челны", "Нижнекамск", "Альметьевск"] +dadata_names = ["Респ Татарстан", "Татарстан"] + +[[region]] +name_ru = "Республика Тыва" +key = "tuva" +code = "17" +iso = "RU-TY" +name_en = "Tuva Republic" +zone = "Asia/Krasnoyarsk" +aliases = ["Тыва", "Тува"] +cities = ["Кызыл"] +dadata_names = ["Респ Тыва", "Тыва"] + +[[region]] +name_ru = "Удмуртская Республика" +key = "udmurtia" +code = "18" +iso = "RU-UD" +name_en = "Udmurt Republic" +zone = "Europe/Samara" +aliases = ["Удмуртия"] +cities = ["Ижевск", "Сарапул", "Глазов", "Воткинск"] +dadata_names = ["Удмуртская Респ", "Удмуртская"] + +[[region]] +name_ru = "Республика Хакасия" +key = "khakassia" +code = "19" +iso = "RU-KK" +name_en = "Republic of Khakassia" +zone = "Asia/Krasnoyarsk" +aliases = ["Хакасия"] +cities = ["Абакан", "Черногорск"] +dadata_names = ["Респ Хакасия", "Хакасия"] + +[[region]] +name_ru = "Чеченская Республика" +key = "chechnya" +code = "20" +iso = "RU-CE" +name_en = "Chechen Republic" +zone = "Europe/Moscow" +aliases = ["Чечня"] +cities = ["Грозный", "Гудермес"] +dadata_names = ["Чеченская Респ", "Чеченская"] + +[[region]] +name_ru = "Чувашская Республика" +key = "chuvashia" +code = "21" +iso = "RU-CU" +name_en = "Chuvash Republic" +zone = "Europe/Moscow" +aliases = ["Чувашия", "Чувашская Республика — Чувашия"] +cities = ["Чебоксары", "Новочебоксарск"] +# The register's own spelling carries the second name after a hyphen. +dadata_names = ["Чувашская Республика - Чувашия", "Чувашская Респ", "Чувашская Республика"] + +[[region]] +name_ru = "Алтайский край" +key = "altai-krai" +code = "22" +iso = "RU-ALT" +name_en = "Altai Krai" +zone = "Asia/Barnaul" +aliases = [] +cities = ["Барнаул", "Бийск", "Рубцовск"] +dadata_names = ["Алтайский край", "Алтайский"] + +[[region]] +name_ru = "Забайкальский край" +key = "zabaikalsky" +code = "75" +iso = "RU-ZAB" +name_en = "Zabaykalsky Krai" +zone = "Asia/Chita" +aliases = ["Забайкалье", "Читинская область"] +cities = ["Чита", "Краснокаменск"] +dadata_names = ["Забайкальский край", "Забайкальский"] + +[[region]] +name_ru = "Камчатский край" +key = "kamchatka" +code = "41" +iso = "RU-KAM" +name_en = "Kamchatka Krai" +zone = "Asia/Kamchatka" +aliases = ["Камчатка"] +cities = ["Петропавловск-Камчатский", "Елизово"] +dadata_names = ["Камчатский край", "Камчатский"] + +[[region]] +name_ru = "Краснодарский край" +key = "krasnodar" +code = "23" +iso = "RU-KDA" +name_en = "Krasnodar Krai" +zone = "Europe/Moscow" +aliases = ["Кубань"] +cities = ["Краснодар", "Сочи", "Новороссийск", "Армавир"] +dadata_names = ["Краснодарский край", "Краснодарский"] + +[[region]] +name_ru = "Красноярский край" +key = "krasnoyarsk" +code = "24" +iso = "RU-KYA" +name_en = "Krasnoyarsk Krai" +zone = "Asia/Krasnoyarsk" +aliases = ["Красноярье"] +cities = ["Красноярск", "Норильск", "Ачинск"] +dadata_names = ["Красноярский край", "Красноярский"] + +[[region]] +name_ru = "Пермский край" +key = "perm" +code = "59" +iso = "RU-PER" +name_en = "Perm Krai" +zone = "Asia/Yekaterinburg" +aliases = ["Прикамье", "Пермская область"] +cities = ["Пермь", "Березники", "Соликамск"] +dadata_names = ["Пермский край", "Пермский"] + +[[region]] +name_ru = "Приморский край" +key = "primorye" +code = "25" +iso = "RU-PRI" +name_en = "Primorsky Krai" +zone = "Asia/Vladivostok" +aliases = ["Приморье"] +cities = ["Владивосток", "Уссурийск", "Находка"] +dadata_names = ["Приморский край", "Приморский"] + +[[region]] +name_ru = "Ставропольский край" +key = "stavropol" +code = "26" +iso = "RU-STA" +name_en = "Stavropol Krai" +zone = "Europe/Moscow" +aliases = ["Ставрополье"] +cities = ["Ставрополь", "Пятигорск", "Кисловодск", "Невинномысск"] +dadata_names = ["Ставропольский край", "Ставропольский"] + +[[region]] +name_ru = "Хабаровский край" +key = "khabarovsk" +code = "27" +iso = "RU-KHA" +name_en = "Khabarovsk Krai" +zone = "Asia/Vladivostok" +aliases = [] +cities = ["Хабаровск", "Комсомольск-на-Амуре"] +dadata_names = ["Хабаровский край", "Хабаровский"] + +[[region]] +name_ru = "Амурская область" +key = "amur" +code = "28" +iso = "RU-AMU" +name_en = "Amur Oblast" +zone = "Asia/Yakutsk" +aliases = ["Приамурье"] +cities = ["Благовещенск", "Белогорск", "Свободный"] +dadata_names = ["Амурская обл", "Амурская"] + +[[region]] +name_ru = "Архангельская область" +key = "arkhangelsk" +code = "29" +iso = "RU-ARK" +name_en = "Arkhangelsk Oblast" +zone = "Europe/Moscow" +aliases = ["Поморье"] +cities = ["Архангельск", "Северодвинск", "Котлас"] +dadata_names = ["Архангельская обл", "Архангельская"] + +[[region]] +name_ru = "Астраханская область" +key = "astrakhan" +code = "30" +iso = "RU-AST" +name_en = "Astrakhan Oblast" +zone = "Europe/Astrakhan" +aliases = [] +cities = ["Астрахань"] +dadata_names = ["Астраханская обл", "Астраханская"] + +[[region]] +name_ru = "Белгородская область" +key = "belgorod" +code = "31" +iso = "RU-BEL" +name_en = "Belgorod Oblast" +zone = "Europe/Moscow" +aliases = ["Белгородчина"] +cities = ["Белгород", "Старый Оскол", "Губкин"] +dadata_names = ["Белгородская обл", "Белгородская"] + +[[region]] +name_ru = "Брянская область" +key = "bryansk" +code = "32" +iso = "RU-BRY" +name_en = "Bryansk Oblast" +zone = "Europe/Moscow" +aliases = ["Брянщина"] +cities = ["Брянск"] +dadata_names = ["Брянская обл", "Брянская"] + +[[region]] +name_ru = "Владимирская область" +key = "vladimir" +code = "33" +iso = "RU-VLA" +name_en = "Vladimir Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Владимир", "Ковров", "Муром"] +dadata_names = ["Владимирская обл", "Владимирская"] + +[[region]] +name_ru = "Волгоградская область" +key = "volgograd" +code = "34" +iso = "RU-VGG" +name_en = "Volgograd Oblast" +zone = "Europe/Volgograd" +aliases = [] +cities = ["Волгоград", "Волжский", "Камышин"] +dadata_names = ["Волгоградская обл", "Волгоградская"] +# Its «Сетевой город» serves http only and refuses datacenter addresses, so the +# allow-list leaves it out (regions.py says why). The catalog still lists it — a +# family there should be told why the app cannot open it, not that it does not exist. +netschool_excluded = "http-only" + +[[region]] +name_ru = "Вологодская область" +key = "vologda" +code = "35" +iso = "RU-VLG" +name_en = "Vologda Oblast" +zone = "Europe/Moscow" +aliases = ["Вологодчина"] +cities = ["Вологда", "Череповец"] +dadata_names = ["Вологодская обл", "Вологодская"] + +[[region]] +name_ru = "Воронежская область" +key = "voronezh" +code = "36" +iso = "RU-VOR" +name_en = "Voronezh Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Воронеж"] +dadata_names = ["Воронежская обл", "Воронежская"] + +[[region]] +name_ru = "Запорожская область" +key = "zaporozhye" +code = "90" # not verified: see the header +name_en = "Zaporozhye Oblast" +zone = "Europe/Moscow" +aliases = ["Запорожье"] +cities = ["Мелитополь", "Бердянск", "Энергодар"] +dadata_names = ["Запорожская обл", "Запорожская"] +# docs/diaries.md: «Госуслуги Моя школа» is offered in front of every regional +# system except here and in Херсонская. +tor = "absent" + +[[region]] +name_ru = "Ивановская область" +key = "ivanovo" +code = "37" +iso = "RU-IVA" +name_en = "Ivanovo Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Иваново", "Кинешма"] +dadata_names = ["Ивановская обл", "Ивановская"] + +[[region]] +name_ru = "Иркутская область" +key = "irkutsk" +code = "38" +iso = "RU-IRK" +name_en = "Irkutsk Oblast" +zone = "Asia/Irkutsk" +aliases = ["Приангарье"] +cities = ["Иркутск", "Братск", "Ангарск"] +dadata_names = ["Иркутская обл", "Иркутская"] + +[[region]] +name_ru = "Калининградская область" +key = "kaliningrad" +code = "39" +iso = "RU-KGD" +name_en = "Kaliningrad Oblast" +zone = "Europe/Kaliningrad" +aliases = [] +cities = ["Калининград", "Советск"] +dadata_names = ["Калининградская обл", "Калининградская"] + +[[region]] +name_ru = "Калужская область" +key = "kaluga" +code = "40" +iso = "RU-KLU" +name_en = "Kaluga Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Калуга", "Обнинск"] +dadata_names = ["Калужская обл", "Калужская"] + +[[region]] +name_ru = "Кемеровская область — Кузбасс" +key = "kemerovo" +code = "42" +iso = "RU-KEM" +name_en = "Kemerovo Oblast — Kuzbass" +zone = "Asia/Novokuznetsk" +aliases = ["Кузбасс", "Кемеровская область"] +cities = ["Кемерово", "Новокузнецк", "Прокопьевск"] +dadata_names = [ + "Кемеровская область - Кузбасс", "Кемеровская обл - Кузбасс", "Кемеровская обл", + "Кемеровская", +] + +[[region]] +name_ru = "Кировская область" +key = "kirov" +code = "43" +iso = "RU-KIR" +name_en = "Kirov Oblast" +zone = "Europe/Kirov" +aliases = ["Вятка"] +cities = ["Киров"] +dadata_names = ["Кировская обл", "Кировская"] + +[[region]] +name_ru = "Костромская область" +key = "kostroma" +code = "44" +iso = "RU-KOS" +name_en = "Kostroma Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Кострома"] +dadata_names = ["Костромская обл", "Костромская"] + +[[region]] +name_ru = "Курганская область" +key = "kurgan" +code = "45" +iso = "RU-KGN" +name_en = "Kurgan Oblast" +zone = "Asia/Yekaterinburg" +aliases = ["Зауралье"] +cities = ["Курган", "Шадринск"] +dadata_names = ["Курганская обл", "Курганская"] + +[[region]] +name_ru = "Курская область" +key = "kursk" +code = "46" +iso = "RU-KRS" +name_en = "Kursk Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Курск", "Железногорск"] +dadata_names = ["Курская обл", "Курская"] + +[[region]] +name_ru = "Ленинградская область" +key = "leningrad" +code = "47" +iso = "RU-LEN" +name_en = "Leningrad Oblast" +zone = "Europe/Moscow" +aliases = ["Ленобласть", "ЛО"] +cities = ["Гатчина", "Всеволожск", "Выборг", "Мурино"] +dadata_names = ["Ленинградская обл", "Ленинградская"] + +[[region]] +name_ru = "Липецкая область" +key = "lipetsk" +code = "48" +iso = "RU-LIP" +name_en = "Lipetsk Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Липецк", "Елец"] +dadata_names = ["Липецкая обл", "Липецкая"] + +[[region]] +name_ru = "Магаданская область" +key = "magadan" +code = "49" +iso = "RU-MAG" +name_en = "Magadan Oblast" +zone = "Asia/Magadan" +aliases = ["Колыма"] +cities = ["Магадан"] +dadata_names = ["Магаданская обл", "Магаданская"] + +[[region]] +name_ru = "Московская область" +key = "moscow-oblast" +code = "50" +iso = "RU-MOS" +name_en = "Moscow Oblast" +zone = "Europe/Moscow" +aliases = ["Подмосковье", "МО"] +cities = ["Балашиха", "Подольск", "Химки", "Мытищи", "Королёв"] +dadata_names = ["Московская обл", "Московская"] + +[[region]] +name_ru = "Мурманская область" +key = "murmansk" +code = "51" +iso = "RU-MUR" +name_en = "Murmansk Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Мурманск", "Апатиты", "Североморск"] +dadata_names = ["Мурманская обл", "Мурманская"] + +[[region]] +name_ru = "Нижегородская область" +key = "nizhny-novgorod" +code = "52" +iso = "RU-NIZ" +name_en = "Nizhny Novgorod Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Нижний Новгород", "Дзержинск", "Арзамас"] +dadata_names = ["Нижегородская обл", "Нижегородская"] + +[[region]] +name_ru = "Новгородская область" +key = "novgorod" +code = "53" +iso = "RU-NGR" +name_en = "Novgorod Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Великий Новгород", "Боровичи"] +dadata_names = ["Новгородская обл", "Новгородская"] + +[[region]] +name_ru = "Новосибирская область" +key = "novosibirsk" +code = "54" +iso = "RU-NVS" +name_en = "Novosibirsk Oblast" +zone = "Asia/Novosibirsk" +aliases = [] +cities = ["Новосибирск", "Бердск"] +dadata_names = ["Новосибирская обл", "Новосибирская"] + +[[region]] +name_ru = "Омская область" +key = "omsk" +code = "55" +iso = "RU-OMS" +name_en = "Omsk Oblast" +zone = "Asia/Omsk" +aliases = [] +cities = ["Омск"] +dadata_names = ["Омская обл", "Омская"] + +[[region]] +name_ru = "Оренбургская область" +key = "orenburg" +code = "56" +iso = "RU-ORE" +name_en = "Orenburg Oblast" +zone = "Asia/Yekaterinburg" +aliases = ["Оренбуржье"] +cities = ["Оренбург", "Орск", "Новотроицк"] +dadata_names = ["Оренбургская обл", "Оренбургская"] + +[[region]] +name_ru = "Орловская область" +key = "oryol" +code = "57" +iso = "RU-ORL" +name_en = "Oryol Oblast" +zone = "Europe/Moscow" +aliases = ["Орловщина"] +cities = ["Орёл", "Ливны"] +dadata_names = ["Орловская обл", "Орловская"] + +[[region]] +name_ru = "Пензенская область" +key = "penza" +code = "58" +iso = "RU-PNZ" +name_en = "Penza Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Пенза", "Кузнецк"] +dadata_names = ["Пензенская обл", "Пензенская"] + +[[region]] +name_ru = "Псковская область" +key = "pskov" +code = "60" +iso = "RU-PSK" +name_en = "Pskov Oblast" +zone = "Europe/Moscow" +aliases = ["Псковщина"] +cities = ["Псков", "Великие Луки"] +dadata_names = ["Псковская обл", "Псковская"] + +[[region]] +name_ru = "Ростовская область" +key = "rostov" +code = "61" +iso = "RU-ROS" +name_en = "Rostov Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Ростов-на-Дону", "Таганрог", "Шахты", "Волгодонск"] +dadata_names = ["Ростовская обл", "Ростовская"] + +[[region]] +name_ru = "Рязанская область" +key = "ryazan" +code = "62" +iso = "RU-RYA" +name_en = "Ryazan Oblast" +zone = "Europe/Moscow" +aliases = ["Рязанщина"] +cities = ["Рязань"] +dadata_names = ["Рязанская обл", "Рязанская"] + +[[region]] +name_ru = "Самарская область" +key = "samara" +code = "63" +iso = "RU-SAM" +name_en = "Samara Oblast" +zone = "Europe/Samara" +aliases = [] +cities = ["Самара", "Тольятти", "Сызрань"] +dadata_names = ["Самарская обл", "Самарская"] + +[[region]] +name_ru = "Саратовская область" +key = "saratov" +code = "64" +iso = "RU-SAR" +name_en = "Saratov Oblast" +zone = "Europe/Saratov" +aliases = [] +cities = ["Саратов", "Энгельс", "Балаково"] +dadata_names = ["Саратовская обл", "Саратовская"] + +[[region]] +name_ru = "Сахалинская область" +key = "sakhalin" +code = "65" +iso = "RU-SAK" +name_en = "Sakhalin Oblast" +zone = "Asia/Sakhalin" +aliases = ["Сахалин"] +cities = ["Южно-Сахалинск", "Корсаков"] +dadata_names = ["Сахалинская обл", "Сахалинская"] + +[[region]] +name_ru = "Свердловская область" +key = "sverdlovsk" +code = "66" +iso = "RU-SVE" +name_en = "Sverdlovsk Oblast" +zone = "Asia/Yekaterinburg" +aliases = ["Средний Урал"] +cities = ["Екатеринбург", "Нижний Тагил", "Каменск-Уральский"] +dadata_names = ["Свердловская обл", "Свердловская"] + +[[region]] +name_ru = "Смоленская область" +key = "smolensk" +code = "67" +iso = "RU-SMO" +name_en = "Smolensk Oblast" +zone = "Europe/Moscow" +aliases = ["Смоленщина"] +cities = ["Смоленск", "Вязьма"] +dadata_names = ["Смоленская обл", "Смоленская"] + +[[region]] +name_ru = "Тамбовская область" +key = "tambov" +code = "68" +iso = "RU-TAM" +name_en = "Tambov Oblast" +zone = "Europe/Moscow" +aliases = ["Тамбовщина"] +cities = ["Тамбов", "Мичуринск"] +dadata_names = ["Тамбовская обл", "Тамбовская"] + +[[region]] +name_ru = "Тверская область" +key = "tver" +code = "69" +iso = "RU-TVE" +name_en = "Tver Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Тверь", "Ржев"] +dadata_names = ["Тверская обл", "Тверская"] + +[[region]] +name_ru = "Томская область" +key = "tomsk" +code = "70" +iso = "RU-TOM" +name_en = "Tomsk Oblast" +zone = "Asia/Tomsk" +aliases = [] +cities = ["Томск", "Северск"] +dadata_names = ["Томская обл", "Томская"] + +[[region]] +name_ru = "Тульская область" +key = "tula" +code = "71" +iso = "RU-TUL" +name_en = "Tula Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Тула", "Новомосковск"] +dadata_names = ["Тульская обл", "Тульская"] + +[[region]] +name_ru = "Тюменская область" +key = "tyumen" +code = "72" +iso = "RU-TYU" +name_en = "Tyumen Oblast" +zone = "Asia/Yekaterinburg" +aliases = [] +cities = ["Тюмень", "Тобольск", "Ишим"] +dadata_names = ["Тюменская обл", "Тюменская"] + +[[region]] +name_ru = "Ульяновская область" +key = "ulyanovsk" +code = "73" +iso = "RU-ULY" +name_en = "Ulyanovsk Oblast" +zone = "Europe/Ulyanovsk" +aliases = [] +cities = ["Ульяновск", "Димитровград"] +dadata_names = ["Ульяновская обл", "Ульяновская"] + +[[region]] +name_ru = "Херсонская область" +key = "kherson" +code = "95" # not verified: see the header +name_en = "Kherson Oblast" +zone = "Europe/Moscow" +aliases = ["Херсонщина"] +cities = ["Геническ", "Новая Каховка", "Скадовск"] +dadata_names = ["Херсонская обл", "Херсонская"] +# docs/diaries.md: «Госуслуги Моя школа» is not offered here. +tor = "absent" + +[[region]] +name_ru = "Челябинская область" +key = "chelyabinsk" +code = "74" +iso = "RU-CHE" +name_en = "Chelyabinsk Oblast" +zone = "Asia/Yekaterinburg" +aliases = ["Южный Урал"] +cities = ["Челябинск", "Магнитогорск", "Златоуст", "Миасс"] +dadata_names = ["Челябинская обл", "Челябинская"] + +[[region]] +name_ru = "Ярославская область" +key = "yaroslavl" +code = "76" +iso = "RU-YAR" +name_en = "Yaroslavl Oblast" +zone = "Europe/Moscow" +aliases = [] +cities = ["Ярославль", "Рыбинск"] +dadata_names = ["Ярославская обл", "Ярославская"] + +[[region]] +name_ru = "Москва" +key = "moscow" +code = "77" +iso = "RU-MOW" +name_en = "Moscow" +zone = "Europe/Moscow" +aliases = ["Мск"] +cities = ["Зеленоград"] +dadata_names = ["г Москва", "Москва"] + +[[region]] +name_ru = "Санкт-Петербург" +key = "saint-petersburg" +code = "78" +iso = "RU-SPE" +name_en = "Saint Petersburg" +zone = "Europe/Moscow" +aliases = ["Питер", "СПб", "Петербург", "Ленинград"] +cities = ["Колпино", "Пушкин", "Петергоф", "Кронштадт"] +dadata_names = ["г Санкт-Петербург", "Санкт-Петербург"] + +[[region]] +name_ru = "Севастополь" +key = "sevastopol" +code = "92" +name_en = "Sevastopol" +zone = "Europe/Simferopol" +aliases = [] +cities = ["Балаклава", "Инкерман"] +dadata_names = ["г Севастополь", "Севастополь"] +# regions.md: not among ТОР's regions, and with the journal suspended «Госуслуги Моя +# школа» has no marks of the city's to show. +tor = "absent" + +[[region]] +name_ru = "Еврейская автономная область" +key = "eao" +code = "79" +iso = "RU-YEV" +name_en = "Jewish Autonomous Oblast" +zone = "Asia/Vladivostok" +aliases = ["ЕАО"] +cities = ["Биробиджан"] +dadata_names = ["Еврейская Аобл", "Еврейская"] + +[[region]] +name_ru = "Ненецкий автономный округ" +key = "nao" +code = "83" +iso = "RU-NEN" +name_en = "Nenets Autonomous Okrug" +zone = "Europe/Moscow" +aliases = ["НАО"] +cities = ["Нарьян-Мар"] +dadata_names = ["Ненецкий АО", "Ненецкий"] + +[[region]] +name_ru = "Ханты-Мансийский автономный округ — Югра" +key = "khmao" +code = "86" +iso = "RU-KHM" +name_en = "Khanty-Mansi Autonomous Okrug — Yugra" +zone = "Asia/Yekaterinburg" +aliases = ["ХМАО", "Югра", "ХМАО — Югра"] +cities = ["Ханты-Мансийск", "Сургут", "Нижневартовск", "Нефтеюганск"] +dadata_names = ["Ханты-Мансийский Автономный округ - Югра", "Ханты-Мансийский АО - Югра"] + +[[region]] +name_ru = "Чукотский автономный округ" +key = "chukotka" +code = "87" +iso = "RU-CHU" +name_en = "Chukotka Autonomous Okrug" +zone = "Asia/Anadyr" +aliases = ["Чукотка", "ЧАО"] +cities = ["Анадырь", "Билибино"] +dadata_names = ["Чукотский АО", "Чукотский"] + +[[region]] +name_ru = "Ямало-Ненецкий автономный округ" +key = "yanao" +code = "89" +iso = "RU-YAN" +name_en = "Yamalo-Nenets Autonomous Okrug" +zone = "Asia/Yekaterinburg" +aliases = ["ЯНАО", "Ямал"] +cities = ["Салехард", "Новый Уренгой", "Ноябрьск"] +dadata_names = ["Ямало-Ненецкий АО", "Ямало-Ненецкий"] diff --git a/server/tests/test_region_catalog.py b/server/tests/test_region_catalog.py new file mode 100644 index 00000000..95a9251e --- /dev/null +++ b/server/tests/test_region_catalog.py @@ -0,0 +1,658 @@ +"""The region catalog: generated from the survey, committed, and read by both halves. + +`app/catalog/data/regions.json` is what the phone's onboarding lists, searches and +recommends from, and what the server's school directory places a school with. It +is generated by `scripts/region_catalog.py` from `docs/diaries/regions.md`, the +netschool allow-list and a hand overlay, and every decision in it — which system +can be signed into, which is handed off to Госуслуги, which is put first — is +made there and read everywhere else. + +Three kinds of test live here. The drift test, which makes a survey edit without +the regenerated catalog a red build. The contract tests, which hold the catalog to +the things other code stores or trusts: region keys that sit in database columns, +origins a sign-in may go to, zones, DaData's spellings. And the parser tests, +which pin the traps the survey's markdown sets — a full stop inside «Since», a +label that is itself «Е-услуги. Образование», a port, an IDN and its punycode twin, +one page that means two platforms. +""" + +from __future__ import annotations + +import fnmatch +import functools +import json +import re +import tomllib +from collections import Counter +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo + +import pytest + +from app import catalog +from app.providers.diary import registry +from app.providers.netschool import regions as allow_list +from app.providers.petersburg.client import BASE_URL as PETERSBURG_ORIGIN +from scripts import region_catalog as generator + +ROOT = Path(__file__).resolve().parents[2] +SERVER = ROOT / "server" + + +@functools.cache +def _overlay() -> dict[str, Any]: + return tomllib.loads(generator.OVERLAY.read_text(encoding="utf-8")) + + +@functools.cache +def _built_text() -> str: + return generator.render(generator.build_from_repository()) + + +@functools.cache +def _committed_text() -> str: + return catalog.DATA.read_text(encoding="utf-8") + + +def _committed() -> dict[str, Any]: + # A fresh parse each time: a test that edits what it is handed must not edit + # what the next test reads. + return json.loads(_committed_text()) + + +def _regions() -> dict[str, dict[str, Any]]: + return {region["key"]: region for region in _committed()["regions"]} + + +def _systems() -> list[tuple[dict[str, Any], dict[str, Any]]]: + return [(region, system) for region in _committed()["regions"] for system in region["systems"]] + + +def _headings() -> list[str]: + text = generator.REGIONS_MD.read_text(encoding="utf-8") + return re.findall(r"^## (.+?)\s*$", text, flags=re.MULTILINE) + + +# -------------------------------------------------------------------------- +# The committed file +# -------------------------------------------------------------------------- + + +def test_the_committed_catalog_is_what_the_generator_writes(): + """A survey edit that is not followed by `python -m scripts.region_catalog` fails here. + + The phone bundles the committed file, so a regions.md fix that never reached + the JSON is a fix no family sees — and the same holds for regions.py: an + origin moved in the allow-list and not in the catalog leaves the phone + signing in somewhere the server refuses to follow. + """ + assert _committed_text() == _built_text(), ( + "app/catalog/data/regions.json is stale: run `python -m scripts.region_catalog` " + "from server/ and commit the result" + ) + + +def test_the_check_flag_fails_on_a_catalog_that_drifted(tmp_path, monkeypatch, capsys): + stale = tmp_path / "regions.json" + stale.write_text(_built_text().replace('"leningrad"', '"lenobl"', 1), encoding="utf-8") + monkeypatch.setattr(generator, "OUTPUT", stale) + monkeypatch.setattr(generator, "ROOT", tmp_path) + + assert generator.main(["--check"]) == 1 + assert "is not what the survey implies" in capsys.readouterr().err + + stale.write_text(_built_text(), encoding="utf-8") + assert generator.main(["--check"]) == 0 + + +def test_eighty_nine_regions_in_the_survey_order(): + regions = _committed()["regions"] + + assert len(regions) == 89 + assert [region["name_ru"] for region in regions] == _headings() + assert [region["order"] for region in regions] == list(range(1, 90)) + # Art. 65 order, which is not alphabetical: Russian collation would file + # every «Республика …» under Р, and the survey's first region is a republic. + assert regions[0]["key"] == "adygea" and regions[-1]["key"] == "yanao" + assert sum(region["mandatory"] for region in regions) == 13 + + +def test_keys_are_unique_slugs_and_codes_unique_two_digits(): + regions = _committed()["regions"] + keys = [region["key"] for region in regions] + codes = [region["code"] for region in regions] + + assert len(set(keys)) == 89 + assert len(set(codes)) == 89 + for region in regions: + # The width of classes.diary_region and diary_sessions.region, and the + # pattern the registration body checks a region against. + assert re.fullmatch(r"[a-z0-9-]{2,32}", region["key"]), region["key"] + assert re.fullmatch(r"\d\d", region["code"]), region["code"] + assert {key: code for key, code in zip(keys, codes, strict=True)}["crimea"] == "91" + assert {key: code for key, code in zip(keys, codes, strict=True)}["sevastopol"] == "92" + + +def test_the_nineteen_netschool_keys_are_the_allow_lists_own(): + """The keys the database stores, byte for byte — and everything else the phone trusts. + + `classes.diary_region`, `diary_sessions.region` and the sealed credential all + hold these strings. A catalog key that differed by a letter would leave every + class bound to that region looking unbound on the phone, and an origin that + differed would be a second allow-list. + """ + regions = _regions() + rows = allow_list.listed(password_only=False) + assert len(rows) == 19 + + for row in rows: + region = regions[row.key] + assert region["name_ru"] == row.title + (linked,) = [system for system in region["systems"] if system["netschool"]] + assert linked["netschool"] == { + "region": row.key, + "origin": row.origin, + "password": row.password, + "verified": row.verified, + "zone": row.zone, + } + + +def test_every_allow_listed_region_appears_exactly_once(): + linked = Counter( + system["netschool"]["region"] for _, system in _systems() if system["netschool"] + ) + + assert linked == Counter(row.key for row in allow_list.listed(password_only=False)) + for region, system in _systems(): + if system["netschool"]: + assert system["netschool"]["region"] == region["key"] + assert system["platform"] == "netschool" + + +def test_volgograd_is_listed_but_unreachable(): + """In the survey, out of the allow-list, and told apart from «not supported». + + Its «Сетевой город» serves http only and refuses datacenter addresses. The + family should read that, not that the app has never heard of their diary. + """ + volgograd = _regions()["volgograd"] + (netschool,) = [s for s in volgograd["systems"] if s["platform"] == "netschool"] + + assert allow_list.get("volgograd") is None + assert netschool["role"] == "primary" + assert netschool["action"] == "none" + assert netschool["netschool"] is None + assert netschool["excluded"] == "http-only" + assert netschool["web_url"] is None + assert volgograd["recommended"]["reason"] == "unreachable" + assert volgograd["recommended"]["platform"] == "netschool" + assert [ + region["key"] for region in _committed()["regions"] + if region["recommended"]["reason"] == "unreachable" + ] == ["volgograd"] + + +def test_every_region_has_an_english_name(): + """Names in the JSON escape `ResourceTranslationTest`, so this is their twin rule.""" + cyrillic = re.compile(r"[Ѐ-ӿ]") + for region in _committed()["regions"]: + assert region["name_en"].strip(), region["key"] + assert not cyrillic.search(region["name_en"]), region["name_en"] + assert region["name_en"] != region["name_ru"] + for key, platform in _committed()["platforms"].items(): + assert platform["name_ru"].strip() and platform["name_en"].strip(), key + assert not cyrillic.search(platform["name_en"]), platform["name_en"] + + +def test_dadata_names_resolve_to_exactly_one_region(): + seen: dict[str, str] = {} + for region in _committed()["regions"]: + assert region["dadata_names"], region["key"] + for name in region["dadata_names"]: + normalised = catalog.normalise_name(name) + assert seen.setdefault(normalised, region["key"]) == region["key"], name + placed = catalog.by_dadata_name(name) + assert placed is not None and placed.key == region["key"], name + + +def test_every_system_names_a_known_platform_and_provider_key(): + platforms = _committed()["platforms"] + for key, platform in platforms.items(): + assert platform["provider"] in (*registry.KEYS, None), key + assert platform["provider"] in (key, None), key + if platform["page"] is not None: + assert (generator.PAGES / f"{platform['page']}.md").is_file(), key + for region, system in _systems(): + assert system["platform"] in platforms, (region["key"], system["platform"]) + assert system["role"] in ("primary", "secondary", "legacy", "migrating_to", "unclear") + assert system["confidence"] in ("low", "medium", "high") + assert {system["platform"] for _, system in _systems()} == set(platforms) + + +def test_primary_counts_match_the_platform_table(): + """Counting primaries by page reproduces docs/diaries.md's platforms table. + + ТОР and the federal portal share `myschool-federal.md`; the table's row + counts ТОР, and the portal is never anybody's primary. + """ + platforms = _committed()["platforms"] + now: Counter[str] = Counter() + moving: Counter[str] = Counter() + for _, system in _systems(): + page = platforms[system["platform"]]["page"] + if page is None: + continue + if system["role"] == "primary": + now[page] += 1 + elif system["role"] == "migrating_to": + moving[page] += 1 + + table = generator.platform_table(generator.DIARIES_MD.read_text(encoding="utf-8")) + assert {page: counts for page, counts in table.items() if any(counts)} == { + page: (now[page], moving[page]) for page in set(now) | set(moving) + } + # The two primaries the table cannot count, because neither has a page. + unpaged = [ + system["platform"] for _, system in _systems() + if system["role"] == "primary" and platforms[system["platform"]]["page"] is None + ] + assert sorted(unpaged) == ["it-school-penza", "paper"] + + +def test_only_petersburg_and_password_netschool_are_signable(): + """The one place the catalog could open a door the decision record keeps shut. + + Sign-in here means the app's own form, sending a password straight to the + provider: Petersburg, and the sixteen «Сетевой город» regions whose + allow-list row takes a password. ТОР and the three Госуслуги-only regions + are hand-offs to a page in the browser, and nothing about signing in to + Госуслуги inside the app may enter the catalog in any form. + """ + signable = { + (region["key"], system["platform"]) + for region, system in _systems() + if system["action"] == "signin" + } + password_regions = {row.key for row in allow_list.listed()} + assert len(password_regions) == 16 + assert signable == {("saint-petersburg", "petersburg")} | { + (key, "netschool") for key in password_regions + } + + for region, system in _systems(): + assert system["action"] in ("signin", "handoff", "none") + if system["role"] in ("legacy", "unclear"): + assert system["action"] == "none", (region["key"], system["platform"]) + if system["action"] == "handoff": + if system["platform"] == "tor-myschool": + assert system["handoff_url"] == "https://www.gosuslugi.ru/school" + else: + row = allow_list.get(region["key"]) + assert system["platform"] == "netschool" and row is not None + assert not row.password + assert system["handoff_url"] == row.origin + else: + assert system["handoff_url"] is None + if system["action"] == "signin" and system["platform"] == "petersburg": + assert system["web_url"] == PETERSBURG_ORIGIN + + handed_to_origin = { + region["key"] for region, system in _systems() + if system["action"] == "handoff" and system["platform"] == "netschool" + } + assert handed_to_origin == {"altai-krai", "primorye", "tula"} + + for text in (_committed_text(), generator.OVERLAY.read_text(encoding="utf-8")): + lowered = text.casefold() + for forbidden in ("signin_surface", "webview", "на странице дневника"): + assert forbidden not in lowered, forbidden + + +def test_every_address_the_phone_may_open_is_https(): + """`web_url` and `handoff_url` go to `ACTION_VIEW` as they stand. + + Волгоград's diary serves only http and so has no `web_url` at all, and a + wildcard host such as `*.eljur.ru` is never turned into an address. + """ + for region, system in _systems(): + for field in ("web_url", "handoff_url"): + url = system[field] + if url is None: + continue + assert url.startswith("https://"), (region["key"], field, url) + assert "*" not in url and url.isascii(), (region["key"], field, url) + + +def test_tor_is_never_recommended_where_the_survey_says_it_is_absent(): + regions = _committed()["regions"] + absent = {region["key"] for region in regions if region["tor"] == "absent"} + + assert absent == {"zaporozhye", "kherson", "sevastopol"} + assert {region["tor"] for region in regions} <= set(generator.TOR_STATES) + for region in regions: + if region["tor"] == "absent": + assert region["recommended"]["platform"] != "tor-myschool" + assert all(system["platform"] != "tor-myschool" for system in region["systems"]) + + +def test_zones_are_real_and_match_the_allow_list(): + regions = _regions() + for region in regions.values(): + ZoneInfo(region["zone"]) + for row in allow_list.listed(password_only=False): + assert regions[row.key]["zone"] == row.zone + + +def _ignored_by(pattern: str, relative: str) -> bool: + """One `.vercelignore` line against one path, by gitignore's rules as Vercel reads them.""" + directory_only = pattern.endswith("/") + core = pattern.strip("/") + parts = relative.split("/") + if "/" in core: + # Anchored at the root: it names a directory by its path (or a file, if + # it has no trailing slash). + prefixes = ["/".join(parts[: i + 1]) for i in range(len(parts) - 1)] + if not directory_only: + prefixes.append(relative) + return any(fnmatch.fnmatch(prefix, core) for prefix in prefixes) + # Unanchored: it names a component at any depth, a directory's only if it ends in «/». + candidates = parts[:-1] if directory_only else parts + return any(fnmatch.fnmatch(part, core) for part in candidates) + + +def test_the_catalog_sits_where_vercel_ships_it(): + """Under `server/app/`, matched by nothing in `.vercelignore`, and packaged. + + `server/scripts/` is ignored on purpose — the generator never runs in a + request — so the catalog must not live beside it, and the loader must not + read the overlay. Whether Vercel then uploads a `.json` next to the code is + inferred rather than seen: the first preview deploy's directory call is what + settles it. + """ + data = catalog.DATA.relative_to(ROOT).as_posix() + loader = Path(catalog.__file__).resolve().relative_to(ROOT).as_posix() + assert data.startswith("server/app/") + + patterns = [ + line.strip() + for line in (ROOT / ".vercelignore").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.startswith("#") + ] + assert _ignored_by("server/scripts/", "server/scripts/region_catalog.toml") + for path in (data, loader): + assert not [pattern for pattern in patterns if _ignored_by(pattern, path)], path + + pyproject = tomllib.loads((SERVER / "pyproject.toml").read_text(encoding="utf-8")) + assert "catalog/data/*.json" in pyproject["tool"]["setuptools"]["package-data"]["app"] + + +# -------------------------------------------------------------------------- +# What is decided +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("key", "platform", "reason", "modifiers"), + [ + ("saint-petersburg", "petersburg", "primary", ["unverified"]), + ("leningrad", "netschool", "primary", ["unverified"]), + ("altai-krai", "netschool", "primary", ["esia_only"]), + ("altai-republic", "tor-myschool", "tor_primary", []), + ("tatarstan", "tor-myschool", "front_end", []), + ("orenburg", "tor-myschool", "moving_to", []), + ("volgograd", "netschool", "unreachable", []), + ("adygea", "dnevnik-ru", "unsupported", []), + ("moscow", "mesh-moscow", "unsupported", []), + ("sevastopol", "paper", "no_diary", []), + ], +) +def test_one_system_is_recommended_and_the_reason_is_a_code(key, platform, reason, modifiers): + region = _regions()[key] + recommended = region["recommended"] + chosen = region["systems"][recommended["system"]] + + assert recommended["platform"] == chosen["platform"] == platform + assert recommended["confidence"] == chosen["confidence"] + assert recommended["reason"] == reason + assert recommended["modifiers"] == modifiers + + +def test_every_reason_is_one_the_phone_has_a_sentence_for(): + for region in _committed()["regions"]: + assert region["recommended"]["reason"] in generator.REASONS + assert set(region["recommended"]["modifiers"]) <= set(generator.MODIFIERS) + # A front end below «medium» is listed, and never put first. + if region["recommended"]["reason"] == "front_end": + chosen = region["systems"][region["recommended"]["system"]] + assert chosen["front_end"] and chosen["confidence"] != "low", region["key"] + + +def test_the_school_year_follows_the_survey_month(): + assert _committed()["survey"] == {"month": "2026-09", "school_year": "2026/27"} + + +# -------------------------------------------------------------------------- +# Reading the survey +# -------------------------------------------------------------------------- + +#: A survey block carrying every trap at once, in regions.md's own grammar. +_BLOCK = "\n".join( + [ + "# Preamble that is not a region", + "", + "## Республика Бурятия", + "", + "*Mandatory region.*", + "", + "- **in use now: [«Сетевой город»](netschool.md)** — ГИС «Электронное образование»" + " (ИРТех). Hosts: `deti.obr03.ru`, `sad06.ru:82`. Since: 2016/17 (decree of" + " 01.12.2016 № 549). Confidence: high.", + " deti.obr03.ru answered 403. Hosts: `evidence.example` is prose, not a field.", + " - https://egov-buryatia.ru/obr/index.php — «quoted»", + "- **alongside: Е-услуги. Образование** — Е-услуги. Образование (admissions)." + " Hosts: `es.zabedu.ru`. Since: 2020. Confidence: medium.", + "- **previous: [БАРС](bars.md)** — Барс. Hosts: `школа.образование33.рф`," + " `xn--80atdl2c.xn--33-6kcadhwnl3cfdx.xn--p1ai`, `login.dnevnik.ru/login/esia/irkutsk`," + " `*.eljur.ru`. Confidence: low.", + "- **alongside: [«Госуслуги Моя школа»](myschool-federal.md) as a front end** — app." + " Hosts: `gosuslugi.ru/school`. Since: by 2025/26. Confidence: medium.", + "- **alongside: [ФГИС «Моя школа»](myschool-federal.md)** — portal." + " Hosts: `myschool.edu.ru`. Confidence: medium.", + "- **previous: [БАРС](bars.md)** — the same platform again, earlier." + " Hosts: `old.example.ru`. Confidence: high.", + "- **Notes.** Hosts: `not.a.system` — notes are not systems.", + "- **Checked:** confirmed.", + "", + ] +) + + +def test_a_full_stop_inside_since_or_a_label_does_not_move_the_hosts(): + """Anchored on «Hosts:», «Since:» and «Confidence:», never on the first full stop.""" + (region,) = generator.parse_survey(_BLOCK) + + assert region.name == "Республика Бурятия" + assert region.mandatory + primary, admissions = region.systems[0], region.systems[1] + assert [host.display() for host in primary.hosts] == ["deti.obr03.ru", "sad06.ru:82"] + assert primary.confidence == "high" and primary.page == "netschool" + assert admissions.label == "Е-услуги. Образование" and admissions.page is None + assert [host.display() for host in admissions.hosts] == ["es.zabedu.ru"] + # Only the first line of a bullet is read: evidence and «Notes.» are prose. + everything = [host.display() for system in region.systems for host in system.hosts] + assert "evidence.example" not in everything and "not.a.system" not in everything + + +def test_a_host_keeps_its_port_and_path_and_an_idn_meets_its_punycode_twin(): + (region,) = generator.parse_survey(_BLOCK) + bars = region.systems[2] + + assert [host.display() for host in bars.hosts] == [ + "школа.образование33.рф", + "login.dnevnik.ru/login/esia/irkutsk", + "*.eljur.ru", + ] + idn, path, pattern = bars.hosts + assert idn.url() == "https://xn--80atdl2c.xn--33-6kcadhwnl3cfdx.xn--p1ai" + assert path.url() == "https://login.dnevnik.ru/login/esia/irkutsk" + assert pattern.pattern and pattern.url() is None + + sakhalin = generator.parse_host("netcity.admsakhalin.ru:11111") + assert (sakhalin.ascii, sakhalin.port, sakhalin.path) == ("netcity.admsakhalin.ru", 11111, "") + + +def test_duplicates_in_the_survey_are_real_and_kept(): + (region,) = generator.parse_survey(_BLOCK) + assert [system.role for system in region.systems if system.page == "bars"] == [ + "legacy", + "legacy", + ] + + regions = _regions() + petersburg = [s["role"] for s in regions["saint-petersburg"]["systems"] + if s["platform"] == "petersburg"] + assert petersburg == ["primary", "legacy"] + bars = [s["role"] for s in regions["vologda"]["systems"] if s["platform"] == "bars"] + assert bars == ["secondary", "legacy"] + + +def test_the_federal_page_is_split_by_host_not_by_label(): + """`myschool-federal.md` is ТОР on `gosuslugi.ru/school` and the portal on `myschool.edu.ru`.""" + platforms = generator._platforms(_overlay()) + (region,) = generator.parse_survey(_BLOCK) + front_end, portal = region.systems[3], region.systems[4] + + assert generator._platform_of(front_end, platforms, {}, "x").key == "tor-myschool" + assert front_end.front_end + assert generator._platform_of(portal, platforms, {}, "x").key == "fgis-myschool" + + yanao = [(s["platform"], s["front_end"]) for s in _regions()["yanao"]["systems"]] + assert ("tor-myschool", True) in yanao and ("fgis-myschool", False) in yanao + assert _committed()["platforms"]["fgis-myschool"]["kind"] == "portal" + + +def test_a_label_with_no_page_must_be_in_the_overlay_word_for_word(): + platforms = generator._platforms(_overlay()) + (region,) = generator.parse_survey(_BLOCK.replace("Е-услуги. Образование**", "Е-услуги**")) + + with pytest.raises(generator.CatalogError, match="not in \\[unlinked\\]"): + generator._platform_of(region.systems[1], platforms, dict(_overlay()["unlinked"]), "x") + + +def test_a_bullet_that_starts_like_a_system_but_does_not_parse_stops_the_build(): + front_end_line = next(line for line in _BLOCK.splitlines() if "as a front end" in line) + broken = _BLOCK.replace(front_end_line, front_end_line.replace("medium.", "sure.")) + with pytest.raises(generator.CatalogError, match="Confidence"): + generator.parse_survey(broken) + + no_dash = _BLOCK.replace("(bars.md)** — Барс.", "(bars.md)** Барс.") + with pytest.raises(generator.CatalogError, match="cannot read"): + generator.parse_survey(no_dash) + + +def test_the_summary_table_is_held_to_the_survey(): + regions_md = generator.REGIONS_MD.read_text(encoding="utf-8") + table_md = generator.DIARIES_MD.read_text(encoding="utf-8") + survey = generator.parse_survey(regions_md) + generator.cross_check(survey, table_md) + + # Ленинградская's primary is «Сетевой город»; a table that said otherwise + # would be one of the two documents lying about a region's diary. + row = next(line for line in table_md.splitlines() if line.startswith("| Ленинградская область")) + wrong = table_md.replace(row, row.replace("diaries/netschool.md", "diaries/eljur.md", 1)) + with pytest.raises(generator.CatalogError, match="Ленинградская"): + generator.cross_check(survey, wrong) + + unbolded = table_md.replace("| **Москва** |", "| Москва |") + with pytest.raises(generator.CatalogError, match="bold"): + generator.cross_check(survey, unbolded) + + +def test_the_overlay_cannot_rename_an_allow_listed_region(): + """A renamed key would orphan every class and session stored under the old one.""" + overlay = tomllib.loads(generator.OVERLAY.read_text(encoding="utf-8")) + for entry in overlay["region"]: + if entry["key"] == "leningrad": + entry["key"] = "lenobl" + + with pytest.raises(generator.CatalogError, match="leningrad"): + generator.build( + generator.REGIONS_MD.read_text(encoding="utf-8"), + generator.DIARIES_MD.read_text(encoding="utf-8"), + overlay, + ) + + +def test_a_dadata_spelling_two_regions_share_is_refused(): + overlay = tomllib.loads(generator.OVERLAY.read_text(encoding="utf-8")) + for entry in overlay["region"]: + if entry["key"] == "altai-krai": + entry["dadata_names"].append("Респ. Алтай") + + with pytest.raises(generator.CatalogError, match="already places"): + generator.build( + generator.REGIONS_MD.read_text(encoding="utf-8"), + generator.DIARIES_MD.read_text(encoding="utf-8"), + overlay, + ) + + +# -------------------------------------------------------------------------- +# The loader and the lexicon +# -------------------------------------------------------------------------- + + +def test_the_loader_places_a_school_by_code_or_by_dadatas_spelling(): + assert catalog.get("leningrad").name_en == "Leningrad Oblast" + assert catalog.get("nowhere") is None and catalog.get(None) is None + assert catalog.by_code("47").key == "leningrad" + assert catalog.by_code("78").key == "saint-petersburg" + # A thirteen-digit KLADR id is the caller's to cut, and a guess is worse than a miss. + assert catalog.by_code("4700000000000") is None + assert catalog.by_code("4") is None and catalog.by_code(None) is None + assert catalog.by_dadata_name("Респ Татарстан").key == "tatarstan" + assert catalog.by_dadata_name("г. Москва").key == "moscow" + assert catalog.by_dadata_name("Кемеровская область — Кузбасс").key == "kemerovo" + assert catalog.by_dadata_name("РЕСП САХА (ЯКУТИЯ)").key == "yakutia" + # «Алтай» is the republic and «Алтайский» the krai: exact, never partial. + assert catalog.by_dadata_name("Алтай").key == "altai-republic" + assert catalog.by_dadata_name("Алтайский край").key == "altai-krai" + assert catalog.by_dadata_name("Алт") is None + assert len(catalog.regions()) == 89 + + +def test_normalise_name_drops_case_yo_and_punctuation(): + assert catalog.normalise_name(" Респ Саха /Якутия/ ") == "респ саха якутия" + assert catalog.normalise_name("Королёв") == "королев" + assert catalog.normalise_name("Ханты-Мансийский АО — Югра") == "ханты мансийский ао югра" + + +def test_the_directorys_school_words_are_the_phones(): + assert catalog.school_words() == tuple(_committed()["search"]["school_words"]) + assert {"школа", "сош", "гимназия", "лицей", "№"} <= set(catalog.school_words()) + + +def test_the_search_lexicon_swaps_layouts_key_for_key(): + search = _committed()["search"] + latin, cyrillic = search["latin_layout"], search["cyrillic_layout"] + swap = dict(zip(latin, cyrillic, strict=True)) + + assert "".join(swap[char] for char in "cfvfhf") == "самара" + assert search["fold"]["ё"] == "е" and search["fold"]["—"] == " " + assert {"республика", "область", "край", "округ", "г"} <= set(search["stop_words"]) + + def transliterate(text: str) -> str: + pairs = search["translit"] + out, i = [], 0 + while i < len(text): + source, target = next(pair for pair in pairs if text.startswith(pair[0], i)) + out.append(target) + i += len(source) + return "".join(out) + + # Best effort: a prefix of the name is all the search needs to land. + assert transliterate("moskva") == "москва" + assert transliterate("chelyabinsk") == "челябинск" + assert "казань".startswith(transliterate("kazan")) From 2bfdeba4810c7502e842c2c74191be9634706806 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 14:49:15 +0000 Subject: [PATCH 10/30] Write the terms of use and the privacy policy the first screen will link to MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner asked for a line under the first screen's button saying that continuing accepts the terms and the privacy policy, linked to documents in the build's own repository. The documents did not exist. `docs/legal/` now holds both, Russian first (`*.ru.md`, the source, like `values/`) with English translations, in the Markdown subset the app's guide reader already parses, plus `legal.json` with the edition and the date it takes effect. The app will bundle them as a fallback and open them from the first screen and from «О приложении». They describe what this code does and nothing more, and say plainly what a reader would otherwise assume: - the password goes only to the diary from the app, but still crosses the server on the bot's sign-in page and from older apps; - the operator holds the key the diary sessions are sealed with, so can read the diary; hosting is Frankfurt, not Russia; - leaving a class deletes nothing on the server (the device row goes 180 days after it was last seen); corrections, the audit log and tasks have no expiry; - the «Сетевой город» keep-alive runs for up to 30 days after the last real use, and only foreground use counts; - an `http://` server address carries the diary session in the clear; the app warns and does not refuse. Each passage that describes the upstream deployment sits under a `FORK:` comment naming the fields a fork must rewrite (operator, contact, hosting, country, …). Not legal advice: whether naming a GitHub account as operator satisfies 152-ФЗ, cross-border transfer, the age line and parental consent are for the owner and a lawyer, and the text claims no compliance with any of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- docs/legal/legal.json | 14 +++ docs/legal/privacy.en.md | 233 +++++++++++++++++++++++++++++++++++ docs/legal/privacy.ru.md | 254 +++++++++++++++++++++++++++++++++++++++ docs/legal/terms.en.md | 130 ++++++++++++++++++++ docs/legal/terms.ru.md | 147 ++++++++++++++++++++++ 5 files changed, 778 insertions(+) create mode 100644 docs/legal/legal.json create mode 100644 docs/legal/privacy.en.md create mode 100644 docs/legal/privacy.ru.md create mode 100644 docs/legal/terms.en.md create mode 100644 docs/legal/terms.ru.md diff --git a/docs/legal/legal.json b/docs/legal/legal.json new file mode 100644 index 00000000..f1b206fe --- /dev/null +++ b/docs/legal/legal.json @@ -0,0 +1,14 @@ +{ + "edition": 1, + "effective": "2026-09-25", + "files": { + "terms": { + "ru": "terms.ru.md", + "en": "terms.en.md" + }, + "privacy": { + "ru": "privacy.ru.md", + "en": "privacy.en.md" + } + } +} diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md new file mode 100644 index 00000000..6c6123c0 --- /dev/null +++ b/docs/legal/privacy.en.md @@ -0,0 +1,233 @@ + + +# Privacy policy of Lessons + +## Who is responsible for the data + + +This text describes what the app Lessons («Дневник» in Russian), its server and its Telegram bot do with data. What it says about the app holds for any build of the app from this code, what it says about the server holds for a server run from this code unmodified, and the operator and the place the data is kept are named below for one server only — the one this operator runs. + + + +- **The operator** is the maintainer of the repository [lumenpearson/lessons](https://github.com/lumenpearson/lessons) on GitHub. +- **Where the server runs**: on Vercel, region `fra1` (Frankfurt am Main, Germany); the database is on Neon, region `aws-eu-central-1` (also Frankfurt). +- **How to get in touch**: see the “Contact” section at the end. + +You type the server's address into the app yourself. If it leads to a server somebody else started, whoever started it is responsible for the data on that server and in its bot, and their own policy should describe it. + +## What is kept on the phone + + +- For each class you have joined: an access key, and the names of the class and the school. +- A copy of the class timetable, events and homework, teachers' names included, so that the app and the widget work offline. +- If you have signed in to a diary: the diary access key the server issued, your login, which diary, region and school it is and which pupil you chose; and, in a separate database, a copy of the diary — lessons, homework, marks, pupils' and teachers' names. +- The server's address, the app's settings and, if you signed in to GitHub from the app, the GitHub key and your account name there. +- Crash reports, only if you turned them on: up to five files with the phone's model, the Android and app versions, a description of the error and the app's latest log lines. + +The keys, the login and the settings sit in the app's settings files **unencrypted**. The databases and the settings files are excluded from Google backup and from transfer to a new phone. Crash reports are not excluded: if you turned them on, they may end up in the phone's backup (this has not been checked on a device). + +The phone never stores the diary password. The session the diary hands out after sign-in is held only in memory, never written down, and forgotten as soon as the phone has handed it to the server or the sign-in is abandoned. + +## What the server receives and keeps + + +When a phone joins a class, the server keeps: + +- the phone's access key — only as a SHA-256 hash, from which the key cannot be recovered; +- the phone's name — its manufacturer and model; +- when the phone last made a request to the server; +- the Telegram account, if the phone has been linked to one. + +When you sign in to a diary, the server keeps: + +- the diary session — **encrypted** with the operator's key; for Setevoy Gorod, the region, the school's number and name and the school year's details are sealed inside with it; +- your login — as you typed it, in plain text; in Petersburg Education that is an email address; +- which diary and region it is, when the session was opened, when it was last used, when the server last kept it open and when the diary stopped accepting it; +- the diary access key issued to the phone — only as a SHA-256 hash. + +A session opened in the app is linked to neither a Telegram account nor a class, and the bot does not see it. A session opened from the bot is linked to your Telegram account and to the class, and remembers which pupil you chose. + +Your corrections to the diary: what you corrected, the new value and what the diary said when you made the correction. They are tied to your login and the pupil's number, not to the session, so they remain after you sign out of the diary. + +If the operator has turned school search on, you can find your region by your school's name while choosing a diary: the server passes the text you typed to the DaData service. The server does not write that text to its database, but it is part of the request's address, and so it stays in the hosting's request log. + +To limit guessing of codes and passwords, the server counts failed attempts to join a class and to sign in to a diary, and every school search too. To do so it writes down a SHA-256 hash of your IP address, taken without a secret key. Such a hash can be reversed by trying every address, so this is not anonymisation: it is personal data. + +If you use the bot, the server keeps: + +- your Telegram account number, your username and name as Telegram gives them, and your role in the class; +- your phone number — only if you shared your contact yourself and an invitation was found for it; a number with no invitation is not stored; +- the invitations by phone number that admins set up, with their labels; +- your tasks, your “done” ticks, your reminder times and your requests for rights, with their text; +- the class's change log — who changed what; its lines may contain names and phone numbers; +- what you started typing in the bot and did not finish, and the class you chose if you are in several. + +The class's own data — the timetable, substitutions, homework, events, teachers' names and who added each homework — is kept on the server for as long as the class exists. + +## What the server does not keep + + +**The server does not keep your diary password.** The app this text comes with sends the password only to the diary's system, straight from the phone, and the server never receives it. + +The password does pass through the server in two cases: when you sign in to a diary on the page the bot opens — the browser sends the password to the server, and the server passes it to the diary once — and when an older version of the app signs in, one that does not have this text yet. In both cases the server writes the password down nowhere. + +**The diary's contents** — marks, homework, timetable, the list of pupils — are read by the server when you ask and passed on without being kept. The exception is what an entry said when you corrected it. + +**There are no analytics, no advertising identifiers and no automatic crash reporting**, in the app or on the server. + +## How signing in to a diary works + + +1. **The form** — You type your login and password into the app's own form, which says which diary and which address the password will go to. +2. **The diary** — The app sends them over HTTPS straight to the diary system's server — only to addresses on a list built into the app — and gets a session back. +3. **The server** — The app hands that session and your login to the server, plus the region and school for Setevoy Gorod. The server checks the session with a request of its own to the diary (four for Setevoy Gorod), encrypts it and gives the app a diary access key of its own. +4. **After that** — The phone forgets the diary's session and reads the diary through the server, and the server talks to the diary from its own address. + +If the diary does not accept the session from the server's address, the server does not keep it, and tells the app that the problem is not the password but where the session came from. + +The app does not sign in to Gosuslugi or to My School: it opens the system's page in your browser, and nothing from Gosuslugi reaches either the app or the server. + +## Who can read your diary + + +- **The diary's system**, after sign-in, sees the server's address using your session, not your phone's. +- **The operator** holds the key the sessions are encrypted with, and so can technically open your diary. The encryption protects against whoever gets the database without the key, not against the operator. +- **Telegram** keeps in the chat history whatever the bot sent you from the diary — marks, homework, timetable. +- **Whoever holds your phone:** the diary access key sits on it unencrypted, and the app opens the diary without a password until you sign out. + +## Keeping the session open + + +A Setevoy Gorod session closes by itself after a quarter of an hour to an hour without requests, and the server has no password to sign in again with. So while the server's clock is running — an outside service that calls the server every few minutes, if the operator has set one up — the server contacts Setevoy Gorod with each open session, no more than once every four minutes, so that it does not close. + +This goes on for up to 30 days after you last signed in to the diary or read it through the server — in the app or in the bot; then the server deletes the session. The requests that keep the session open do not count as use and do not extend that period. + +Use means the diary being read by the app while it is open on screen, or by the bot. The widget and background sync do not read the diary and do not extend the session. + +The server does not keep Petersburg Education sessions open: they last as long as that system allows, and that period is documented nowhere. + +## How long things are kept + + +- The IP address hash from a failed attempt or a school search: no more than an hour. +- A diary session: 30 days after it was last used; a session the diary stopped accepting: one day after that was found out. +- The record of a phone in a class: 180 days after its last request; neither leaving the class in the app nor an admin disconnecting the phone deletes it sooner. +- The link for signing in to a diary from the bot: 15 minutes; a personal code for connecting a phone: one day after its 15 minutes have run out. +- What you started typing in the bot: 2 days without a change. + +**With no time limit** — until somebody deletes them or deletes the class — the server keeps the change log, tasks and “done” ticks, reminder times, requests for rights, invitations by phone number, your membership of the class in the bot, and the class's data. Diary corrections and the class chosen in the bot are not deleted even with the class; corrections are deleted by the “Reset corrections” button. + +These periods are kept by the server's clock. If the operator has not set that clock up, the records in this list stay past their periods, and Setevoy Gorod sessions are not kept open. + + + +This server's database (Neon) keeps a history of changes for a further 6 hours, so something deleted can be restored within that time. The hosting (Vercel) keeps request logs with the IP address, the request's address and the time; some addresses contain a secret — the link to a class's calendar, for example, or the link for signing in to a diary from the bot. How long the hosting keeps those logs is set by its own rules. + +## Third parties + + + + +- **The hosting and the database** — Vercel and Neon, for this operator: the server runs on their machines, and everything it keeps is stored there. +- **Telegram** — everything you do in the bot and everything the bot sends you goes through it. +- **The diary systems** — Petersburg Education and Setevoy Gorod's regional servers. The phone sends them your login and password when you sign in, and sends Setevoy Gorod your school's name when you search for it; the server sends them your requests to the diary. +- **DaData** — if the operator has turned school search on: the server sends it the school name you typed, but not your IP address. +- **GitHub** — once a day at start-up the app checks there whether a new version is out (on by default, can be turned off in settings), and fetches the guide from there when you open it; GitHub sees the phone's address and the app's version when it does. A bug report or a translation fix goes there publicly — only if you send it yourself. +- **Google** — the phone's backup, but only what is not excluded from it (see “What is kept on the phone”). +- **Gosuslugi and the diary systems' websites** that the app opens in your browser: their own rules apply there. + +## Where the data is kept + + + + +This operator's server and its database are in Germany, in Frankfurt am Main. Everything the server keeps is kept outside Russia, and data from a phone in Russia leaves the country. + +If you have connected to a different server, whoever started it decides where its data is kept. + +## Children and parents + + +A diary is information about a child: their marks, homework and timetable. If a pupil under 18 uses Lessons, it should be with the knowledge and consent of their parent or another legal guardian. + +The app does not ask anybody's age and checks nothing about who signs in. A parent's diary account may show several children, and everybody who signs in to it sees all of them. + +A parent who wants the server to delete their child's data can write to the operator — the “Contact” section says how. + +## Security + + +- The access keys of phones and diaries and the one-time codes — for signing in from the bot and for connecting a phone — are kept by the server only as SHA-256 hashes. The class code is kept as it is: the bot shows it to admins. +- The server encrypts the diary session (Fernet: AES-128-CBC with HMAC) with a key the operator sets. Without that key the diary does not run on the server at all, rather than keeping sessions unencrypted. +- The app itself encrypts nothing on the phone: there, the data is protected only by whatever protects the phone itself. + +**HTTPS depends on the address you typed.** The app also accepts `http://` addresses, for servers on a school's local network. At such an address everything between the phone and the server travels in the clear: the class and diary access keys, the phone's name, the timetable, and the diary session the phone hands to the server when you sign in. Anybody on the same network can intercept it and open your diary. The app warns you about this before you sign in to a diary, but does not forbid it. + +In the app, whatever the server's address, the diary password goes only to the diary's system, and only over HTTPS. + +## What you can do + + +- Sign out of the diary in the app or in the bot — the server deletes the session. If the phone is offline at that moment, the session is deleted by itself 30 days after it was last used, and until then the server keeps a Setevoy Gorod session open. +- Reset your corrections to the diary. +- Leave a class — this erases the copy on the phone, but not the server's record of the phone. +- Turn off the automatic update check. Crash reports stay off until you turn them on yourself. + +You cannot remove yourself from the bot or delete your data from the server on your own: there are no commands for that, so write to the operator. The operator cannot delete your Telegram chat history or the data in the diary's system — that is done there. + +## Changes + + +The edition number and the date it applies from are in the file `legal.json` next to this text. The app carries a copy of the edition it was built with; the current one opens at its link when the build knows that link. + +When what the code keeps or sends, or how long it keeps it, changes, this text changes too, with a new edition number. By continuing to use Lessons after that, you accept the new edition; when you accepted it is recorded nowhere. + +This text is written in Russian, and the English is its translation. Where they differ, the Russian prevails. + +## Contact + + + + +The operator of this server is the owner of the GitHub account `lumenpearson`, who maintains the repository [lumenpearson/lessons](https://github.com/lumenpearson/lessons). + +Write questions about your data, and requests to delete it, on [the repository's Issues page](https://github.com/lumenpearson/lessons/issues). Anybody can read it, so do not write logins, passwords, phone numbers or children's names there — only what you are asking for. If your build has a “Send by email” button (Settings → About → Report a problem), you can also write by email. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md new file mode 100644 index 00000000..1abe6ffe --- /dev/null +++ b/docs/legal/privacy.ru.md @@ -0,0 +1,254 @@ + + +# Политика конфиденциальности «Дневника» + +## Кто отвечает за данные + + +Этот текст описывает, что делают с данными приложение «Дневник», его сервер и Telegram-бот. Сказанное о приложении верно для любой его сборки из этого кода, сказанное о сервере — для сервера, запущенного из этого кода без изменений, а оператор и место хранения названы ниже только для одного сервера — того, который запускает этот оператор. + + + +- **Оператор** — сопровождающий репозитория [lumenpearson/lessons](https://github.com/lumenpearson/lessons) на GitHub. +- **Где работает сервер** — хостинг Vercel, регион `fra1` (Франкфурт-на-Майне, Германия); база данных — Neon, регион `aws-eu-central-1` (тоже Франкфурт). +- **Как связаться** — в разделе «Контакты» в конце. + +Адрес сервера вы вводите в приложении сами. Если он ведёт на сервер, который запустил кто-то другой, за данные на том сервере и в его боте отвечает тот, кто его запустил, и описывать их должна его политика. + +## Что хранится на телефоне + + +- Для каждого класса, к которому вы подключились, — ключ доступа, название класса и школы. +- Копия расписания класса, событий и заданий, включая имена учителей, — чтобы приложение и виджет работали без сети. +- Если вы вошли в дневник, — выданный сервером ключ доступа к дневнику, ваш логин, какой это дневник, регион и школа и какого ученика вы выбрали; а в отдельной базе — копия дневника: уроки, задания, оценки, имена учеников и учителей. +- Адрес сервера, настройки приложения и, если вы входили в GitHub из приложения, ключ GitHub и имя вашей учётной записи там. +- Отчёты о сбоях — только если вы их включили: до пяти файлов с моделью телефона, версиями Android и приложения, описанием ошибки и последними записями о работе приложения. + +Ключи, логин и настройки лежат в файлах настроек приложения **без шифрования**. Базы данных и файлы настроек исключены из резервной копии Google и из переноса на новый телефон. Отчёты о сбоях не исключены: если вы их включили, они могут попасть в резервную копию телефона (на устройстве это не проверялось). + +Пароль от дневника телефон не сохраняет нигде. Сессию, которую дневник выдаёт после входа, телефон держит только в памяти, не записывая, и забывает, как только передал её серверу или вход отменён. + +## Что получает и хранит сервер + + +Когда телефон подключается к классу, сервер сохраняет: + +- ключ доступа телефона — только в виде хеша SHA-256, по которому ключ не восстановить; +- название телефона — производитель и модель; +- когда телефон последний раз обращался к серверу; +- учётную запись Telegram, если телефон к ней привязали. + +Когда вы входите в дневник, сервер сохраняет: + +- сессию дневника — **зашифрованной** ключом оператора; у «Сетевого города» вместе с ней внутри шифра лежат регион, номер и название школы и сведения об учебном годе; +- ваш логин — так, как вы его ввели, открытым текстом; в «Петербургском образовании» это адрес электронной почты; +- какой это дневник и регион, когда сессию открыли, когда ею последний раз пользовались, когда сервер её поддерживал и когда дневник перестал её принимать; +- ключ доступа к дневнику, выданный телефону, — только в виде хеша SHA-256. + +Сессия, открытая в приложении, не связана ни с учётной записью Telegram, ни с классом, и бот её не видит. Сессия, открытая из бота, связана с вашей учётной записью Telegram и с классом, и в ней запоминается выбранный ученик. + +Ваши правки дневника: что вы поправили, новое значение и то, что было в дневнике в момент правки. Они привязаны к вашему логину и номеру ученика, а не к сессии, поэтому остаются после выхода из дневника. + +Если оператор включил поиск школ, при выборе дневника можно найти свой регион по названию школы: сервер передаёт набранный текст сервису DaData. В базу сервер этот текст не записывает, но он входит в адрес запроса и поэтому остаётся в журнале запросов хостинга. + +Чтобы ограничить подбор кодов и паролей, сервер считает неудачные попытки подключиться к классу и войти в дневник, а также каждый поиск школы. Для этого он записывает хеш SHA-256 вашего IP-адреса без секретного ключа. Такой хеш можно обратить перебором всех адресов, поэтому это не обезличивание: это персональные данные. + +Если вы пользуетесь ботом, сервер хранит: + +- номер вашей учётной записи Telegram, имя пользователя и имя, как они указаны в Telegram, и вашу роль в классе; +- номер телефона — только если вы сами поделились контактом и для него нашлось приглашение; номер без приглашения не сохраняется; +- приглашения по номеру телефона, которые оформили администраторы, с подписями к ним; +- ваши задачи, отметки «сделал», время напоминаний и запросы прав вместе с их текстом; +- журнал изменений класса — кто и что поменял; в его строках бывают имена и номера телефонов; +- незаконченный ввод в боте и класс, который вы выбрали, если их у вас несколько. + +Данные самого класса — расписание, замены, задания, события, имена учителей и то, кто добавил задание, — хранятся на сервере, пока существует класс. + +## Чего сервер не хранит + + +**Пароль от дневника сервер не хранит.** Приложение, в котором есть этот текст, отправляет пароль только в систему дневника, прямо с телефона, и сервер его не получает. + +Через сервер пароль всё же проходит в двух случаях: когда вы входите в дневник на странице, которую открывает бот, — браузер отправляет пароль серверу, а сервер один раз передаёт его дневнику, — и когда входят старые версии приложения, в которых этого текста ещё нет. В обоих случаях сервер нигде пароль не записывает. + +**Содержимое дневника** — оценки, задания, расписание, список учеников — сервер читает по вашему запросу и передаёт дальше, не сохраняя. Исключение — то, что было в записи, которую вы поправили. + +**Аналитики, рекламных идентификаторов и автоматической отправки отчётов о сбоях** нет ни в приложении, ни на сервере. + +## Как устроен вход в дневник + + +1. **Форма** — Вы вводите логин и пароль в форме приложения; в ней написано, в какой дневник и на какой адрес уйдёт пароль. +2. **Дневник** — Приложение отправляет их по HTTPS прямо на сервер системы дневника — только на адреса из списка, встроенного в приложение, — и получает в ответ сессию. +3. **Сервер** — Приложение передаёт серверу эту сессию и ваш логин, а для «Сетевого города» — ещё регион и школу. Сервер проверяет сессию своим обращением к дневнику (к «Сетевому городу» — четырьмя), шифрует её и выдаёт приложению свой ключ доступа к дневнику. +4. **Дальше** — Телефон забывает сессию дневника и читает дневник через сервер, а сервер обращается к дневнику со своего адреса. + +Если дневник не принял сессию с адреса сервера, сервер её не сохраняет и отвечает приложению, что дело не в пароле, а в том, откуда пришла сессия. + +В Госуслуги и в «Мою школу» приложение не входит: оно открывает страницу системы в вашем браузере, и ничего из Госуслуг не попадает ни в приложение, ни на сервер. + +## Кто может прочитать ваш дневник + + +- **Система дневника** после входа видит, что вашей сессией пользуется адрес сервера, а не вашего телефона. +- **Оператор** держит ключ, которым зашифрованы сессии, и поэтому технически может открыть ваш дневник. Шифрование защищает от того, к кому попадёт база данных без ключа, а не от оператора. +- **Telegram** хранит в истории чата то, что бот прислал вам из дневника, — оценки, задания, расписание. +- **Тот, у кого в руках ваш телефон:** ключ доступа к дневнику лежит на нём без шифрования, и приложение открывает дневник без пароля, пока вы из него не вышли. + +## Поддержание сеанса + + +Сессия «Сетевого города» сама закрывается после четверти часа или часа без обращений, а пароля, чтобы войти снова, у сервера нет. Поэтому, пока идут часы сервера — внешний сервис, который вызывает сервер каждые несколько минут, если оператор его настроил, — сервер обращается к «Сетевому городу» с каждой открытой сессией не чаще раза в четыре минуты, чтобы она не закрылась. + +Так продолжается до 30 дней с тех пор, как вы в последний раз входили в дневник или читали его через сервер — в приложении или в боте; потом сервер удаляет сессию. Сами обращения для поддержания сеанса пользованием не считаются и этот срок не продлевают. + +Пользованием считается чтение дневника приложением, открытым на экране, или ботом. Виджет и фоновая синхронизация дневник не читают и сессию не продлевают. + +Сессии «Петербургского образования» сервер не поддерживает: они живут столько, сколько позволяет сама система, и этот срок нигде не описан. + +## Сколько хранится + + +- Хеш IP-адреса от неудачной попытки или поиска школы — не дольше часа. +- Сессия дневника — 30 дней после последнего пользования; сессия, которую дневник перестал принимать, — сутки после того, как это выяснилось. +- Запись о телефоне в классе — 180 дней после последнего обращения; ни выход из класса в приложении, ни отключение телефона администратором не удаляют её раньше. +- Ссылка для входа в дневник из бота — 15 минут; личный код для подключения телефона — сутки после того, как истекли его 15 минут. +- Незаконченный ввод в боте — 2 дня без изменений. + +**Без срока** — пока их не удалят или пока не удалят класс — хранятся журнал изменений, задачи и отметки «сделал», время напоминаний, запросы прав, приглашения по номеру телефона, ваше участие в классе в боте и данные класса. Правки дневника и класс, выбранный в боте, не удаляются и вместе с классом; правки удаляет кнопка «Сбросить правки». + +Эти сроки выдерживают часы сервера. Если оператор их не настроил, записи из этого списка остаются и после срока, а сессии «Сетевого города» не поддерживаются. + + + +База данных этого сервера (Neon) хранит историю изменений ещё 6 часов, так что удалённое можно восстановить в течение этого времени. Хостинг (Vercel) ведёт журналы запросов с IP-адресом, адресом запроса и временем; в некоторых адресах есть секрет — например, ссылка на календарь класса или ссылка для входа в дневник из бота. Сколько хостинг хранит эти журналы, определяют его правила. + +## Третьи стороны + + + + +- **Хостинг и база данных** — у этого оператора Vercel и Neon: на их серверах работает сервер и лежит всё, что он хранит. +- **Telegram** — через него проходит всё, что вы делаете в боте и что бот вам присылает. +- **Системы дневников** — «Петербургское образование» и региональные серверы «Сетевого города». Телефон отправляет им логин и пароль при входе, а «Сетевому городу» — и название школы, когда вы её ищете; сервер отправляет им ваши запросы к дневнику. +- **DaData** — если оператор включил поиск школ: сервер отправляет туда набранное название школы, но не ваш IP-адрес. +- **GitHub** — приложение раз в сутки при запуске проверяет там, нет ли новой версии (включено по умолчанию, выключается в настройках), и загружает оттуда руководство, когда вы его открываете; GitHub при этом видит адрес телефона и версию приложения. Отчёт об ошибке и исправление перевода попадают туда публично — только если вы сами их отправили. +- **Google** — резервная копия телефона, но лишь то, что из неё не исключено (см. «Что хранится на телефоне»). +- **Госуслуги и сайты систем дневников**, которые приложение открывает в вашем браузере: там действуют их собственные правила. + +## Где хранятся данные + + + + +Сервер этого оператора и его база данных находятся в Германии, во Франкфурте-на-Майне. Всё, что хранит сервер, хранится не в России, и данные с телефона в России уходят за её пределы. + +Если вы подключились к другому серверу, где хранятся данные, решает тот, кто его запустил. + +## Дети и родители + + +Дневник — это сведения о ребёнке: его оценки, задания и расписание. Если «Дневником» пользуется ученик младше 18 лет, это должно происходить с ведома и согласия его родителя или другого законного представителя. + +Приложение не спрашивает возраст и ничего не проверяет о том, кто входит. Родительская учётная запись дневника может показывать нескольких детей, и всех их видит каждый, кто в неё вошёл. + +Родитель, который хочет, чтобы сервер удалил данные его ребёнка, может написать оператору — способ указан в разделе «Контакты». + +## Защита + + +- Ключи доступа телефона и дневника и одноразовые коды — для входа из бота и для подключения телефона — сервер хранит только в виде хеша SHA-256. Код класса хранится как есть: бот показывает его администраторам. +- Сессию дневника сервер шифрует (Fernet: AES-128-CBC с HMAC) ключом, который задаёт оператор. Без ключа дневник на сервере не работает вовсе, а не хранит сессии открыто. +- Приложение само ничего не шифрует на телефоне: там данные защищены лишь тем, чем защищён сам телефон. + +**HTTPS зависит от адреса, который вы ввели.** Приложение принимает и адреса `http://` — ради серверов в локальной сети школы. По такому адресу всё, что идёт между телефоном и сервером, передаётся открытым текстом: ключи доступа к классу и к дневнику, название телефона, расписание и сессия дневника, которую телефон передаёт серверу при входе. Любой в той же сети может её перехватить и открыть ваш дневник. Приложение предупреждает об этом перед входом в дневник, но не запрещает. + +В приложении пароль от дневника при любом адресе сервера уходит только в систему дневника и только по HTTPS. + +## Что вы можете сделать + + +- Выйти из дневника в приложении или в боте — сервер удалит сессию. Если телефон в этот момент не в сети, сессия удалится сама через 30 дней после последнего пользования, а сессию «Сетевого города» сервер до тех пор продолжит поддерживать. +- Сбросить свои правки дневника. +- Выйти из класса — это сотрёт копию на телефоне, но не запись о телефоне на сервере. +- Выключить автоматическую проверку обновлений. Отчёты о сбоях выключены, пока вы сами их не включите. + +Удалить себя из бота или свои данные с сервера самостоятельно нельзя: таких команд нет, для этого напишите оператору. Историю чата в Telegram и данные в системе дневника оператор удалить не может — это делается там. + +## Изменения + + +Номер редакции и дата, с которой она действует, записаны в файле `legal.json` рядом с этим текстом. В приложении есть копия той редакции, с которой его собрали; действующая открывается по ссылке, если сборка эту ссылку знает. + +Если меняется то, что код хранит, передаёт или как долго держит, меняется и этот текст — с новым номером редакции. Продолжая пользоваться «Дневником» после этого, вы принимаете новую редакцию; нигде не записывается, когда вы её приняли. + +Этот текст написан по-русски, английский — его перевод. Если они расходятся, действует русский. + +## Контакты + + + + +Оператор этого сервера — владелец учётной записи `lumenpearson` на GitHub, который сопровождает репозиторий [lumenpearson/lessons](https://github.com/lumenpearson/lessons). + +Вопросы о ваших данных и просьбы их удалить пишите на [странице Issues репозитория](https://github.com/lumenpearson/lessons/issues). Она открыта всем, поэтому не пишите там логинов, паролей, телефонов и имён детей — только суть просьбы. Если в вашей сборке есть кнопка «Отправить письмом» («Настройки → О приложении → Сообщить об ошибке»), можно написать и письмом. diff --git a/docs/legal/terms.en.md b/docs/legal/terms.en.md new file mode 100644 index 00000000..619e6daf --- /dev/null +++ b/docs/legal/terms.en.md @@ -0,0 +1,130 @@ + + +# Terms of use of Lessons + +## What this document covers + + +These terms apply to one program in three parts: the Android app Lessons («Дневник» in Russian), the server it works with, and that server's Telegram bot. The source code of all three is open: [github.com/lumenpearson/lessons](https://github.com/lumenpearson/lessons). + + + +- **The operator** is the maintainer of that repository (`lumenpearson` on GitHub): the one who keeps the repository the app is built from and runs the server this text was written for. +- **What you accept** is these terms and the privacy policy that sits next to them. Both open from the app: Settings → About. + +The app does not choose its server: you type the server's address into the app. If that is a server somebody else started — your school, for example — then it and its bot are run by whoever started it, and their rules apply, not these. + +## Who may use it + + +Pupils, their parents and other legal guardians, teachers, and whoever keeps a class's timetable may use the app and the bot. + +If you are a pupil under 18, use Lessons with the knowledge and consent of a parent or another legal guardian. The diary holds information about you, and part of what you do in the app and in the bot is kept on the operator's server; the privacy policy says exactly what. + +The app does not ask your age and does not check who signs in to a diary, so this condition rests on you and your parents. + +## What the app does + + +- It shows the class timetable that people with rights in that class keep in the Telegram bot, once you have entered the class code or a personal code from the bot. +- It shows your electronic diary — lessons, homework, marks — if you have signed in to it. The server reads the diary from the diary's system and passes it on to the app. +- It lets you correct what came from the diary: the homework text, the room, the teacher, the lesson's topic. A correction is kept on the server next to the diary and **is never sent to the diary's system** — the school register does not change because of it. Marks and attendance cannot be corrected. + +## This is not the official record + + +The timetable in the app is a copy a person typed into the bot. It may have been changed after the app last fetched it: before a test or a substitution, check against what the school said. + +The app shows the diary as the diary's system handed it over — possibly late, or misread. What the system's own website shows is what is right. + +Lessons is not affiliated with Petersburg Education («Петербургское образование»), Setevoy Gorod. Obrazovanie («Сетевой город. Образование»), Gosuslugi or My School («Моя школа»), and does not act on their behalf. Those names belong to their owners. + +## Signing in to a diary + + +Sign in only to your own account, or to one you have been allowed to use — a parent's, for example. + +The app can sign in only to Petersburg Education and to Setevoy Gorod in the regions where it accepts a login and password. Which regions those are can be seen in [the server's source code](https://github.com/lumenpearson/lessons/blob/HEAD/server/app/providers/netschool/regions.py). + +If your region's diary opens only through Gosuslugi, the app does not sign in to it: it opens that system's website in your browser and receives nothing back. The app never signs in to Gosuslugi. + +When you use a diary you remain bound by its system's own rules: these terms do not replace them. + +## What not to do + + +- Do not sign in to somebody else's diary without the permission of the person it belongs to. +- Do not pass on a class code or a personal code that was given to you. +- Do not try to guess codes, overload the server or get around its limits. + +> The app does not lock the diary behind a password of its own: whoever holds your unlocked phone can open your diary in it. + +## The bot and class admins + + +A class is run in the Telegram bot. Its admins see the names and Telegram usernames of the class's members and the names of the connected phones (manufacturer and model), can disconnect any of those phones, and read the change log: who changed what. + +The operator does not check what a class's admins and editors type into the bot: the timetable, substitutions, homework, events, teachers' names. + +## Availability + + +The operator does not promise that the server, the bot or the diary in the app will always be available. A diary's system may stop accepting requests from the server's address at any time, and then the diary will not open in the app. + +As of this edition, signing in to a diary and reading one have never been tried against a real diary — neither Petersburg Education nor Setevoy Gorod. The first real sign-in may not work. + +Features of the app, the server and the bot may change, and some may go away. + +## No warranty + + +The program is distributed under [the MIT licence](https://github.com/lumenpearson/lessons/blob/HEAD/LICENSE) “as is”, without warranty of any kind: nobody promises that it fits your purpose or that it works without errors. + +The operator is liable for the consequences of using Lessons only to the extent that the law does not allow that liability to be excluded. + +## How to stop using it + + +- **Sign out of the diary** — in the app or in the bot. The server deletes the session and, for Setevoy Gorod, also tells the diary you have signed out; your corrections to the diary stay on the server until you reset them. +- **Leave a class** in the app — this erases only what is kept on the phone. The server deletes its record of the phone by itself 180 days after the phone's last request; an admin can disconnect the phone sooner, but even then the record is kept until that date. +- **Uninstall the app** — this erases everything it keeps on the phone; on the server, data is kept for the periods the privacy policy gives. + +To have the server delete what it keeps about you and does not delete by itself, write to the operator — the “Contact” section says how. + +## Changes + + +This text has an edition number and a date from which it applies; both are in the file `legal.json` next to it. The app carries a copy of the edition it was built with, and opens the current one at its link when the build knows that link. + +By continuing to use the app, the server or the bot after the text has changed, you accept the new edition. + +Neither the phone nor the server records what you accepted or when: using Lessons is what counts as accepting. The app says so on its first screen, under the button; the bot does not show a link to these terms yet. + +This text is written in Russian, and the English is its translation. Where they differ, the Russian prevails. + +## Contact + + + + +The operator of this server is the owner of the GitHub account `lumenpearson`, who maintains the repository [lumenpearson/lessons](https://github.com/lumenpearson/lessons). + +You can write to the operator on [the repository's Issues page](https://github.com/lumenpearson/lessons/issues). Anybody can read it, so do not write logins, passwords, phone numbers or children's names there — only what your question is about. If your build has a “Send by email” button (Settings → About → Report a problem), you can also write by email. diff --git a/docs/legal/terms.ru.md b/docs/legal/terms.ru.md new file mode 100644 index 00000000..e8ef477a --- /dev/null +++ b/docs/legal/terms.ru.md @@ -0,0 +1,147 @@ + + +# Условия использования «Дневника» + +## О чём этот документ + + +Эти условия относятся к одной программе из трёх частей: к Android-приложению «Дневник», к серверу, с которым оно работает, и к Telegram-боту этого сервера. Исходный код всех трёх открыт: [github.com/lumenpearson/lessons](https://github.com/lumenpearson/lessons). + + + +- **Оператор** — сопровождающий этого репозитория (на GitHub — `lumenpearson`). Он ведёт репозиторий, из которого собирается приложение, и запускает сервер, для которого написан этот текст. +- **Что вы принимаете** — эти условия и политику конфиденциальности, которая лежит рядом с ними. Обе открываются из приложения: «Настройки → О приложении». + +Приложение не выбирает сервер само: его адрес вы вводите в приложении. Если это сервер, который запустил кто-то другой, — например, ваша школа, — им и его ботом распоряжается тот, кто его запустил, и действуют его правила, а не эти. + +## Кто может пользоваться + + +Приложением и ботом могут пользоваться ученики, их родители и другие законные представители, а также учителя и те, кто ведёт расписание класса. + +Если вы ученик и вам ещё нет 18 лет, пользуйтесь «Дневником» с ведома и согласия родителя или другого законного представителя. В дневнике — сведения о вас, и часть того, что вы делаете в приложении и в боте, хранится на сервере оператора; что именно — сказано в политике конфиденциальности. + +Приложение не спрашивает возраст и не проверяет, кто входит в дневник, поэтому это условие держится на вас и на ваших родителях. + +## Что делает приложение + + +- Показывает расписание класса, которое в Telegram-боте ведут люди с правами в этом классе, — после того как вы ввели код класса или личный код из бота. +- Показывает ваш электронный дневник — уроки, задания, оценки, — если вы в него вошли. Дневник читает сервер у системы дневника и передаёт приложению. +- Даёт поправить то, что пришло из дневника: текст задания, кабинет, учителя, тему урока. Правка хранится на сервере рядом с дневником и **в систему дневника не отправляется** — школьный журнал от неё не меняется. Оценки и посещаемость поправить нельзя. + +## Это не официальный журнал + + +Расписание в приложении — копия, которую набрал человек в боте. Его могли изменить позже, чем приложение успело его забрать: перед контрольной или заменой сверяйтесь с тем, что сказали в школе. + +Дневник приложение показывает таким, каким его отдала система дневника, — возможно, с опозданием или прочитанным неверно. Верно то, что показывает сайт самой системы. + +«Дневник» не связан с «Петербургским образованием», «Сетевым городом. Образование», Госуслугами и «Моей школой» и не выступает от их имени. Эти названия принадлежат их владельцам. + +## Вход в дневник + + +Входите только в свою учётную запись или в ту, которой вам разрешили пользоваться, — например, в учётную запись родителя. + +Из приложения можно войти только в «Петербургское образование» и в «Сетевой город. Образование» в тех регионах, где он принимает логин и пароль. Какие это регионы, видно в [исходном коде сервера](https://github.com/lumenpearson/lessons/blob/HEAD/server/app/providers/netschool/regions.py). + +Если дневник вашего региона открывается только через Госуслуги, приложение в него не входит: оно открывает сайт этой системы в вашем браузере и ничего оттуда не получает. В Госуслуги приложение не входит никогда. + +Пользуясь дневником, вы остаётесь связаны правилами его системы: эти условия их не заменяют. + +## Чего не делать + + +- Не входите в чужой дневник без разрешения того, чей он. +- Не передавайте другим код класса или личный код, который выдали вам. +- Не пытайтесь подобрать коды, перегрузить сервер или обойти его ограничения. + +> Приложение не запирает дневник отдельным паролем: кто держит в руках ваш разблокированный телефон, тот может открыть в нём ваш дневник. + +## Бот и администраторы класса + + +Класс ведут в Telegram-боте. Его администраторы видят имена и имена пользователей Telegram участников класса и названия подключённых телефонов (производитель и модель), могут отключить любой из этих телефонов и читают журнал изменений: кто и что поменял. + +Оператор не проверяет то, что вводят в бот администраторы и редакторы класса: расписание, замены, задания, события, имена учителей. + +## Доступность + + +Оператор не обещает, что сервер, бот и дневник в приложении будут доступны всегда. Система дневника может в любой момент перестать принимать запросы с адреса сервера — тогда дневник в приложении не откроется. + +На дату этой редакции вход в дневник и его чтение ни разу не проверялись на настоящем дневнике — ни в «Петербургском образовании», ни в «Сетевом городе». Первый настоящий вход может не получиться. + +Возможности приложения, сервера и бота могут меняться, а некоторые — исчезнуть. + +## Без гарантий + + +Программа распространяется по [лицензии MIT](https://github.com/lumenpearson/lessons/blob/HEAD/LICENSE) «как есть», без каких-либо гарантий: никто не обещает, что она подойдёт для вашей цели и будет работать без ошибок. + +Оператор отвечает за последствия использования «Дневника» лишь в той мере, в какой закон не позволяет это исключить. + +## Как прекратить пользоваться + + +- **Выйти из дневника** — в приложении или в боте. Сервер удалит сессию, а «Сетевому городу» ещё и сообщит о выходе; ваши правки дневника останутся на сервере, пока вы их не сбросите. +- **Выйти из класса** в приложении — это сотрёт только то, что хранится на телефоне. Запись о телефоне сервер удаляет сам через 180 дней после его последнего обращения; администратор может отключить телефон раньше, но запись и тогда хранится до этого срока. +- **Удалить приложение** — это сотрёт всё, что оно хранит на телефоне; на сервере данные хранятся в сроки, указанные в политике конфиденциальности. + +Чтобы сервер удалил то, что он хранит о вас и не удаляет сам, напишите оператору — как, сказано в разделе «Контакты». + +## Изменения + + +У этого текста есть номер редакции и дата, с которой он действует: они записаны в файле `legal.json` рядом с ним. Приложение носит в себе копию той редакции, с которой его собрали, а действующую открывает по ссылке, если сборка эту ссылку знает. + +Продолжая пользоваться приложением, сервером или ботом после того, как текст изменился, вы принимаете новую редакцию. + +Ни телефон, ни сервер не записывают, что и когда вы приняли: согласием считается само пользование «Дневником». В приложении об этом сказано на первом экране, под кнопкой; бот ссылки на эти условия пока не показывает. + +Этот текст написан по-русски, английский — его перевод. Если они расходятся, действует русский. + +## Контакты + + + + +Оператор этого сервера — владелец учётной записи `lumenpearson` на GitHub, который сопровождает репозиторий [lumenpearson/lessons](https://github.com/lumenpearson/lessons). + +Написать ему можно на [странице Issues репозитория](https://github.com/lumenpearson/lessons/issues). Она открыта всем, поэтому не пишите там логинов, паролей, телефонов и имён детей — только суть вопроса. Если в вашей сборке есть кнопка «Отправить письмом» («Настройки → О приложении → Сообщить об ошибке»), можно написать и письмом. From 6fa1c6e89d934093251ccb3ff8e98caf3965b503 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 14:51:54 +0000 Subject: [PATCH 11/30] Let a phone register a diary session it opened itself, and fix what that exposed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone is about to sign in to Петербург and «Сетевой город» itself, so the password never reaches this server (#141). What it then needs is a door that takes the session the diary handed it, instead of the password. `POST /api/v1/diary/session` is that door. The body is one of two models chosen by `provider`, with `extra="forbid"` everywhere: a `password` key is a 422. Every credential value is checked against the one definition of "safe to put in a header" (`providers/diary/http.py`), because cookie values go straight into `Cookie:` and a `;` would inject a second one. The server then reads with the session once from its own address — Петербург's pupils, or «Сетевой город»'s four bootstrap calls, which fill the year and type fields a sealed credential cannot work without — seals it through the same `_open_row` as `sign_in`, and returns our token, the pupils and the diary's zone (`zone_for`, the same rule `today()` uses). It shares `/login`'s limiter and bucket, so ten wrong passwords do not buy ten more tries by session. A session the diary refuses from here is a 409, not `/login`'s 401 + reauth: asking for the password again would loop, and what failed is where the session came from. 422s no longer echo the refused value back. `GET /api/v1/diary/capabilities` tells the phone, before any password is typed, whether the diary is on and which regions this server serves. Every diary 503 now says why in `X-Diary-Unavailable`. `POST /diary/login` is otherwise unchanged, for older apps. `JoinResponse` gains `diary`, the class's binding through `registry.binding()`, so a phone joining a bound class can sign in without searching. The shared known-answer vectors (`tests/vectors/diary_protocol.json`) pin both sign-in protocols for the Kotlin port to be tested against; the Python side is driven over `httpx.MockTransport`. Adopting them forced the fixes below. - #145 The bot read a «Сетевой город» region its class had left: `_session_for` matched the provider only, and rebinding expired nothing. One clause, `reads_binding`, now decides; binding another region or school expires the sessions it no longer reads (`expire_off_binding`); unbinding does not. - #146 The keep-alive could overwrite a credential a read rotated while the ping was in flight: the write-back now matches only the sealed value it claimed. The per-origin breaker its comment promised now exists, per tick. - #147 A sign-in without `cacheVer` stored and sent the word "None" as `ver`. - #148 Malformed «Сетевой город» answers — an array from `logindata`/`login`, a non-ASCII or null salt, a non-integer `timeOut`, an unreadable role question — escaped as 500s. They are diary errors now. - #149 The school search kept a row whose id was JSON `true`; it also keeps the address now. - #150 (part) `Region.ca_bundle`, read by nothing, is gone; the source-order comment and the password-path docstrings are corrected. The user-facing texts and docs of that issue follow. Not linked to the bot (#143): a phone's session carries no Telegram account or class. Unverified: whether either diary accepts a session opened on a phone when replayed from this server's address — 409 is the designed answer; and the four bootstrap calls against Vercel's 30-second ceiling. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/diary.py | 280 +++++++- server/app/api/diary_web.py | 24 +- server/app/api/public.py | 7 + server/app/bot/handlers/diary.py | 33 +- server/app/bot/handlers/manage.py | 12 + server/app/models.py | 42 +- server/app/providers/diary/base.py | 54 +- server/app/providers/diary/errors.py | 20 +- server/app/providers/diary/http.py | 36 +- server/app/providers/netschool/client.py | 180 +++++- server/app/providers/netschool/provider.py | 115 +++- server/app/providers/netschool/regions.py | 13 +- server/app/providers/petersburg/client.py | 8 + server/app/providers/petersburg/provider.py | 23 +- server/app/schemas.py | 222 ++++++- server/app/services/diary.py | 206 +++++- server/app/services/diary_keepalive.py | 115 +++- server/tests/test_bot_diary.py | 32 + server/tests/test_bot_manage.py | 131 ++++ server/tests/test_diary_client.py | 27 + server/tests/test_diary_keepalive.py | 122 ++++ server/tests/test_diary_protocol_vectors.py | 411 ++++++++++++ server/tests/test_diary_session.py | 677 ++++++++++++++++++++ server/tests/test_join_modes.py | 61 ++ server/tests/test_netschool_client.py | 219 +++++++ server/tests/vectors/diary_protocol.json | 156 +++++ 26 files changed, 3042 insertions(+), 184 deletions(-) create mode 100644 server/tests/test_diary_protocol_vectors.py create mode 100644 server/tests/test_diary_session.py create mode 100644 server/tests/vectors/diary_protocol.json diff --git a/server/app/api/diary.py b/server/app/api/diary.py index cd0d2545..1be523b3 100644 --- a/server/app/api/diary.py +++ b/server/app/api/diary.py @@ -10,23 +10,38 @@ the two are different things: one is a class's shared plan, the other is one family's account somewhere else. Keeping them apart in the path keeps them apart in everybody's head. + +A session of ours is opened two ways. ``POST /session`` registers one the +phone opened itself, straight with the diary, so the password never reaches +this server; that is what the app does. ``POST /login`` takes the password and +signs in from here, and stays exactly as it was for the apps that still call +it. Every 503 either answers carries ``X-Diary-Unavailable`` — ``disabled``, +``address-refused`` or ``upstream`` — so the app can tell «выключен на +сервере» from «дневник не отвечает» without reading the Russian. """ from __future__ import annotations +from collections.abc import Callable, Coroutine from datetime import date as Date from datetime import timedelta +from typing import Annotated, Any from dishka.integrations.fastapi import FromDishka, inject -from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status +from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query, Request, status +from fastapi.exceptions import RequestValidationError +from fastapi.responses import Response from sqlalchemy.ext.asyncio import AsyncSession from app.api.public import MAX_BUNDLE_START, MIN_BUNDLE_START, caller_bucket from app.api.routing import DishkaAnnotatedRoute +from app.crypto import diary_enabled from app.models import DiarySession from app.providers.diary.errors import ( + AddressRefused, BadCredentials, DiaryError, + NoStudents, SessionExpired, SignInUnsupported, UnexpectedResponse, @@ -38,6 +53,7 @@ ) from app.schemas import ( DiaryAttendanceOut, + DiaryCapabilitiesOut, DiaryHomeworkOut, DiaryLessonOut, DiaryLoginIn, @@ -46,10 +62,15 @@ DiaryOverrideIn, DiaryOverrideOut, DiaryPeriodOut, + DiaryProvidersOut, DiaryResetIn, + DiarySessionBody, + DiarySessionOut, DiaryStudentOut, DiarySubjectOut, DiaryTeacherOut, + NetSchoolCapabilitiesOut, + NetSchoolSessionIn, ) from app.security import JoinThrottle from app.services import diary as service @@ -142,6 +163,40 @@ def _service( return service.DiaryService(session, row) +#: Says which of three things a diary 503 is, because the app does something +#: different about each and the ``detail`` is Russian prose it should not +#: parse: ``disabled`` (no ``DIARY_SECRET`` — nothing anybody types will help), +#: ``address-refused`` (the region drops this server's address — not the +#: password, not worth retrying) and ``upstream`` (the diary is down or will +#: not take this way in — try later). +UNAVAILABLE_HEADER = "X-Diary-Unavailable" + +#: The detail of the 503 a deployment without ``DIARY_SECRET`` answers. +DISABLED_DETAIL = "Дневник на этом сервере выключен." + + +def _unavailable(failure: UpstreamUnavailable | SignInUnsupported) -> HTTPException: + """The 503 for an upstream that did not let us in, with its reason named. + + ``SignInUnsupported`` is ``upstream`` too: it is the region's own answer + about who it lets in, and it comes only from the password sign-in. + """ + reason = "address-refused" if isinstance(failure, AddressRefused) else "upstream" + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail=failure.message, + headers={UNAVAILABLE_HEADER: reason}, + ) + + +def _disabled() -> HTTPException: + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail=DISABLED_DETAIL, + headers={UNAVAILABLE_HEADER: "disabled"}, + ) + + async def _guard(awaitable): """Turns a provider failure into the status code that fits it. @@ -168,15 +223,11 @@ async def _guard(awaitable): # is not the password and there is nothing to retry — and so that the # login limiter, which forgives only a 503, does not count an attempt # where nothing looked at a password. - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=failure.message - ) from failure + raise _unavailable(failure) from failure except UpstreamUnavailable as failure: # AddressRefused is a subclass and lands here too: a 503, uncounted, - # carrying its own «дело не в пароле» message. - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=failure.message - ) from failure + # carrying its own «дело не в пароле» message and its own header value. + raise _unavailable(failure) from failure except UnexpectedResponse as failure: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail=failure.message @@ -212,6 +263,33 @@ async def _guard(awaitable): diary_login_limiter = JoinThrottle(limit=10, window=900.0) +async def _refuse_if_throttled(session: AsyncSession, client: str) -> None: + """429 while ``client`` has spent its failures. One check for both doors + onto the upstream, so they cannot drift into two limits.""" + retry_after = await diary_login_limiter.blocked_for(session, client) + if retry_after is not None: + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail="Слишком много попыток входа. Попробуйте позже.", + headers={"Retry-After": str(int(retry_after) + 1)}, + ) + + +def _served_region(key: str | None) -> str: + """An allow-listed «Сетевой город» region that still takes a password, or + a 422 — asked before any upstream call, so a region we do not serve never + receives a request, whichever door it came through.""" + from app.providers.netschool import regions + + region = regions.get(key) + if region is None or not region.password: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Unknown or unsupported region for «Сетевой город»", + ) + return region.key + + def _resolve_login_target(payload: DiaryLoginIn) -> tuple[str, str | None, int | None]: """The provider, region and school to sign in with, validated locally. @@ -225,20 +303,13 @@ def _resolve_login_target(payload: DiaryLoginIn) -> tuple[str, str | None, int | if provider == PETERSBURG: return PETERSBURG, None, None if provider == NETSCHOOL: - from app.providers.netschool import regions - - region = regions.get(payload.region) - if region is None or not region.password: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Unknown or unsupported region for «Сетевой город»", - ) + region = _served_region(payload.region) if payload.school_id is None: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="A school id is required for «Сетевой город»", ) - return NETSCHOOL, region.key, payload.school_id + return NETSCHOOL, region, payload.school_id raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Unknown diary provider {provider!r}", @@ -266,13 +337,7 @@ async def login( # 500 instead of 401 and nothing was ever counted — the limit below existed # only in the tests, where SQLite does not enforce a width. client = caller_bucket(request, scope="diary:") - retry_after = await diary_login_limiter.blocked_for(session, client) - if retry_after is not None: - raise HTTPException( - status_code=status.HTTP_429_TOO_MANY_REQUESTS, - detail="Слишком много попыток входа. Попробуйте позже.", - headers={"Retry-After": str(int(retry_after) + 1)}, - ) + await _refuse_if_throttled(session, client) provider, region, school_id = _resolve_login_target(payload) @@ -295,10 +360,7 @@ async def login( # per attempt, and nothing for the app to put on the screen. The other # door onto the same service, ``POST /diary/signin``, has always # answered 503 and said so in words; this is that answer. - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Дневник на этом сервере выключен.", - ) from failure + raise _disabled() from failure except HTTPException as refusal: # Everything but a 503 counts, and the line is drawn where the other # door onto this upstream draws it. @@ -324,6 +386,168 @@ async def login( return DiaryLoginOut(token=token, login=row.login) +# --------------------------------------------------------------------------- +# A session the phone opened +# --------------------------------------------------------------------------- + + +#: The detail of a registration the upstream refused from this server. +REFUSED_FROM_HERE_DETAIL = "Дневник не принял эту сессию с нашего сервера — дело не в пароле." + + +class _NoEchoRoute(DishkaAnnotatedRoute): + """A route whose 422 names what was wrong and never repeats what was sent. + + FastAPI's validation answer carries each refused value back as ``input``. + On ``/session`` that value is an upstream session — a cookie that failed + the charset check, a token that is not a JWT — or, for a client that sent + one, a password. A session goes to this server once and is never echoed; + the refusal is no exception to that. + """ + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + handler = super().get_route_handler() + + async def without_echo(request: Request) -> Response: + try: + return await handler(request) + except RequestValidationError as refusal: + raise RequestValidationError( + [ + {key: value for key, value in error.items() if key != "input"} + for error in refusal.errors() + ] + ) from None + + return without_echo + + +@router.get("/capabilities", response_model=DiaryCapabilitiesOut) +async def capabilities() -> DiaryCapabilitiesOut: + """What this server's diary can do, before the phone takes a password. + + Anonymous and database-free, so it is cheap to ask on every sign-in + screen: whether the diary runs here at all, and which «Сетевой город» + regions this server signs in to — a region missing from the list is one + the phone should not send a password to, since the session it opened could + not be kept. A server from before registration answers 404 here. + """ + from app.providers.netschool import regions + + return DiaryCapabilitiesOut( + enabled=diary_enabled(), + providers=DiaryProvidersOut( + netschool=NetSchoolCapabilitiesOut(regions=[r.key for r in regions.listed()]), + ), + ) + + +def _resolve_session_target(payload: DiarySessionBody) -> tuple[str, str | None, int | None]: + """The provider, region and school to adopt into, checked against the + allow-list before any call — a region outside it, or one that takes no + password (altai-krai, primorye, tula), is a 422 that nothing upstream saw. + """ + if not isinstance(payload, NetSchoolSessionIn): + return PETERSBURG, None, None + return NETSCHOOL, _served_region(payload.region), payload.school_id + + +async def register_session( + request: Request, + payload: Annotated[DiarySessionBody, Body(discriminator="provider")], + *, + session: FromDishka[AsyncSession], +) -> DiarySessionOut: + """Keep a session the phone opened itself, and hand back a token of ours. + + The phone signed in with the diary directly, so the password never came + here; what arrives is the session the diary gave it. It is read with once, + from this server's address — that read is the check — then sealed, and the + phone forgets its copy. Nothing here stores or accepts a password: a + ``password`` key anywhere in the body is a 422. + + Shares ``/login``'s limiter **and bucket**, so a caller who spent ten + wrong passwords does not get ten more tries by session. Counted: a session + the upstream refused (409), an account with no pupil (403), an answer + nobody can read (502). Not counted: anything that never reached the + upstream (422), the feature being off, or the upstream not answering (503). + + 409 rather than ``/login``'s 401 + ``X-Diary-Reauth``, because asking for + the password again would loop: the session was good on the phone seconds + ago, and it is *this server* the diary will not take it from. + """ + # The same limiter and the same bucket as /login: a separate one would + # double what one caller may try against the upstream from our address. + client = caller_bucket(request, scope="diary:") + await _refuse_if_throttled(session, client) + + provider, region, school_id = _resolve_session_target(payload) + # The provider's own serialisation: Petersburg's bare token, or the JSON of + # what «Сетевой город» handed the phone, with the fields it did not hand + # left out rather than stored as nulls. + credential = ( + payload.credential.model_dump_json(exclude_none=True) + if isinstance(payload, NetSchoolSessionIn) + else payload.credential.token + ) + + try: + registered = await service.adopt( + session, + provider=provider, + login=payload.login, + credential=credential, + region=region, + school_id=school_id, + ) + except service.DiaryDisabled as failure: + raise _disabled() from failure + except UpstreamUnavailable as failure: + # Nothing judged the session: the diary did not answer, or will not + # talk to this address at all. Forgiven, like /login's 503. + raise _unavailable(failure) from failure + except NoStudents as failure: + await diary_login_limiter.record_failure(session, client) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail=failure.message + ) from failure + except (SessionExpired, BadCredentials) as failure: + # Before the broader DiaryError below, and after NoStudents, which is + # a SessionExpired too. Counted: this is also what a replay of a + # session that was never real looks like. + await diary_login_limiter.record_failure(session, client) + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=REFUSED_FROM_HERE_DETAIL + ) from failure + except DiaryError as failure: + await diary_login_limiter.record_failure(session, client) + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, detail=failure.message + ) from failure + + return DiarySessionOut( + token=registered.token, + login=registered.row.login, + provider=provider, + region=region, + school_id=school_id, + school_name=registered.school_name, + zone=service.zone_for(provider, region), + students=[DiaryStudentOut.of(student) for student in registered.students], + ) + + +# Added by hand rather than by decorator only to give it the route class that +# keeps a refused session out of the 422. +router.add_api_route( + "/session", + register_session, + methods=["POST"], + response_model=DiarySessionOut, + route_class_override=_NoEchoRoute, +) + + @router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) async def logout( row: DiarySession = Depends(current_diary), diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index 2b6b5667..76566236 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -7,15 +7,21 @@ chat history, on Telegram's servers, in the notification on a locked screen and in that phone's backup, and deleting the message undoes none of it. -So the password is taken here instead: over HTTPS, straight from the browser -to the upstream, written down nowhere. The page holds no state of its own. It -sets no cookie, because the session it opens belongs to a Telegram account -rather than to whichever browser happened to be handy. It is reached once, -with a ticket the bot handed out (``services/diary_link``), and the ticket is -spent by an attempt — a right password and a wrong one cost the same. The one -thing that does not cost it is the diary being unreachable, where nothing ever -looked at the password and so no guess was made (see ``_unspend``, which says -why that line is drawn there and not further along). +So the password is taken here instead: over HTTPS, from the browser to this +server, which passes it to the diary once and writes it down nowhere. It does +cross this server. The app's own sign-in does not — it talks to the diary +directly and hands over only the session — so this page, and the +``POST /api/v1/diary/login`` older apps still call, are where a family's +password passes through us, and they are described that way. + +The page holds no state of its own. It sets no cookie, because the session it +opens belongs to a Telegram account rather than to whichever browser happened +to be handy. It is reached once, with a ticket the bot handed out +(``services/diary_link``), and the ticket is spent by an attempt — a right +password and a wrong one cost the same. The one thing that does not cost it is +the diary being unreachable, where nothing ever looked at the password and so +no guess was made (see ``_unspend``, which says why that line is drawn there +and not further along). Three headers do the rest of the work, and each answers a specific leak: diff --git a/server/app/api/public.py b/server/app/api/public.py index 430fc700..b6d841b7 100644 --- a/server/app/api/public.py +++ b/server/app/api/public.py @@ -35,6 +35,7 @@ Subject, TimetableEntry, ) +from app.providers.diary.registry import binding as diary_binding from app.schedule import ResolvedDay, ResolvedLesson, ScheduleResolver from app.schemas import ( API_VERSION, @@ -43,6 +44,7 @@ ClassOut, DayOut, DeviceOut, + DiaryBindingOut, DoneIn, DoneOut, EventOut, @@ -430,6 +432,11 @@ async def join( class_name=school_class.name, school=school_class.school, timezone=school_class.timezone_name, + # Through `registry.binding`, the one reading of a class's binding, so + # a region since dropped from the allow-list, one that takes no + # password, or a «Сетевой город» binding with no school all tell the + # phone «no diary» rather than point it at one this server refuses. + diary=DiaryBindingOut.of(diary_binding(school_class)), ) diff --git a/server/app/bot/handlers/diary.py b/server/app/bot/handlers/diary.py index ab5ec0c9..8796b5ce 100644 --- a/server/app/bot/handlers/diary.py +++ b/server/app/bot/handlers/diary.py @@ -22,7 +22,7 @@ class to dnevnik2 gives the class nothing; it offers every member a door to from aiogram import F, Router from aiogram.types import CallbackQuery -from sqlalchemy import or_, select +from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.bot.diary_keyboard import ( @@ -44,6 +44,7 @@ class to dnevnik2 gives the class nothing; it offers every member a door to from app.config import get_settings from app.crypto import diary_enabled from app.models import DiarySession, Role, SchoolClass +from app.providers.diary import registry as diary_registry from app.providers.diary.errors import DiaryError, SessionExpired, UpstreamUnavailable from app.providers.diary.registry import binding as diary_binding from app.services import diary as diary_service @@ -53,9 +54,10 @@ class to dnevnik2 gives the class nothing; it offers every member a door to router = Router(name="diary") -#: The provider a class may be bound to. One today; the column is a string so -#: that a second one does not rename it. -PETERSBURG = "petersburg" +#: Petersburg's provider key, as the class column stores it. The registry's +#: own name (`registry.PETERSBURG`), kept here under the spelling the tests of +#: this module bind a class with. +PETERSBURG = diary_registry.PETERSBURG #: How many days of homework a «Задания» screen asks for. HOMEWORK_DAYS = 14 @@ -73,29 +75,26 @@ async def _session_for( classes would read one child's diary from the other class's screen; on class_id alone there would be no diary in this bot worth having. - Also keyed on the class's *current* provider: an admin can rebind a class - from one diary to another, and a session opened against the old upstream - holds a credential the new diary would not accept. Filtering it out here - turns the stale row into a clean «войдите снова» rather than a screen that - silently talks to the diary the class left. A legacy row with no provider - is Petersburg, which is what the column meant before it existed. + Also keyed on the class's *current* binding: an admin can rebind a class + from one diary to another, or from one «Сетевой город» region to another, + and a session opened against the old one holds a credential for a server + the class has left. Filtering it out here turns the stale row into a clean + «войдите снова» rather than a screen that silently talks to the diary the + class left. Matching the provider alone let a session on the old region + through; `diary_service.reads_binding` is the one clause, and the rebind + expires the same rows by it. A legacy row with no provider is Petersburg, + which is what the column meant before it existed. """ b = diary_binding(school_class) if b is None: return None - if b.provider.key == PETERSBURG: - provider_clause = or_( - DiarySession.provider == PETERSBURG, DiarySession.provider.is_(None) - ) - else: - provider_clause = DiarySession.provider == b.provider.key row = await session.scalar( select(DiarySession) .where( DiarySession.telegram_id == telegram_id, DiarySession.class_id == school_class.id, DiarySession.expired_at.is_(None), - provider_clause, + diary_service.reads_binding(b), ) .order_by(DiarySession.id.desc()) ) diff --git a/server/app/bot/handlers/manage.py b/server/app/bot/handlers/manage.py index 3ae1aff6..b5bad8d5 100644 --- a/server/app/bot/handlers/manage.py +++ b/server/app/bot/handlers/manage.py @@ -122,6 +122,7 @@ from app.services import access as access_service from app.services import audit, linking, structure, timetable_io from app.services import calendar as calendar_service +from app.services import diary as diary_service from app.services import stats as stats_service from app.services import subjects as subjects_service from app.services import terms as terms_service @@ -2389,6 +2390,10 @@ async def class_diary_bind( if school_class.diary_provider: # Bound → unbind. The door goes; the sessions people opened stay theirs # until they sign out or the class is deleted, as three screens promise. + # Nothing is expired here, deliberately: with no binding the bot reads + # none of them anyway, and a later bind expires exactly those it does + # not read (`diary_service.expire_off_binding`) — which, unlike this, + # knows which diary the class went to. school_class.diary_provider = None school_class.diary_region = None school_class.diary_school_id = None @@ -2427,6 +2432,9 @@ async def class_diary_provider( school_class.diary_region = None school_class.diary_school_id = None school_class.diary_school_name = None + # The members' «Сетевой город» sessions read a diary the class has + # left; expired in the same commit as the binding they no longer fit. + await diary_service.expire_off_binding(session, school_class) await audit.record( session, school_class.id, callback.from_user.id, "class.diary", "привязан дневник Санкт-Петербурга", @@ -2583,6 +2591,10 @@ async def class_diary_school( school_class.diary_region = region.key school_class.diary_school_id = int(school["id"]) school_class.diary_school_name = str(school["name"])[:300] + # Sessions on another region's server, or Petersburg's, read a diary the + # class has left: expired with the binding, so the keep-alive stops + # pinging a server nobody here uses. The same region keeps them. + await diary_service.expire_off_binding(session, school_class) await audit.record( session, school_class.id, callback.from_user.id, "class.diary", f"привязан «Сетевой город»: {region.title}, {str(school['name'])[:200]}", diff --git a/server/app/models.py b/server/app/models.py index 57f58934..7298ce92 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -767,11 +767,15 @@ class DiarySession(Base): session dies the app asks the person to sign in again, which is what every other service does too. - The token is a bearer credential, so it is treated like one: it never - leaves the server, never reaches the Android client, and the client is - handed a token of ours instead (`token_hash`, hashed exactly like - :class:`DeviceToken`). One row is one browser-shaped session; a person - signing in twice gets two, and signing out drops one. + The token is a bearer credential, so it is treated like one. It arrives + one of two ways: this server signs in with a password and receives it + (the bot's sign-in page, the older ``POST /api/v1/diary/login``), or the + phone signs in with the diary itself and hands the session over once + (``POST /api/v1/diary/session``), then forgets it. Either way it never + leaves this server again — no answer carries it back to any client — and + the client is handed a token of ours instead (`token_hash`, hashed exactly + like :class:`DeviceToken`). One row is one browser-shaped session; a + person signing in twice gets two, and signing out drops one. """ __tablename__ = "diary_sessions" @@ -779,24 +783,28 @@ class DiarySession(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True) # Our token, as a hash. The plaintext is shown to the client once. token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False) - # The upstream's ``X-JWT-Token``, **sealed** — see ``app/crypto.py``. It is - # the one credential here that cannot be a hash, because it is replayed to - # the upstream on every call, so it is the one that is encrypted instead. - # Refreshed in place (and re-sealed) whenever the upstream hands back a new - # one, which it does on most calls. + # The upstream's session — Petersburg's ``X-JWT-Token``, or «Сетевой + # город»'s ``at``, cookies and bootstrap as JSON — **sealed**; see + # ``app/crypto.py``. It is the one credential here that cannot be a hash, + # because it is replayed to the upstream on every call, so it is the one + # that is encrypted instead. Refreshed in place (and re-sealed) whenever the + # upstream hands back a new one, which it does on most calls. upstream_token: Mapped[str] = mapped_column(Text, nullable=False) # Who signed in. Shown on the "you are signed in as" line, and also the key # a family's corrections hang on (`services/diary.py:owner_key`), so the # same login re-used later lays its overrides over the same lessons. login: Mapped[str] = mapped_column(String(200), nullable=False) # The Telegram account this session belongs to. Set when the session was - # opened from the bot's sign-in ticket (`api/diary_web.py`); NULL for the - # phone's `POST /api/v1/diary/login`, which has no Telegram account. + # opened from the bot's sign-in ticket (`api/diary_web.py`); NULL for a + # phone's (`POST /api/v1/diary/session`, or the older `/login`), which has + # no Telegram account — showing a phone's session in the bot is left for + # later, on purpose. telegram_id: Mapped[int | None] = mapped_column(BigInteger, index=True) # The class the session was opened from, when it was opened in the bot. # Carried so that leaving a class can take its diary session with it, and # so that «Дневник» in one class does not answer with a session opened in - # another. Null for the Android client, which has no class in this flow. + # another. Null for a phone's session, which belongs to no class: joining + # a class and signing in to a diary imply nothing about each other. class_id: Mapped[int | None] = mapped_column( ForeignKey("classes.id", ondelete="CASCADE"), index=True ) @@ -838,9 +846,11 @@ class DiaryLinkCode(Base): The password is the whole confidentiality question, and the answer this project gives is that it never enters Telegram at all. The bot hands out a URL; the form is served over HTTPS by this same app; the password goes - from the browser straight to the upstream and is never written down. What - Telegram ever sees is this code, which is worth one sign-in, for fifteen - minutes, for one account. + from the browser to this server, which passes it to the diary once and + writes it down nowhere. It does cross this server — unlike the app's own + sign-in, which talks to the diary directly — and that is said wherever + the form is described. What Telegram ever sees is this code, which is + worth one sign-in, for fifteen minutes, for one account. Typing the password to the bot instead would put it in the chat history, on Telegram's servers, in the notification that pops up on a locked screen and diff --git a/server/app/providers/diary/base.py b/server/app/providers/diary/base.py index ea813526..d89e4472 100644 --- a/server/app/providers/diary/base.py +++ b/server/app/providers/diary/base.py @@ -1,10 +1,17 @@ -"""The shape a diary provider meets, and the request that signs one in. +"""The shape a diary provider meets, and the two ways a session reaches it. -Two protocols and one dataclass. `services/diary.DiaryService` builds a +Two protocols and three dataclasses. `services/diary.DiaryService` builds a :class:`DiaryConnection` from the provider named on the session row and calls it; it never knows which upstream is behind it. A provider raises only the :mod:`app.providers.diary.errors` family from these methods — never a ``ValueError`` or a ``KeyError``, which would reach the API edge as a 500. + +A session arrives one of two ways. :class:`SignInRequest` carries a password, +which this server sends upstream once (the bot's sign-in page, and +``POST /api/v1/diary/login`` for the apps that still call it). +:class:`AdoptRequest` carries a session the phone opened itself, straight with +the diary, so the password never came here at all; the provider checks it with +a read of its own and hands back :class:`Adopted`. """ from __future__ import annotations @@ -41,6 +48,36 @@ class SignInRequest: school_id: int | None = None +@dataclass(frozen=True) +class AdoptRequest: + """A session the phone opened itself, handed over once for this server to keep. + + ``credential`` is the provider's own serialisation of what the phone + received — Petersburg's bare JWT, «Сетевой город»'s JSON of ``at``, the + cookies, ``ver`` and ``timeOut`` — and ``repr=False`` for the same reason + as a password: it opens the account. + """ + + credential: str = field(repr=False) + region: str | None = None + school_id: int | None = None + + +@dataclass(frozen=True) +class Adopted: + """What a validated session comes to: the credential to seal, and what the + validating read already fetched, so the caller does not ask again. + + ``credential`` may differ from the one handed in — the validating read can + rotate it — and it is this one that is sealed. ``school_name`` is what the + upstream calls the school, where it says; ``None`` otherwise. + """ + + credential: str = field(repr=False) + students: tuple[Student, ...] = () + school_name: str | None = None + + @runtime_checkable class DiaryConnection(Protocol): """One signed-in session's reads. @@ -95,5 +132,18 @@ class DiaryProvider(Protocol): async def sign_in(self, request: SignInRequest) -> str: """Sign in and return the serialised credential, which the caller seals.""" + async def adopt(self, request: AdoptRequest) -> Adopted: + """Check a session the phone opened, from this server's address, and + return what to seal. A session the upstream will not take from here + is :class:`~app.providers.diary.errors.SessionExpired`; an account + with no pupil is :class:`~app.providers.diary.errors.NoStudents`.""" + def open(self, credential: str) -> DiaryConnection: """A connection for a stored credential.""" + + def zone(self, region: str | None) -> str: + """The IANA zone this diary's days are cut at, for ``region``. + + The one rule: a connection's ``today()`` cuts the day with it, and the + phone is told it at registration, so the two never disagree about + which day it is in the diary.""" diff --git a/server/app/providers/diary/errors.py b/server/app/providers/diary/errors.py index 3df0cee8..97ff007a 100644 --- a/server/app/providers/diary/errors.py +++ b/server/app/providers/diary/errors.py @@ -55,6 +55,20 @@ class SessionExpired(DiaryError): message = "Сессия дневника истекла — войдите заново" +class NoStudents(SessionExpired): + """The account signed in, and there is no pupil behind it. + + A staff-only account, or a pupil's account that does not list itself. A + subclass of :class:`SessionExpired` so the password sign-in keeps the + answer it always gave (401 with ``X-Diary-Reauth``), while registering a + session the phone opened can tell it apart: there the session was + accepted, so «войдите снова» would be the wrong sentence and a 403 says + what is true. + """ + + message = "В этой учётной записи нет ученика" + + class UpstreamUnavailable(DiaryError): """A timeout, a connection failure, or a 5xx. @@ -75,8 +89,10 @@ class AddressRefused(UpstreamUnavailable): server dropping a foreign or datacenter address, seen as a WAF block page, a 403, or a connection reset. Told apart from a timeout because retrying cannot help and the family must hear that it is not their password and not - worth trying again; the keep-alive trips a per-origin breaker on it rather - than pinging that origin's other sessions into the same wall. + worth trying again. The keep-alive trips a per-origin breaker on it + (`services/diary_keepalive._ping_all`): the rest of that origin's sessions + are not pinged for the rest of the tick, rather than each walking into the + same wall from the same address. """ message = ( diff --git a/server/app/providers/diary/http.py b/server/app/providers/diary/http.py index 6b5e490c..e483d98a 100644 --- a/server/app/providers/diary/http.py +++ b/server/app/providers/diary/http.py @@ -19,12 +19,21 @@ ``build_client`` also pins ``follow_redirects=False`` (a cross-origin redirect would carry the session bearer to another host — the one way around a region allow-list) and never turns TLS verification off. + +And a third, which arrived with the phone opening sessions itself: **a stored +session value is only ever written into a header if it is safe there.** A +cookie value holding ``;`` smuggles a second cookie, and one holding CR/LF a +second header. :func:`cookie_value_ok` and :func:`header_value_ok` are the one +definition of "safe", used by the schema that accepts a session from a phone +*and* by the clients that write the headers, so a credential that reached the +database by any path is checked again on the way out. """ from __future__ import annotations import http.cookiejar import logging +import re import httpx @@ -37,6 +46,25 @@ "Chrome/124.0.0.0 Safari/537.36" ) +#: RFC 6265 ``cookie-octet``: printable ASCII less space, the double quote, +#: the comma, the semicolon and the backslash. What a ``Cookie:`` header can +#: carry as one value and nothing more. +_COOKIE_OCTETS = re.compile(r"[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+") + +#: RFC 7235 ``token68``: what a bearer-shaped header value is made of. No +#: space, no quote, no CR or LF — so no way to end the header and start another. +_HEADER_TOKEN = re.compile(r"[A-Za-z0-9._~+/=-]+") + + +def cookie_value_ok(value: object) -> bool: + """Whether ``value`` can be sent as one cookie's value without becoming two.""" + return isinstance(value, str) and _COOKIE_OCTETS.fullmatch(value) is not None + + +def header_value_ok(value: object) -> bool: + """Whether ``value`` can be sent as a bearer-shaped header value, whole.""" + return isinstance(value, str) and _HEADER_TOKEN.fullmatch(value) is not None + class NoCookieJar(http.cookiejar.CookieJar): """A jar that keeps nothing it is handed. @@ -92,7 +120,9 @@ def build_client( cookies=NoCookieJar(), headers=base_headers, follow_redirects=False, - # verify defaults to True and is never set False: a region that needs - # the Russian Trusted Root must carry its own CA bundle in regions.py, - # not have verification switched off for everyone. + # verify defaults to True and is never set False. A region whose + # server presents a root the system does not trust (the Russian + # Trusted Root) is left out of the allow-list rather than given a + # CA of its own or a verification switched off — there is no + # per-origin trust store here, and none is read. ) diff --git a/server/app/providers/netschool/client.py b/server/app/providers/netschool/client.py index 3c71c80e..9ca97c89 100644 --- a/server/app/providers/netschool/client.py +++ b/server/app/providers/netschool/client.py @@ -8,9 +8,12 @@ The session is a small dict, sealed by the service into ``upstream_token``: ``at`` (the bearer), the cookies to send, ``ver`` (for the SecurityWarning -acknowledgement), the school year id and its bounds, the assignment-type map, -and the login's ``timeOut`` so the keep-alive knows this server's idle window. -No password, and no hash of it, is ever in it. +acknowledgement and the logout, and only when the server gave one), the school +year id and its bounds, the assignment-type map, and the login's ``timeOut``. +That last one is stored and read by nothing: the keep-alive pings on a fixed +floor (`services/diary_keepalive.KEEPALIVE_MIN_INTERVAL`) well inside the +shortest idle window seen, rather than trusting each server's own figure. No +password, and no hash of it, is ever in it. Rules the review nailed down, each with a reason: @@ -22,6 +25,11 @@ answers JSON and 401 rather than an HTML redirect. - A blocked address (403, a WAF page, a connection reset) is :class:`AddressRefused`, never a wrong password and never an expired session. +- Every answer is read as the shape it turned out to be, not the one it should + have been. A list where an object belongs, a salt in Cyrillic, a ``timeOut`` + of ``"soon"`` are each an error of the diary family; before, each walked out + of this module as ``AttributeError``, ``UnicodeEncodeError`` or + ``ValueError`` and answered the sign-in with a 500. - Sign-in *ends* at the accepted ``POST /webapi/login``. A failure before it (logindata, getdata) is :class:`UpstreamUnavailable`/:class:`AddressRefused`/ :class:`SignInUnsupported` — nothing looked at the password. A failure in the @@ -47,7 +55,12 @@ UnexpectedResponse, UpstreamUnavailable, ) -from app.providers.diary.http import build_client, session_cookie +from app.providers.diary.http import ( + build_client, + cookie_value_ok, + header_value_ok, + session_cookie, +) from app.providers.netschool.regions import Region log = logging.getLogger(__name__) @@ -101,7 +114,15 @@ def _hash_password(salt: str, password: str) -> tuple[str, str]: A character the region's charset cannot encode is a wrong password from here: raised as :class:`BadCredentials` without the source character in the message, because that message would otherwise carry the password. + + The salt is the server's, and one that is not ASCII is the server's + failure, not the password's: :class:`UpstreamUnavailable`, which hands the + ticket back, because nothing has looked at what was typed. It used to + raise ``UnicodeEncodeError`` out of the diary's error family, which the + sign-in answered with a 500. """ + if not salt.isascii(): + raise UpstreamUnavailable try: raw = password.encode("windows-1251") except UnicodeEncodeError: @@ -111,6 +132,26 @@ def _hash_password(salt: str, password: str) -> tuple[str, str]: return pw2[: len(password)], pw2 +def _scalar_text(value: Any) -> str: + """A JSON string or integer as the text it spells, and anything else as "". + + ``str(value)`` is what these lines used to be, and it turns a missing + ``ver`` into the word ``"None"`` and a ``true`` into ``"True"`` — values + the server then reads as if it had sent them. A bool is refused although + Python calls it an ``int``. + """ + if isinstance(value, str): + return value + if isinstance(value, int) and not isinstance(value, bool): + return str(value) + return "" + + +def _json_int(value: Any) -> int | None: + """A JSON integer, or ``None`` — never a bool, never a string of digits.""" + return value if isinstance(value, int) and not isinstance(value, bool) else None + + class NetSchoolClient: """Calls one region's ``/webapi`` on behalf of one session. @@ -134,15 +175,36 @@ def _url(self, path: str) -> str: return f"{self.region.origin}{path}" def _auth_headers(self) -> dict[str, str]: + """The session as headers, and only if every part of it is safe there. + + The phone now hands this server a session it opened, and the schema + checks it at the door; this checks again, whatever wrote the sealed + value. An ``at`` holding a line break is a second header, and a cookie + value holding ``;`` is a second cookie. A session that cannot be sent + whole is a dead one — :class:`SessionExpired`, the answer every dead + session gets — rather than one sent in pieces. + """ headers: dict[str, str] = {} at = self.session.get("at") if at: + if not header_value_ok(at): + raise SessionExpired headers["at"] = at cookies = self.session.get("cookies") or {} + if not isinstance(cookies, dict): + raise SessionExpired if cookies: + for name, value in cookies.items(): + if name not in SESSION_COOKIES or not cookie_value_ok(value): + raise SessionExpired headers["cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items()) return headers + def _ver(self) -> str: + """The stored ``ver``, or "" — never the word "None" a missing one was + once stored as, which sealed sessions from before the fix still hold.""" + return _scalar_text(self.session.get("ver")) + def _absorb_cookies(self, response: httpx.Response) -> None: """Fold this answer's session cookies into the stored set.""" cookies = dict(self.session.get("cookies") or {}) @@ -241,7 +303,7 @@ async def _acknowledge_warning(self) -> None: with_at = self.session.get("at") if not with_at: return - data = {"at": with_at, "WarnType": "2", "ver": str(self.session.get("ver", ""))} + data = {"at": with_at, "WarnType": "2", "ver": self._ver()} try: await self._send("POST", "/asp/SecurityWarning.asp", data=data) except UpstreamUnavailable: @@ -257,10 +319,17 @@ async def login_allowed(self) -> None: """ response = await self._send("GET", "/webapi/logindata", auth=False) data = self._decode(response, step="logindata") + if not isinstance(data, dict): + raise UnexpectedResponse self._absorb_cookies(response) if not data.get("schoolLogin", True): raise SignInUnsupported - self.session.setdefault("ver", data.get("cacheVer")) + # Kept only when the server gave one. `setdefault` of a missing + # `cacheVer` used to store None, which the warning acknowledgement and + # the logout then posted as the word "None". + ver = _scalar_text(data.get("cacheVer")) + if ver: + self.session.setdefault("ver", ver) async def login(self, login: str, password: str, school_id: int) -> None: """Sign in with a password. On return the session holds ``at`` and cookies. @@ -275,6 +344,12 @@ async def login(self, login: str, password: str, school_id: int) -> None: try: await self._password_login(login, password, school_id, rolegroup=None) except _NeedsRole as need: + if need.rolegroup is None: + # The server wants a role chosen and names none this code can + # read. Retrying without one asks the same question again, and + # the second `_NeedsRole` used to leave this client as an + # exception outside the diary's family — a 500. + raise UnexpectedResponse from None await self._password_login(login, password, school_id, rolegroup=need.rolegroup) async def _password_login( @@ -287,9 +362,11 @@ async def _password_login( ) self._absorb_cookies(getdata) payload = self._decode(getdata, step="getdata") - salt = str(payload.get("salt", "")) - lt = str(payload.get("lt", "")) - ver = str(payload.get("ver", "")) + if not isinstance(payload, dict): + payload = {} + salt = _scalar_text(payload.get("salt")) + lt = _scalar_text(payload.get("lt")) + ver = _scalar_text(payload.get("ver")) if not salt or not lt: raise UpstreamUnavailable # getdata is before the password; hand the ticket back pw, pw2 = _hash_password(salt, password) @@ -328,18 +405,30 @@ def _consume_login( body = response.json() except ValueError: raise UnexpectedResponse from None - entry = body.get("entryPoint") or "" - if "choose-session-role" in entry and not tried_role: + if not isinstance(body, dict): + raise UnexpectedResponse + entry = body.get("entryPoint") + if isinstance(entry, str) and "choose-session-role" in entry and not tried_role: # The account is both staff and parent. The salt was one-shot, so # the role re-login (in `login`) reruns the whole sequence with a # fresh one. Checked before `at` is accepted, as netschoolpy does. raise _NeedsRole(self._pick_parent_role(body)) at = body.get("at") - if not at: + if not isinstance(at, str) or not at: + # A number here used to be stored as it came and blew up as a + # TypeError in the next call's headers. raise BadCredentials(self._login_message(body)) + if not header_value_ok(at): + # Accepted, but not a value that can go in a header whole — a + # shape this code does not know, not a wrong password. + raise UnexpectedResponse self.session["at"] = at - if body.get("timeOut"): - self.session["time_out"] = int(body["timeOut"]) + # Kept when it is a JSON integer and ignored otherwise: `int("soon")` + # raised ValueError out of the sign-in. Nothing reads it (see the + # module docstring), so ignoring an odd one costs nothing. + time_out = _json_int(body.get("timeOut")) + if time_out: + self.session["time_out"] = time_out @staticmethod def _login_message(source: Any) -> str | None: @@ -356,20 +445,33 @@ def _login_message(source: Any) -> str | None: @staticmethod def _pick_parent_role(body: dict[str, Any]) -> str | None: - info = body.get("accountInfo") or {} - roles = info.get("userRoles") or body.get("userRoles") or [] + """The role to sign in as: the first parent's, else the first role's. + + A role is ``entry.role`` or the entry itself, and it counts only with + an id that is a JSON string or integer — anything else is skipped, so + a ``true`` is never posted as the word ``True``. Every level is checked + for its type, because this is read off an answer that has already + surprised us once by asking the question at all. + """ + info = body.get("accountInfo") + roles = info.get("userRoles") if isinstance(info, dict) else None + if not roles: + roles = body.get("userRoles") + if not isinstance(roles, list): + return None + usable: list[tuple[str, str]] = [] for entry in roles: - role = entry.get("role", entry) if isinstance(entry, dict) else {} - name = str(role.get("name", "")) if isinstance(role, dict) else "" + role = entry.get("role", entry) if isinstance(entry, dict) else None + if not isinstance(role, dict): + continue + rid = _scalar_text(role.get("id")) + if rid: + name = role.get("name") + usable.append((rid, name if isinstance(name, str) else "")) + for rid, name in usable: if "Родител" in name: - rid = role.get("id") if isinstance(role, dict) else None - if rid is not None: - return str(rid) - if roles: - first = roles[0].get("role", roles[0]) if isinstance(roles[0], dict) else {} - rid = first.get("id") if isinstance(first, dict) else None - return str(rid) if rid is not None else None - return None + return rid + return usable[0][0] if usable else None # ---- keep-alive and logout ------------------------------------------- @@ -390,7 +492,7 @@ async def logout(self) -> None: "POST", "/webapi/auth/logout", auth=True, - data={"at": at, "ver": str(self.session.get("ver", ""))}, + data={"at": at, "ver": self._ver()}, timeout=_KEEPALIVE_TIMEOUT, ) except (UpstreamUnavailable, SessionExpired, UnexpectedResponse): @@ -434,6 +536,14 @@ async def schools_search(self, query: str) -> list[dict[str, Any]]: what it gives; the caller cuts and indexes. A blocked address or a down server raises, so the admin is told which rather than shown an empty list they cannot tell from «no such school». + + A row is kept only with an ``id`` that is a JSON integer and a name + that is non-blank text. ``isinstance(True, int)`` is true in Python, so + a row whose id was ``true`` used to be kept as the school with id 1. + ``address`` is the server's ``addressString`` where it gave one: it is + what tells apart the many «Школа № 5» of one region. The phone's own + search reads the same rows by the same rule + (``tests/vectors/diary_protocol.json``). """ response = await self._send( "GET", "/webapi/schools/search", auth=False, params={"name": query[:60]} @@ -443,8 +553,20 @@ async def schools_search(self, query: str) -> list[dict[str, Any]]: raise UnexpectedResponse out: list[dict[str, Any]] = [] for row in data: - if isinstance(row, dict) and isinstance(row.get("id"), int) and row.get("name"): - out.append({"id": row["id"], "name": str(row["name"])}) + if not isinstance(row, dict): + continue + school_id = _json_int(row.get("id")) + name = row.get("name") + if school_id is None or not isinstance(name, str) or not name.strip(): + continue + address = row.get("addressString") + if not isinstance(address, str) or not address.strip(): + address = None + out.append({ + "id": school_id, + "name": name.strip(), + "address": address.strip() if address else None, + }) return out async def terms_search(self, group_id: int | None) -> Any: diff --git a/server/app/providers/netschool/provider.py b/server/app/providers/netschool/provider.py index d35fd6b4..b7debf1f 100644 --- a/server/app/providers/netschool/provider.py +++ b/server/app/providers/netschool/provider.py @@ -4,7 +4,9 @@ every open client runs — the children (a staff-only account with no pupil is refused here, not on the first screen later), the school year and its bounds, and the assignment-type map — sealing them into the credential so later reads -cost fewer calls and a walk can be clipped to the year. +cost fewer calls and a walk can be clipped to the year. `adopt` runs the same +bootstrap over a session the phone opened itself: no password is involved, and +``diary/init`` from this server's address is what proves the session opens here. `NetSchoolConnection` walks the diary a week at a time, because the route is a week at a time in every client, and clips each walk to the school year's bounds @@ -19,8 +21,11 @@ import logging from datetime import date as Date from datetime import datetime, timedelta +from typing import Any +from zoneinfo import ZoneInfo -from app.providers.diary.errors import SessionExpired, UnexpectedResponse +from app.providers.diary.base import Adopted, AdoptRequest +from app.providers.diary.errors import NoStudents, SessionExpired, UnexpectedResponse from app.providers.diary.models import ( AcademicPeriod, AttendanceEvent, @@ -32,7 +37,7 @@ Teacher, ) from app.providers.netschool import mapper as m -from app.providers.netschool.client import CREDENTIAL_VERSION, NetSchoolClient +from app.providers.netschool.client import CREDENTIAL_VERSION, SESSION_COOKIES, NetSchoolClient from app.providers.netschool.regions import Region from app.providers.netschool.regions import get as region_for from app.timezones import resolve @@ -48,6 +53,27 @@ def _iso(day: Date) -> str: return day.isoformat() +def zone_of(region: Region) -> ZoneInfo: + """The zone a region's diary cuts its days at: its administrative centre's. + + The one rule, read by `NetSchoolConnection.today` and — through + `NetSchoolProvider.zone` — by what the phone is told at registration, so + the phone's «today» and the server's never disagree. + """ + return resolve(region.zone) + + +def _students_of(init: Any, school: str | None) -> list[Student]: + """``diary/init``'s pupils, with any answer that is not the object it + should be read as the diary answering strangely rather than as a crash.""" + if not isinstance(init, dict): + raise UnexpectedResponse + try: + return m.to_students(init, school) + except m.UnexpectedResponseError: + raise UnexpectedResponse from None + + def _weeks(date_from: Date, date_to: Date, year_start: Date | None, year_end: Date | None): """(weekStart, weekEnd) Monday–Sunday spans covering [from, to], clipped to the school year. A week wholly outside the year yields nothing, so no call @@ -86,10 +112,7 @@ def _year(self) -> tuple[int | None, Date | None, Date | None]: async def students(self) -> list[Student]: init = await self._client.diary_init() - try: - return m.to_students(init, self._client.session.get("school")) - except m.UnexpectedResponseError: - raise UnexpectedResponse from None + return _students_of(init, self._client.session.get("school")) async def periods(self, group_id: int) -> list[AcademicPeriod]: terms = await self._client.terms_search(group_id) @@ -143,7 +166,7 @@ async def close(self) -> None: await self._client.logout() def today(self) -> Date: - return datetime.now(resolve(self._region.zone)).date() + return datetime.now(zone_of(self._region)).date() class NetSchoolProvider: @@ -165,21 +188,70 @@ async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest pro client = NetSchoolClient(region, {"v": CREDENTIAL_VERSION, "region": region.key, "school_id": request.school_id}) await client.login(request.login.strip(), request.password, request.school_id) - await self._bootstrap(client) + await self.bootstrap(client) return client.credential + async def adopt(self, request: AdoptRequest) -> Adopted: + """Keep a session the phone opened, once this server has seen it work. + + The stored session is built from the fields this code knows and no + others — ``at``, the two session cookies, and ``ver``/``time_out`` only + when present, so nothing is ever stored as ``None`` — and then the + bootstrap runs over it: ``diary/init`` is the call that proves the + session opens this account from our address, and the other three fill + what a sealed session cannot read without. Four sequential calls, + because each may rotate a cookie the next must carry. + + A region outside the allow-list, one that takes no password, or no + school is a ``ValueError``: the route refuses all three before calling. + A credential that is not the shape the route builds is + :class:`SessionExpired`, like any session this server cannot use. + """ + region = region_for(request.region) + if region is None or not region.password or request.school_id is None: + raise ValueError("netschool adoption needs an allow-listed region and a school id") + try: + handed = json.loads(request.credential) + except ValueError: + raise SessionExpired from None + if not isinstance(handed, dict): + raise SessionExpired + cookies = handed.get("cookies") + cookies = cookies if isinstance(cookies, dict) else {} + session: dict[str, Any] = { + "v": CREDENTIAL_VERSION, + "region": region.key, + "school_id": request.school_id, + "at": handed.get("at"), + "cookies": {name: cookies[name] for name in SESSION_COOKIES if cookies.get(name)}, + } + if handed.get("ver"): + session["ver"] = handed["ver"] + if handed.get("time_out"): + session["time_out"] = handed["time_out"] + # The client refuses an `at` or a cookie that cannot be sent whole + # before the first request, so nothing unchecked reaches a header. + client = NetSchoolClient(region, session) + init = await self.bootstrap(client) + school = client.session.get("school") + return Adopted( + credential=client.credential, + students=tuple(_students_of(init, school)), + school_name=school, + ) + @staticmethod - async def _bootstrap(client: NetSchoolClient) -> None: - """After the password is accepted: the children, the year and the type + async def bootstrap(client: NetSchoolClient) -> dict[str, Any]: + """After the session is accepted: the children, the year and the type map. A failure here is a real session's failure — SessionExpired-shaped - — because the password was already judged.""" + — because the password (or the phone) was already judged. + + @return the ``diary/init`` answer, so a caller that wants the pupils + does not ask for them twice. + """ init = await client.diary_init() - try: - students = m.to_students(init, None) - except m.UnexpectedResponseError: - raise UnexpectedResponse from None - if not students: - raise SessionExpired("В этой учётной записи нет ученика") + if not _students_of(init, None): + raise NoStudents year = await client.years_current() if isinstance(year, dict): client.session["year_id"] = year.get("id") @@ -200,6 +272,7 @@ async def _bootstrap(client: NetSchoolClient) -> None: for t in types if isinstance(t, dict) and t.get("id") is not None } + return init def open(self, credential: str) -> NetSchoolConnection: try: @@ -214,6 +287,12 @@ def open(self, credential: str) -> NetSchoolConnection: return _DeadConnection() # type: ignore[return-value] return NetSchoolConnection(region, session) + def zone(self, region: str | None) -> str: + """The region's zone; Moscow's for a key the allow-list does not know, + which is `app.timezones.resolve`'s own fallback.""" + known = region_for(region) + return zone_of(known).key if known is not None else resolve(None).key + def _year_date(raw) -> str | None: # noqa: ANN001 parsed = m._parse_date(raw) diff --git a/server/app/providers/netschool/regions.py b/server/app/providers/netschool/regions.py index 5f111488..9b78c5a2 100644 --- a/server/app/providers/netschool/regions.py +++ b/server/app/providers/netschool/regions.py @@ -24,9 +24,10 @@ session in clear text, so a region that serves only ``http`` (Волгоград) is left out rather than downgraded. -``ca_bundle`` is for a region that presents a non-Mozilla root (the Russian -Trusted Root): a path to a CA file to trust *for that origin only*. TLS -verification is never turned off; a region that would need that is left out. +Trust is the system's, for every origin alike. A region whose server presents +a root the system does not trust (the Russian Trusted Root) is left out too: +there is no per-origin CA here — an earlier ``ca_bundle`` field promised one +and nothing ever read it — and TLS verification is never turned off. """ from __future__ import annotations @@ -42,11 +43,11 @@ class Region: zone: str # IANA; resolved through app.timezones.resolve, which falls back rather than raises password: bool = True verified: bool = False - ca_bundle: str | None = None -# Ordered as docs/diaries.md lists them. Zones are the region's administrative -# centre; a region spanning several keeps its capital's. +# Alphabetical by title, which is the order the bot's region picker shows. Zones +# are the region's administrative centre; a region spanning several keeps its +# capital's. _REGIONS: tuple[Region, ...] = ( # ЕСИА-only since 10 Jan 2026 — never offered, refused locally. Region("altai-krai", "Алтайский край", "https://netschool.edu22.info", diff --git a/server/app/providers/petersburg/client.py b/server/app/providers/petersburg/client.py index b418856a..bf4d48d6 100644 --- a/server/app/providers/petersburg/client.py +++ b/server/app/providers/petersburg/client.py @@ -29,6 +29,7 @@ import httpx +from app.providers.diary.http import cookie_value_ok from app.providers.petersburg.exceptions import ( BadCredentials, SessionExpired, @@ -353,6 +354,13 @@ async def _get(self, path: str, params: dict[str, str]) -> dict[str, Any]: return self._unwrap(response) async def _raw(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + if self.token and not cookie_value_ok(self.token): + # A session the phone registered is checked at the door, but a + # stored credential is checked again here, whatever wrote it: a + # value holding `;` would send a second cookie of the caller's + # choosing. One that cannot be sent is a dead session, and the + # answer to that is the one every dead session gets. + raise SessionExpired() client = await shared_client() cookies = {SESSION_COOKIE: self.token} if self.token else None try: diff --git a/server/app/providers/petersburg/provider.py b/server/app/providers/petersburg/provider.py index e513a323..45334614 100644 --- a/server/app/providers/petersburg/provider.py +++ b/server/app/providers/petersburg/provider.py @@ -15,6 +15,8 @@ from datetime import date as Date +from app.providers.diary.base import Adopted, AdoptRequest +from app.providers.diary.errors import NoStudents from app.providers.diary.models import ( AcademicPeriod, AttendanceEvent, @@ -26,7 +28,7 @@ Teacher, ) from app.providers.petersburg import mapper as m -from app.providers.petersburg.client import PetersburgClient, today +from app.providers.petersburg.client import TIMEZONE, PetersburgClient, today class PetersburgConnection: @@ -95,5 +97,24 @@ async def sign_in(self, request) -> str: # noqa: ANN001 - the SignInRequest pro client = PetersburgClient() return await client.login(request.login.strip(), request.password) + async def adopt(self, request: AdoptRequest) -> Adopted: + """One read with the phone's token, from here: the pupils. + + The cheapest call that proves the session opens this account from our + address, and the one the phone would make next anyway, so its answer + rides back with the token. A 401, a 403 or a 200 of the login page is + :class:`SessionExpired` through the client's own rules — the upstream + did not take the session from here. The token the answer may have + rotated is the one kept. + """ + connection = PetersburgConnection(request.credential) + students = await connection.students() + if not students: + raise NoStudents() + return Adopted(credential=connection.credential, students=tuple(students)) + def open(self, credential: str) -> PetersburgConnection: return PetersburgConnection(credential) + + def zone(self, region: str | None) -> str: # noqa: ARG002 - one city, one zone + return TIMEZONE.key diff --git a/server/app/schemas.py b/server/app/schemas.py index 3005db7e..47403dec 100644 --- a/server/app/schemas.py +++ b/server/app/schemas.py @@ -10,9 +10,14 @@ from datetime import date as Date from datetime import datetime from datetime import time as Time -from typing import Literal +from typing import TYPE_CHECKING, Literal -from pydantic import BaseModel, Field, field_validator, model_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from app.providers.diary.http import cookie_value_ok, header_value_ok + +if TYPE_CHECKING: + from app.providers.diary.registry import Binding API_VERSION = 1 @@ -94,12 +99,47 @@ def _clean_device_name(cls, value: str | None) -> str | None: return cleaned or None +class DiaryBindingOut(BaseModel): + """Which diary a class reads, so a phone that joined it can sign in there + without searching for its school. + + Defined here rather than in the diary block below because + :class:`JoinResponse` carries it. Built only through ``of`` from + `registry.binding`, so a class bound to a region since dropped from the + allow-list, one that takes no password, or a «Сетевой город» binding with + no school all read as no binding at all — the phone is never pointed at a + diary this server would refuse. + """ + + provider: Literal["petersburg", "netschool"] + #: The allow-list key, which is the region catalog's key. ``None`` for + #: Petersburg, which is one city's server. + region: str | None = None + #: The upstream's own school id («scid»), which the phone signs in with. + school_id: int | None = None + school_name: str | None = None + + @classmethod + def of(cls, bound: Binding | None) -> DiaryBindingOut | None: + if bound is None: + return None + return cls( + provider=bound.provider.key, + region=bound.region, + school_id=bound.school_id, + school_name=bound.school_name, + ) + + class JoinResponse(BaseModel): token: str class_id: int class_name: str school: str | None = None timezone: str + #: The class's diary binding, or ``None`` when it has none this server can + #: reach. Additive, so an older phone ignores it and ``API_VERSION`` holds. + diary: DiaryBindingOut | None = None class LessonOut(BaseModel): @@ -587,10 +627,21 @@ class DiaryLoginIn(BaseModel): @field_validator("login") @classmethod def _clean_login(cls, value: str) -> str: - cleaned = _strip_control_chars(value).strip() - if len(cleaned) < 3: - raise ValueError("login must contain at least 3 usable characters") - return cleaned + return _clean_login_value(value) + + +def _clean_login_value(value: str) -> str: + """A login as the upstream will see it: printable, trimmed, three or more. + + Shared by the password sign-in and the registration of a phone's session, + because both write it to the same column and key the same corrections on + it — two cleanings of one value would file one family's corrections under + two names. + """ + cleaned = _strip_control_chars(value).strip() + if len(cleaned) < 3: + raise ValueError("login must contain at least 3 usable characters") + return cleaned class DiaryLoginOut(BaseModel): @@ -598,6 +649,7 @@ class DiaryLoginOut(BaseModel): login: str + class DiaryStudentOut(BaseModel): id: int first_name: str @@ -624,6 +676,164 @@ def of(cls, student) -> DiaryStudentOut: ) +#: Three dot-separated base64url parts, the last possibly empty: the shape of +#: the ``X-JWT-Token`` Petersburg issues. +_JWT = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*") + +#: An allow-list key's shape. Whether it is *in* the allow-list is the route's +#: question, asked before any upstream call. +_REGION_KEY = r"^[a-z0-9-]{2,32}$" + + +class PetersburgCredentialIn(BaseModel): + """The session Petersburg handed the phone: the ``X-JWT-Token`` cookie, or + ``data.token`` when the answer carried no cookie.""" + + model_config = ConfigDict(extra="forbid") + + token: str = Field(min_length=16, max_length=4096, repr=False) + + @field_validator("token") + @classmethod + def _a_jwt_that_can_be_a_cookie(cls, value: str) -> str: + # Sent back upstream as a cookie on every read, so it must be one + # cookie value and nothing more; `_raw` checks the same again. + if not _JWT.fullmatch(value) or not cookie_value_ok(value): + raise ValueError("token must be a JWT") + return value + + +class NetSchoolCookiesIn(BaseModel): + """The two session cookies «Сетевой город» sets, and no other — an unknown + name is refused rather than carried, since it would be sent on every read.""" + + model_config = ConfigDict(extra="forbid") + + NSSESSIONID: str = Field(min_length=1, max_length=128, repr=False) + ESRNSec: str | None = Field(default=None, min_length=1, max_length=2048, repr=False) + + @field_validator("NSSESSIONID", "ESRNSec") + @classmethod + def _one_cookie_value(cls, value: str | None) -> str | None: + # A `;` here would smuggle a second cookie onto every read. + if value is not None and not cookie_value_ok(value): + raise ValueError("not a cookie value") + return value + + +class NetSchoolCredentialIn(BaseModel): + """What the phone's «Сетевой город» sign-in ended holding.""" + + model_config = ConfigDict(extra="forbid") + + #: The bearer, sent in the ``at`` header, so it must be one header value. + at: str = Field(min_length=8, max_length=512, repr=False) + cookies: NetSchoolCookiesIn + #: The version the server's own sign-in keeps for the SecurityWarning + #: acknowledgement and the logout. + ver: str | None = Field(default=None, max_length=32, pattern=r"^[A-Za-z0-9._-]+$") + #: The login's ``timeOut``. Stored and read by nothing (the keep-alive has + #: a floor of its own), so any non-negative integer is taken: refusing a + #: whole session over the unit of a field nobody reads would be absurd. + time_out: int | None = Field(default=None, ge=0, le=2_147_483_647) + + @field_validator("at") + @classmethod + def _one_header_value(cls, value: str) -> str: + # A line break here would be a second header on every read. + if not header_value_ok(value): + raise ValueError("not a header value") + return value + + +class _SessionIn(BaseModel): + """What every registration carries besides the session itself. + + ``extra="forbid"`` is the rule this endpoint exists for, not tidiness: a + ``password`` key is a 422, so no client can send one here, by mistake or + otherwise. + """ + + model_config = ConfigDict(extra="forbid") + + #: What the person typed into the phone's own form. Nothing upstream + #: vouches for it; it names the session and keys the corrections, so the + #: phone sends the same string on every sign-in. + login: str = Field(min_length=3, max_length=200) + + @field_validator("login") + @classmethod + def _clean_login(cls, value: str) -> str: + return _clean_login_value(value) + + +class PetersburgSessionIn(_SessionIn): + provider: Literal["petersburg"] + credential: PetersburgCredentialIn + + +class NetSchoolSessionIn(_SessionIn): + provider: Literal["netschool"] + #: An allow-list key; one outside it, or a region that takes no password, + #: is a 422 from the route before any upstream call. + region: str = Field(pattern=_REGION_KEY) + #: The upstream school id («scid») the phone signed in with. + school_id: int = Field(ge=1, le=2_000_000_000) + credential: NetSchoolCredentialIn + + +#: The registration body, told apart by ``provider``. +DiarySessionBody = PetersburgSessionIn | NetSchoolSessionIn + + +class DiarySessionOut(DiaryLoginOut): + """Our bearer for a session the phone opened, and what the phone needs to + keep reading it. Never the upstream credential: that stays here, sealed. + + ``token`` and ``login`` sit where ``DiaryLoginOut`` has them, so an app + decodes both answers the same way. + """ + + provider: Literal["petersburg", "netschool"] + region: str | None = None + school_id: int | None = None + #: What the diary calls the school, where it says (``None`` for Petersburg). + school_name: str | None = None + #: The zone the diary cuts its days at — the same rule the server's own + #: «today» uses for this session (`services/diary.zone_for`). + zone: str + #: The pupils the validating read already fetched, so the phone does not + #: ask again straight away. + students: list[DiaryStudentOut] = Field(default_factory=list) + + +class PetersburgCapabilitiesOut(BaseModel): + """Nothing to say yet about Petersburg beyond that it is served.""" + + +class NetSchoolCapabilitiesOut(BaseModel): + #: The allow-list keys this server signs in to with a password. + regions: list[str] = Field(default_factory=list) + + +class DiaryProvidersOut(BaseModel): + petersburg: PetersburgCapabilitiesOut = Field(default_factory=PetersburgCapabilitiesOut) + netschool: NetSchoolCapabilitiesOut = Field(default_factory=NetSchoolCapabilitiesOut) + + +class DiaryCapabilitiesOut(BaseModel): + """What this server's diary can do, asked before the phone takes a password. + + ``enabled`` is false without ``DIARY_SECRET``; ``registration`` says the + server takes a session the phone opened (a server from before this answers + 404 here instead). + """ + + enabled: bool + registration: bool = True + providers: DiaryProvidersOut = Field(default_factory=DiaryProvidersOut) + + class DiaryPeriodOut(BaseModel): id: int name: str diff --git a/server/app/services/diary.py b/server/app/services/diary.py index 4f1a72a4..6b4b8193 100644 --- a/server/app/services/diary.py +++ b/server/app/services/diary.py @@ -6,30 +6,37 @@ policy rather than the upstream's behaviour: how a session is stored, when it is refreshed, and what happens when it dies. -The rule about credentials is enforced here, in one place: the password is used -once, to log in, and is never written anywhere. The upstream's own session -token is what is kept, it is refreshed in place whenever a call brings back a -newer one, and when the upstream stops accepting it the row is marked expired -and the person signs in again. That costs a login screen every few days and -buys not holding a family's password. +The rule about credentials is enforced here, in one place: the upstream's own +session is what is kept, never a password. It reaches this server one of two +ways. :func:`sign_in` takes a password, uses it once to log in and writes it +nowhere — the bot's sign-in page and ``POST /api/v1/diary/login``, which older +apps still call. :func:`adopt` takes a session the phone opened itself, +straight with the diary, so no password ever came here; it is checked with a +read of this server's own before it is kept. Either way the session is sealed, +refreshed in place whenever a call brings back a newer one, and when the +upstream stops accepting it the row is marked expired and the person signs in +again. That costs a login screen every few days and buys not holding a +family's password. """ from __future__ import annotations import hashlib import logging +from dataclasses import dataclass from datetime import UTC, datetime from datetime import date as Date +from sqlalchemy import ColumnElement, and_, func, select from sqlalchemy import delete as sa_delete -from sqlalchemy import select +from sqlalchemy import update as sa_update from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.crypto import diary_enabled, seal, unseal from app.db import rows_affected -from app.models import DiaryOverride, DiarySession -from app.providers.diary.base import SignInRequest +from app.models import DiaryOverride, DiarySession, SchoolClass +from app.providers.diary.base import AdoptRequest, SignInRequest from app.providers.diary.errors import DiaryError, SessionExpired from app.providers.diary.models import ( AcademicPeriod, @@ -41,7 +48,8 @@ Subject, Teacher, ) -from app.providers.diary.registry import PETERSBURG, provider_for +from app.providers.diary.registry import PETERSBURG, Binding, provider_for +from app.providers.diary.registry import binding as class_binding from app.security import hash_token, new_token log = logging.getLogger(__name__) @@ -65,6 +73,59 @@ def utcnow() -> datetime: return datetime.now(UTC).replace(tzinfo=None) +def zone_for(provider: str, region: str | None = None) -> str: + """The IANA zone a diary's days are cut at — Petersburg's city clock, or a + «Сетевой город» region's administrative centre. + + Asked of the provider, whose connection's ``today()`` cuts the day with + the very same rule, so what the phone is told at registration and what + this server reads as «today» for the same session cannot drift apart. + """ + impl = provider_for(provider) + if impl is None: + # A key no implementation answers. Callers validate first, so this is a + # programming error, not a user's. + raise ValueError(f"unknown diary provider {provider!r}") + return impl.zone(region) + + +async def _open_row( + session: AsyncSession, + credential: str, + *, + login: str, + provider: str, + region: str | None, + telegram_id: int | None = None, +) -> tuple[str, DiarySession]: + """Seal an upstream credential and open a session of ours on it. + + The one place a row is minted, whichever way the credential arrived, so + that «what a session holds» has one answer. Every caller has just had the + upstream accept the credential, which is what ``upstream_ok_at`` records. + + @return the token to hand the client — shown once, stored only as a hash — + and the row behind it. + """ + now = utcnow() + token = new_token() + row = DiarySession( + token_hash=hash_token(token), + # Sealed before it is ever handed to the session, so there is no path + # through this function on which the plaintext reaches the ORM. + upstream_token=seal(credential), + login=login.strip(), + provider=provider, + region=region, + telegram_id=telegram_id, + last_used_at=now, + upstream_ok_at=now, + ) + session.add(row) + await session.commit() + return token, row + + async def sign_in( session: AsyncSession, login: str, @@ -98,22 +159,119 @@ async def sign_in( login=login.strip(), password=password, region=region, school_id=school_id ) ) - - token = new_token() - row = DiarySession( - token_hash=hash_token(token), - # Sealed before it is ever handed to the session, so there is no path - # through this function on which the plaintext reaches the ORM. - upstream_token=seal(credential), - login=login.strip(), - provider=provider, - region=region, + return await _open_row( + session, credential, login=login, provider=provider, region=region, telegram_id=telegram_id, - last_used_at=utcnow(), ) - session.add(row) - await session.commit() - return token, row + + +@dataclass(frozen=True) +class Registered: + """A session the phone opened, now ours: the token to hand back once, the + row, and what the validating read already fetched.""" + + token: str + row: DiarySession + students: list[Student] + school_name: str | None + + +async def adopt( + session: AsyncSession, + *, + provider: str, + login: str, + credential: str, + region: str | None = None, + school_id: int | None = None, +) -> Registered: + """Keep a session the phone opened itself, once this server has seen it work. + + The password never came here: the phone signed in with the diary directly + and hands over only what the diary gave it. The provider reads with it from + this server's address — that read is the whole check, since a session the + upstream will not take from here is worth nothing to keep — and what it + hands back (possibly rotated) is what is sealed. + + ``login`` is what the person typed on the phone. Nothing upstream vouches + for it; it names the row and keys the corrections (:func:`owner_key`), + which every route reaches only through a pupil this session can see. + + The row carries no Telegram account and no class: a phone's session is not + the bot's, and linking the two is deliberately left for later. + """ + # Before the upstream call, for `sign_in`'s reason: without a key the + # answer has nowhere to go, and a read made to throw it away is a read + # made from our address for nothing. + if not diary_enabled(): + raise DiaryDisabled("DIARY_SECRET is not configured") + + impl = provider_for(provider) + if impl is None: + raise ValueError(f"unknown diary provider {provider!r}") + + adopted = await impl.adopt( + AdoptRequest(credential=credential, region=region, school_id=school_id) + ) + token, row = await _open_row( + session, adopted.credential, login=login, provider=provider, region=region + ) + return Registered( + token=token, row=row, students=list(adopted.students), school_name=adopted.school_name + ) + + +def reads_binding(bound: Binding) -> ColumnElement[bool]: + """Whether a session row reads the diary a class is bound to. + + The one clause for it, used by the bot's lookup and by the expiry on + rebinding, so «which sessions belong to this binding» cannot be answered + two ways. Petersburg is one server, so the provider is enough — and a row + with no provider is Petersburg, which is what the column meant before it + existed. A many-server provider must match the region too: a «Сетевой + город» session is a session with one regional server, and read against + another region's binding it would talk to the diary the class has left. + + Both halves are written with ``coalesce`` so the clause is never SQL's + NULL, which ``NOT`` would leave NULL and so match nothing. + """ + provider = func.coalesce(DiarySession.provider, PETERSBURG) + if bound.region is None: + return provider == bound.provider.key + return and_( + provider == bound.provider.key, + func.coalesce(DiarySession.region, "") == bound.region, + ) + + +async def expire_off_binding(session: AsyncSession, school_class: SchoolClass) -> int: + """Expire the class's live sessions its current binding no longer reads. + + Called when a class is bound, before the caller commits, so the binding + and the expiry land together. The bot already stops *reading* such a row + (:func:`reads_binding`); expiring it as well is what stops the keep-alive + pinging a regional server the class has left, and what the purge then + sweeps. The same region again, or another school in it, keeps them: a + session is an account on the region's server, not on one school. + + Not called on unbinding. That takes the door away and nothing else — the + sessions stay their owners' until they sign out, as the bot promises. + + @return how many rows were expired. Does not commit. + """ + bound = class_binding(school_class) + if bound is None: + return 0 + result = await session.execute( + sa_update(DiarySession) + .where( + DiarySession.class_id == school_class.id, + DiarySession.expired_at.is_(None), + ~reads_binding(bound), + ) + .values(expired_at=utcnow()) + ) + return rows_affected(result) def upstream_of(row: DiarySession) -> str | None: diff --git a/server/app/services/diary_keepalive.py b/server/app/services/diary_keepalive.py index 90124777..b31bd541 100644 --- a/server/app/services/diary_keepalive.py +++ b/server/app/services/diary_keepalive.py @@ -7,7 +7,7 @@ GitHub's fallback clock is too sparse, and a session goes dead between two of its ticks. -Three rules the review nailed down: +Four rules the review nailed down: - **Never touch ``last_used_at``.** Pinging must not look like the family using the session, or the 30-day purge of one nobody opens would never fire. @@ -19,7 +19,15 @@ database transaction closed; the results are written back one row at a time with a guarded ``UPDATE`` that matches nothing if the row was signed out or its credential rotated meanwhile — so a vanished or changed row is skipped, - not a lost update and not a crash. + not a lost update and not a crash. The guard compares the sealed blob read + at the claim with the one stored now: that is exact, although sealing is not + deterministic, because a rotation writes a new blob and nothing else does. +- **An origin that refuses our address is left alone for the rest of the + tick.** A regional server dropping this deployment's address answers every + session the same way, so after the first :class:`AddressRefused` the claims + on that origin not yet started are skipped rather than walked into the same + wall — at most :data:`KEEPALIVE_CONCURRENCY` pings are wasted per origin per + tick, the ones already in flight. """ from __future__ import annotations @@ -34,8 +42,9 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.crypto import diary_enabled, seal, unseal +from app.db import rows_affected from app.models import DiarySession -from app.providers.diary.errors import SessionExpired +from app.providers.diary.errors import AddressRefused, SessionExpired from app.providers.diary.registry import NETSCHOOL, provider_for log = logging.getLogger(__name__) @@ -59,17 +68,25 @@ def _now() -> datetime: @dataclass class _Claim: - """One row claimed for a ping, read out as plain values.""" + """One row claimed for a ping, read out as plain values. + + ``credential`` is the **sealed** blob as it stood at the claim; ``region`` + names the origin, which is what the breaker groups by. + """ id: int provider: str + region: str | None credential: str @dataclass class _Result: id: int - outcome: str # "ok" | "expired" | "skip" + outcome: str # "ok" | "expired" | "skip" | "refused" + #: The sealed blob read at the claim, so the write-back matches only a row + #: whose credential has not been rotated since. + claimed: str credential: str | None = None @@ -120,20 +137,46 @@ async def _claim(session: AsyncSession) -> list[_Claim]: claims: list[_Claim] = [] for row in rows: row.keepalive_attempted_at = now - claims.append(_Claim(id=row.id, provider=row.provider or "", credential=row.upstream_token)) + claims.append( + _Claim( + id=row.id, + provider=row.provider or "", + region=row.region, + credential=row.upstream_token, + ) + ) await session.commit() return claims async def _ping_all(claims: list[_Claim], *, loop, started: float) -> list[_Result]: - """Ping every claimed session, with no database session held open.""" + """Ping every claimed session, with no database session held open. + + ``refused`` is the per-tick breaker: an origin lands in it on its first + :class:`AddressRefused`, and a claim on it that has not started yet is + skipped — checked after the semaphore, so a claim that waited behind the + first refusal sees it. The row stays claimed, so it goes to the back of + the queue like any other skipped one. + """ semaphore = asyncio.Semaphore(KEEPALIVE_CONCURRENCY) + refused: set[str] = set() async def one(claim: _Claim) -> _Result: if loop.time() - started > KEEPALIVE_DEADLINE_SECONDS: - return _Result(claim.id, "skip") # out of budget; first next tick + return _Result(claim.id, "skip", claim.credential) # out of budget; first next tick async with semaphore: - return await _ping(claim) + if claim.region is not None and claim.region in refused: + return _Result(claim.id, "skip", claim.credential) + result = await _ping(claim) + if result.outcome == "refused" and claim.region is not None: + if claim.region not in refused: + log.warning( + "diary keep-alive: %s refuses this address; " + "its other sessions wait for the next tick", + claim.region, + ) + refused.add(claim.region) + return result return list(await asyncio.gather(*(one(c) for c in claims))) @@ -144,25 +187,41 @@ async def _ping(claim: _Claim) -> _Result: if provider is None or not plain: # A key rotation or an unknown provider: leave it for a real request to # expire when somebody actually asks, rather than expiring en masse. - return _Result(claim.id, "skip") + return _Result(claim.id, "skip", claim.credential) connection = provider.open(plain) + before = connection.credential try: await connection.keep_alive() except SessionExpired: - return _Result(claim.id, "expired") - except Exception: # noqa: BLE001 - a down or blocking origin is left as-is + return _Result(claim.id, "expired", claim.credential) + except AddressRefused: + # Before the broad catch below, which would file it as one more + # failed ping: this one says something about every session on the + # origin, and `_ping_all` acts on it. + return _Result(claim.id, "refused", claim.credential) + except Exception: # noqa: BLE001 - a down origin is left as-is log.info("diary keep-alive ping failed for session %s", claim.id, exc_info=True) - return _Result(claim.id, "skip") - return _Result(claim.id, "ok", credential=connection.credential) + return _Result(claim.id, "skip", claim.credential) + # Re-sealed only when the ping rotated something: sealing is not + # deterministic, so writing back an unchanged session would churn the + # stored blob on every tick for nothing. Compared with what the + # connection itself serialised before the ping, not with the stored text, + # so a difference in spelling is not taken for a rotation. + rotated = connection.credential if connection.credential != before else None + return _Result(claim.id, "ok", claim.credential, credential=rotated) async def _apply(session: AsyncSession, results: list[_Result]) -> tuple[int, int]: """Write each ping's outcome with a guarded UPDATE, then commit once. - Each UPDATE matches on what was read, so a row signed out or rotated between - the claim and now simply matches nothing and is skipped — no lost update, no - StaleDataError. + Each UPDATE matches on what was read — the row, still live, still holding + the sealed credential the claim read — so a row signed out or rotated + between the claim and now simply matches nothing and is skipped. Without + the credential in the guard, a read that rotated the cookies while the ping + was in flight had them overwritten with the older ones, and the next read + was refused; and a ping that failed on the old credential expired a row + whose new one was fine. """ now = _now() kept = lost = 0 @@ -171,18 +230,28 @@ async def _apply(session: AsyncSession, results: list[_Result]) -> tuple[int, in values = {"kept_alive_at": now, "upstream_ok_at": now} if result.credential: values["upstream_token"] = seal(result.credential) - await session.execute( + written = await session.execute( sa_update(DiarySession) - .where(DiarySession.id == result.id, DiarySession.expired_at.is_(None)) + .where( + DiarySession.id == result.id, + DiarySession.expired_at.is_(None), + DiarySession.upstream_token == result.claimed, + ) .values(**values) ) - kept += 1 + kept += rows_affected(written) elif result.outcome == "expired": - await session.execute( + written = await session.execute( sa_update(DiarySession) - .where(DiarySession.id == result.id, DiarySession.expired_at.is_(None)) + .where( + DiarySession.id == result.id, + DiarySession.expired_at.is_(None), + DiarySession.upstream_token == result.claimed, + ) .values(expired_at=now) ) - lost += 1 + # Counted by what was written: a row the guard skipped was not + # lost, and the tick's report should not say it was. + lost += rows_affected(written) await session.commit() return kept, lost diff --git a/server/tests/test_bot_diary.py b/server/tests/test_bot_diary.py index 2f704c99..8ff1505e 100644 --- a/server/tests/test_bot_diary.py +++ b/server/tests/test_bot_diary.py @@ -90,6 +90,38 @@ async def test_a_session_does_not_cross_between_classes(session, school_class): assert await handlers._session_for(session, MINE, other) is not None +async def test_a_session_on_the_region_the_class_left_is_not_read(session, school_class): + """A class moved from samara's «Сетевой город» server to amur's. The lookup + matched the provider alone, so «📒 Мой дневник» went on reading samara — a + diary the class had left, with a credential for another server. The region + is part of what a session reads now.""" + school_class.diary_provider = "netschool" + school_class.diary_region = "amur" + school_class.diary_school_id = 11 + await session.commit() + + def netschool_row(region: str, token: str) -> DiarySession: + return DiarySession( + token_hash=hash_token(token), + upstream_token=seal("upstream"), + login="parent@example.com", + telegram_id=MINE, + class_id=school_class.id, + provider="netschool", + region=region, + ) + + session.add(netschool_row("samara", "left-behind")) + await session.commit() + assert await handlers._session_for(session, MINE, school_class) is None + + current = netschool_row("amur", "current") + session.add(current) + await session.commit() + found = await handlers._session_for(session, MINE, school_class) + assert found is not None and found.id == current.id + + async def test_a_session_whose_key_no_longer_opens_it_is_dead(session, school_class): await _bind(session, school_class) row = await _open_session(session, telegram_id=MINE, class_id=school_class.id) diff --git a/server/tests/test_bot_manage.py b/server/tests/test_bot_manage.py index d0478e31..873821e6 100644 --- a/server/tests/test_bot_manage.py +++ b/server/tests/test_bot_manage.py @@ -137,6 +137,7 @@ DayKind, DayOverride, DeviceToken, + DiarySession, Homework, JoinMode, LessonOverride, @@ -149,6 +150,7 @@ TimetableEntry, WeekParity, ) +from app.security import hash_token, new_token from app.services import audit # -------------------------------------------------------------------------- @@ -2543,6 +2545,135 @@ async def test_an_editor_cannot_walk_the_netschool_flow(session, school_class, m assert school_class.diary_provider is None +# -------------------------------------------------------------------------- +# Rebinding: the sessions a class's new binding no longer reads +# -------------------------------------------------------------------------- + + +async def _member_session( + session, school_class, *, provider: str | None, region: str | None, telegram_id: int = 42 +) -> DiarySession: + from app.crypto import seal + + row = DiarySession( + token_hash=hash_token(new_token()), + upstream_token=seal("upstream"), + login=f"user{telegram_id}@example.com", + telegram_id=telegram_id, + class_id=school_class.id, + provider=provider, + region=region, + ) + session.add(row) + await session.commit() + return row + + +async def _pick_school(session, school_class, region: str, school_id: int = 11) -> None: + callback = FakeCallback(message=FakeEditable()) + state = FakeState( + data={ + "diary_region": region, + "diary_class_id": school_class.id, + "diary_schools": [{"id": school_id, "name": "Гимназия № 1"}], + } + ) + await class_diary_school(callback, SimpleNamespace(value=0), session, Role.ADMIN, state) + assert school_class.diary_region == region + + +async def test_binding_another_region_expires_the_old_sessions(session, school_class): + """A class moved from samara's server to amur's. Its members' samara + sessions read a diary the class has left: the bot matched the provider + alone and went on reading samara, and the keep-alive went on pinging it.""" + school_class.diary_provider = "netschool" + school_class.diary_region = "samara" + school_class.diary_school_id = 5 + await session.commit() + old = await _member_session(session, school_class, provider="netschool", region="samara") + + await _pick_school(session, school_class, "amur") + + await session.refresh(old) + assert old.expired_at is not None + + +async def test_binding_the_same_region_again_keeps_them(session, school_class): + """Another school on the same regional server: a session is an account on + that server, not on one school, so it goes on reading.""" + school_class.diary_provider = "netschool" + school_class.diary_region = "amur" + school_class.diary_school_id = 5 + await session.commit() + kept = await _member_session(session, school_class, provider="netschool", region="amur") + + await _pick_school(session, school_class, "amur", school_id=11) + + await session.refresh(kept) + assert kept.expired_at is None + + +async def test_a_legacy_petersburg_row_is_expired_when_the_class_moves_to_netschool( + session, school_class +): + """A row from before the provider column has NULL there, which means + Petersburg. Written naively, «not this binding» is NULL for it in SQL and + matches nothing, and the row would have been left reading Petersburg.""" + school_class.diary_provider = "petersburg" + await session.commit() + legacy = await _member_session(session, school_class, provider=None, region=None) + + await _pick_school(session, school_class, "amur") + + await session.refresh(legacy) + assert legacy.expired_at is not None + + +async def test_binding_petersburg_expires_the_netschool_sessions_and_nothing_else( + session, school_class +): + other_class = SchoolClass(name="10Б", join_code="OTHER10") + session.add(other_class) + await session.commit() + netschool = await _member_session(session, school_class, provider="netschool", region="amur") + petersburg = await _member_session( + session, school_class, provider="petersburg", region=None, telegram_id=43 + ) + legacy = await _member_session( + session, school_class, provider=None, region=None, telegram_id=44 + ) + elsewhere = await _member_session(session, other_class, provider="netschool", region="amur") + + callback = FakeCallback(message=FakeEditable()) + await class_diary_provider( + callback, SimpleNamespace(value="petersburg"), session, school_class, Role.ADMIN + ) + + for row in (netschool, petersburg, legacy, elsewhere): + await session.refresh(row) + assert netschool.expired_at is not None + assert petersburg.expired_at is None + assert legacy.expired_at is None + # Another class's binding did not change, so neither did its sessions. + assert elsewhere.expired_at is None + + +async def test_unbinding_expires_nothing(session, school_class): + """Unbinding takes the door away and nothing else, as the bot promises: + the sessions stay their owners' until they sign out.""" + school_class.diary_provider = "netschool" + school_class.diary_region = "amur" + school_class.diary_school_id = 5 + await session.commit() + row = await _member_session(session, school_class, provider="netschool", region="amur") + + await class_diary_bind(FakeCallback(message=FakeEditable()), session, school_class, Role.ADMIN) + + await session.refresh(row) + assert school_class.diary_provider is None + assert row.expired_at is None + + async def test_the_switch_screen_needs_somewhere_to_switch_to(session, school_class): callback = FakeCallback(message=FakeEditable()) await class_switch(callback, session, school_class, Role.ADMIN) diff --git a/server/tests/test_diary_client.py b/server/tests/test_diary_client.py index 27091fc6..b7b15373 100644 --- a/server/tests/test_diary_client.py +++ b/server/tests/test_diary_client.py @@ -284,3 +284,30 @@ async def test_one_row_of_the_wrong_shape_among_several_is_not_shouted_about( assert items == [{"id": 1}, {"id": 3}] assert caplog.records == [] + + +@pytest.mark.parametrize( + "stored", + ["jwt.part.sig; X-Other=forged", "jwt.part.sig\r\nX-Evil: 1", "jwt part sig"], + ids=["semicolon", "line-break", "space"], +) +async def test_a_stored_token_that_is_not_a_cookie_value_is_never_sent(monkeypatch, stored): + """The phone now hands this server a token it received itself. The route + checks it at the door; the client checks again before every call, so a + value that would become a second cookie never leaves, whatever wrote it — + and reads as the dead session it is.""" + sent: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={"data": {"items": []}}) + + async def shared(): + return httpx.AsyncClient( + base_url=provider_client.BASE_URL, transport=httpx.MockTransport(handler) + ) + + monkeypatch.setattr(provider_client, "shared_client", shared) + with pytest.raises(SessionExpired): + await provider_client.PetersburgClient(stored).children() + assert sent == [] diff --git a/server/tests/test_diary_keepalive.py b/server/tests/test_diary_keepalive.py index c23953c6..1d6c6fce 100644 --- a/server/tests/test_diary_keepalive.py +++ b/server/tests/test_diary_keepalive.py @@ -12,6 +12,7 @@ import json from app.crypto import seal +from app.db import SessionLocal from app.models import DiarySession from app.providers.diary.errors import SessionExpired, UpstreamUnavailable from app.security import hash_token, new_token @@ -124,3 +125,124 @@ async def test_the_keep_alive_does_nothing_without_a_diary_secret(session, monke await session.commit() monkeypatch.setattr(diary_keepalive, "diary_enabled", lambda: False) assert await diary_keepalive.keep_alive(session) == (0, 0) + + +async def test_an_origin_that_refuses_us_is_not_pinged_again_in_the_same_tick( + session, monkeypatch +): + """A regional server that drops this address answers every session on it + the same way. After the first refusal the rest of that origin's claims are + skipped for the tick — at most the pings already in flight are wasted — + while another origin's sessions are pinged as usual.""" + from app.providers.diary.errors import AddressRefused + + amur = seal(json.dumps({"v": 1, "region": "amur", "school_id": 1, "at": "at", "cookies": {}})) + refusing = [_netschool_row(region="zabaikalsky") for _ in range(20)] + elsewhere = [_netschool_row(region="amur", upstream_token=amur) for _ in range(3)] + session.add_all(refusing + elsewhere) + await session.commit() + + pinged: list[str] = [] + + async def ping(self): + region = self._region.key + pinged.append(region) + if region == "zabaikalsky": + raise AddressRefused + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", ping + ) + kept, lost = await diary_keepalive.keep_alive(session) + + assert (kept, lost) == (3, 0) + assert pinged.count("amur") == 3 + assert 1 <= pinged.count("zabaikalsky") <= diary_keepalive.KEEPALIVE_CONCURRENCY + for row in refusing: + await session.refresh(row) + # Left alone, not expired: the address is refused, not the session. + assert row.expired_at is None + assert row.keepalive_attempted_at is not None + + +async def test_a_credential_rotated_during_the_ping_is_not_overwritten(session, monkeypatch): + """A read rotated the cookies while the ping was in flight. The ping's + write-back used to match on the row alone and put the older credential + back over the newer one — and the next read was refused with it.""" + row = _netschool_row() + session.add(row) + await session.commit() + rotated = seal(json.dumps({"v": 1, "region": "zabaikalsky", "school_id": 1, + "at": "rotated-by-a-read", "cookies": {}, "year_id": 2026})) + + async def ping_while_a_read_rotates(self): + async with SessionLocal() as other: + fresh = await other.get(DiarySession, row.id) + fresh.upstream_token = rotated + await other.commit() + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", + ping_while_a_read_rotates, + ) + kept, lost = await diary_keepalive.keep_alive(session) + + async with SessionLocal() as check: + stored = await check.get(DiarySession, row.id) + assert stored.upstream_token == rotated + assert (kept, lost) == (0, 0) + + +async def test_a_session_used_during_the_ping_is_not_expired_by_it(session, monkeypatch): + """The ping failed on the credential it read; a read meanwhile rotated to + a newer one that works. Expiring the row over the old one's failure would + sign the family out of a session that is fine.""" + row = _netschool_row() + session.add(row) + await session.commit() + + async def dead_but_rotated_meanwhile(self): + async with SessionLocal() as other: + fresh = await other.get(DiarySession, row.id) + fresh.upstream_token = seal(json.dumps( + {"v": 1, "region": "zabaikalsky", "school_id": 1, "at": "newer", + "cookies": {}, "year_id": 2026})) + await other.commit() + raise SessionExpired + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", + dead_but_rotated_meanwhile, + ) + kept, lost = await diary_keepalive.keep_alive(session) + + async with SessionLocal() as check: + stored = await check.get(DiarySession, row.id) + assert stored.expired_at is None + assert (kept, lost) == (0, 0) + + +async def test_a_ping_rewrites_the_credential_only_when_it_rotated(session, monkeypatch): + """A ping that rotated the session stores the new one; a ping that did not + leaves the stored blob exactly as it was, rather than re-sealing the same + session into a new blob every tick.""" + from app.crypto import unseal + + quiet = _netschool_row() + rotating = _netschool_row(upstream_token=seal(json.dumps( + {"v": 1, "region": "zabaikalsky", "school_id": 1, "at": "rotate-me", "cookies": {}}))) + session.add_all([quiet, rotating]) + await session.commit() + quiet_blob = quiet.upstream_token + + async def ping(self): + if self._client.session["at"] == "rotate-me": + self._client.session["at"] = "rotated" + + monkeypatch.setattr("app.providers.netschool.provider.NetSchoolConnection.keep_alive", ping) + assert await diary_keepalive.keep_alive(session) == (2, 0) + + async with SessionLocal() as check: + assert (await check.get(DiarySession, quiet.id)).upstream_token == quiet_blob + stored = (await check.get(DiarySession, rotating.id)).upstream_token + assert json.loads(unseal(stored))["at"] == "rotated" diff --git a/server/tests/test_diary_protocol_vectors.py b/server/tests/test_diary_protocol_vectors.py new file mode 100644 index 00000000..b4a48a13 --- /dev/null +++ b/server/tests/test_diary_protocol_vectors.py @@ -0,0 +1,411 @@ +"""The shared known answers for both diary sign-ins, run through the real code. + +`tests/vectors/diary_protocol.json` is read by this file and by the phone's +`DiaryProtocolVectorsTest`, because the sign-in protocol of each diary now +lives in two codebases: the phone signs in itself and hands the session over, +and this server signs in with a password on the bot's page and on the older +``/login``. Two implementations of one protocol drift apart within a month +unless something holds them to one set of answers; the file is that set, and +neither implementation is the oracle. + +Every case goes through the real client over ``httpx.MockTransport`` — not a +re-implementation of its rules — so a case that fails here is a behaviour of +the code, not of the test. A rule that is not a request (the password hash, +which role is picked) is asked of the function that implements it. + +What a failure here means: the Python side changed and the file did not, or +the reverse. Change them together, and the phone's test with them. +""" + +from __future__ import annotations + +import json +import re +from datetime import timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest + +from app.api import cron +from app.providers.diary import http as diary_http +from app.providers.diary.errors import ( + AddressRefused, + BadCredentials, + DiaryError, + SessionExpired, + SignInUnsupported, + UnexpectedResponse, + UpstreamUnavailable, +) +from app.providers.netschool import client as nsclient +from app.providers.netschool.regions import get as region_for +from app.providers.petersburg import client as pbclient + +VECTORS: dict[str, Any] = json.loads( + (Path(__file__).parent / "vectors" / "diary_protocol.json").read_text(encoding="utf-8") +) +NETSCHOOL = VECTORS["netschool"] +FLOW = NETSCHOOL["flow"] +PETERSBURG = VECTORS["petersburg"] +REGION = region_for("zabaikalsky") + + +@pytest.fixture(autouse=True) +def fresh_database(): + """Nothing here touches the database, so the conftest fixture of this name + — a drop and a create of every table, before each of the hundred cases + below — is overridden with nothing. It was most of this file's runtime.""" + yield + + +def _kind(failure: DiaryError) -> str: + """The vectors' name for a failure. Most specific first: an + ``AddressRefused`` is an ``UpstreamUnavailable`` too, and the two must not + be confused — one is «try later», the other «not from this address».""" + for cls, name in ( + (AddressRefused, "address_refused"), + (UpstreamUnavailable, "unavailable"), + (BadCredentials, "bad_credentials"), + (SignInUnsupported, "sign_in_unsupported"), + (UnexpectedResponse, "unexpected"), + (SessionExpired, "session_expired"), + ): + if isinstance(failure, cls): + return name + return type(failure).__name__ + + +def _json(status: int, body: Any) -> httpx.Response: + return httpx.Response(status, json=body) + + +def _serve_netschool(monkeypatch, handler) -> None: + """The «Сетевой город» client's pooled client, replaced by one on a mock + transport — built like the real one, carrying no cookies of its own.""" + + async def shared() -> httpx.AsyncClient: + return httpx.AsyncClient( + transport=httpx.MockTransport(handler), + cookies=diary_http.NoCookieJar(), + follow_redirects=False, + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + + +async def _netschool_sign_in( + monkeypatch, + *, + logindata: Any = None, + getdata: Any = None, + login_answers: list[tuple[int, Any]] | None = None, +) -> tuple[dict[str, Any] | DiaryError, list[httpx.Request]]: + """One whole password sign-in through `NetSchoolClient.login`. + + The flow's own answers stand in for whatever the case does not replace; + `/webapi/login` answers the listed answers in order, then a plain success. + Only the diary's error family is caught: anything else escaping is exactly + the defect these cases exist to catch, and fails the test on its own. + """ + seen: list[httpx.Request] = [] + answers = list(login_answers or []) + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + path = request.url.path + if path == "/webapi/logindata": + return _json(200, FLOW["logindata"] if logindata is None else logindata) + if path == "/webapi/auth/getdata": + return _json(200, FLOW["getdata"] if getdata is None else getdata) + if path == "/webapi/login": + status, body = answers.pop(0) if answers else (200, {"at": "after-role"}) + return _json(status, body) + return _json(404, {}) + + _serve_netschool(monkeypatch, handler) + client = nsclient.NetSchoolClient(REGION, {"v": 1, "region": REGION.key}) + try: + await client.login(FLOW["login"], FLOW["password"], FLOW["school_id"]) + except DiaryError as failure: + return failure, seen + return client.session, seen + + +def _forms(seen: list[httpx.Request], path: str) -> list[dict[str, str]]: + """The decoded form of every request to ``path`` — decoded, because httpx + and OkHttp write the same fields with different bytes.""" + from urllib.parse import parse_qsl + + return [ + dict(parse_qsl(request.content.decode(), keep_blank_values=True)) + for request in seen + if request.url.path == path + ] + + +# -------------------------------------------------------------------------- +# «Сетевой город» +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize("case", NETSCHOOL["hash"], ids=lambda c: repr(c["password"])) +def test_netschool_password_hashes_match_the_vectors(case): + if "failure" in case: + with pytest.raises(DiaryError) as raised: + nsclient._hash_password(case["salt"], case["password"]) + assert _kind(raised.value) == case["failure"] + # And the failure carries nothing of what was typed. + assert case["password"] not in str(raised.value) + return + assert nsclient._hash_password(case["salt"], case["password"]) == (case["pw"], case["pw2"]) + + +@pytest.mark.parametrize("case", NETSCHOOL["logindata_cases"], ids=lambda c: json.dumps(c["body"])) +async def test_netschool_logindata_answers_match_the_vectors(monkeypatch, case): + def handler(request: httpx.Request) -> httpx.Response: + return _json(200, case["body"]) + + _serve_netschool(monkeypatch, handler) + client = nsclient.NetSchoolClient(REGION) + try: + await client.login_allowed() + except DiaryError as failure: + assert _kind(failure) == case["expect"] + return + assert case["expect"] == "ok" + if case["ver"] is None: + # Never stored as None: that is what was sent as the word "None". + assert "ver" not in client.session + else: + assert client.session["ver"] == case["ver"] + + +@pytest.mark.parametrize("case", NETSCHOOL["getdata_cases"], ids=lambda c: json.dumps(c["body"])) +async def test_netschool_getdata_answers_match_the_vectors(monkeypatch, case): + outcome, seen = await _netschool_sign_in( + monkeypatch, getdata=case["body"], login_answers=[(200, {"at": "x"})] + ) + if case["expect"] != "ok": + assert isinstance(outcome, DiaryError), outcome + assert _kind(outcome) == case["expect"] + # Nothing that failed at getdata may have posted a password. + assert _forms(seen, "/webapi/login") == [] + return + assert not isinstance(outcome, DiaryError), outcome + (form,) = _forms(seen, "/webapi/login") + assert list(form) == NETSCHOOL["login_form_fields"] + for field, value in case["form"].items(): + assert form[field] == value + + +@pytest.mark.parametrize( + "case", NETSCHOOL["login_cases"], ids=lambda c: f"{c['status']}-{json.dumps(c['body'])}" +) +async def test_netschool_sign_in_answers_match_the_vectors(monkeypatch, case): + answer = (case["status"], case["body"]) + answers = [(200, FLOW["role_question"]), answer] if case.get("tried_role") else [answer] + outcome, seen = await _netschool_sign_in(monkeypatch, login_answers=answers) + expect = case["expect"] + + if "failure" in expect: + assert isinstance(outcome, DiaryError), outcome + assert _kind(outcome) == expect["failure"] + if "message" in expect: + wanted = expect["message"] or BadCredentials.message + assert outcome.message == wanted + return + + assert not isinstance(outcome, DiaryError), outcome + if expect.get("needs_role"): + # Re-run with a fresh salt, and the role picked from the answer. + assert len(_forms(seen, "/webapi/auth/getdata")) == 2 + first, second = _forms(seen, "/webapi/login") + assert "rolegroup" not in first + assert second["rolegroup"] == expect["rolegroup"] + assert outcome["at"] == "after-role" + return + assert outcome["at"] == expect["at"] + assert outcome.get("time_out") == expect["time_out"] + + +def test_the_login_form_carries_exactly_the_vector_fields(): + """A role retry adds ``rolegroup``; everything else is exactly this list.""" + assert NETSCHOOL["login_form_fields"] == ["loginType", "scid", "un", "pw", "pw2", "lt", "ver"] + + +@pytest.mark.parametrize("case", NETSCHOOL["role_pick"], ids=lambda c: json.dumps(c["body"])) +def test_netschool_role_pick_matches_the_vectors(case): + assert nsclient.NetSchoolClient._pick_parent_role(case["body"]) == case["expect"] + + +@pytest.mark.parametrize( + "case", NETSCHOOL["refusal"]["cases"], ids=lambda c: f"{c['status']}-{c['body']}" +) +async def test_netschool_refusal_rule_matches_the_vectors(monkeypatch, case): + assert list(nsclient._WAF_MARKERS) == NETSCHOOL["refusal"]["markers"] + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + case["status"], + content=case["body"].encode(), + headers={"content-type": case["content_type"]}, + ) + + _serve_netschool(monkeypatch, handler) + client = nsclient.NetSchoolClient(REGION) + try: + await client._send("GET", "/webapi/logindata", auth=False) + except AddressRefused: + refused = True + else: + refused = False + assert refused is case["refused"] + + +@pytest.mark.parametrize( + "case", NETSCHOOL["schools_search"]["query_cases"], ids=lambda c: c["query"][:12] +) +async def test_netschool_school_search_cuts_the_query_like_the_vectors(monkeypatch, case): + search = NETSCHOOL["schools_search"] + sent: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == search["path"] + # No session rides a search: the server answers it to the login page. + assert "at" not in request.headers and "cookie" not in request.headers + sent.append(request.url.params[search["query_parameter"]]) + return _json(200, []) + + _serve_netschool(monkeypatch, handler) + await nsclient.NetSchoolClient(REGION).schools_search(case["query"]) + assert sent == [case["sent"]] + assert len(case["sent"]) <= search["query_cut_code_points"] + + +@pytest.mark.parametrize( + "case", NETSCHOOL["schools_search"]["cases"], ids=lambda c: json.dumps(c["body"])[:40] +) +async def test_netschool_school_search_rows_match_the_vectors(monkeypatch, case): + def handler(request: httpx.Request) -> httpx.Response: + return _json(200, case["body"]) + + _serve_netschool(monkeypatch, handler) + try: + rows = await nsclient.NetSchoolClient(REGION).schools_search("школа") + except DiaryError as failure: + assert _kind(failure) == case["expect"] + return + assert rows == case["expect"] + + +def test_the_session_cookies_are_the_vectors(): + assert list(nsclient.SESSION_COOKIES) == NETSCHOOL["session_cookies"] + + +# -------------------------------------------------------------------------- +# Petersburg +# -------------------------------------------------------------------------- + + +async def _petersburg_login(monkeypatch, case) -> tuple[str | DiaryError, list[httpx.Request]]: + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + headers = [("content-type", case["content_type"])] + headers += [("set-cookie", cookie) for cookie in case["set_cookie"]] + return httpx.Response(case["status"], headers=headers, content=case["body"].encode()) + + async def shared() -> httpx.AsyncClient: + return httpx.AsyncClient( + base_url=pbclient.BASE_URL, + transport=httpx.MockTransport(handler), + cookies=pbclient._NoCookieJar(), + headers={"user-agent": pbclient.USER_AGENT}, + ) + + monkeypatch.setattr(pbclient, "shared_client", shared) + try: + return await pbclient.PetersburgClient().login("parent@example.com", "secret"), seen + except DiaryError as failure: + return failure, seen + + +@pytest.mark.parametrize("case", PETERSBURG["login_cases"], ids=lambda c: c["name"]) +async def test_petersburg_login_answers_match_the_vectors(monkeypatch, case): + outcome, seen = await _petersburg_login(monkeypatch, case) + + (request,) = seen + assert request.url.path == PETERSBURG["login_path"] + assert "cookie" not in request.headers # nobody is signed in yet + sent = json.loads(request.content) + assert set(sent) == {*PETERSBURG["login_fields"], "login", "password"} + for field, value in PETERSBURG["login_fields"].items(): + assert sent[field] == value + + expect = case["expect"] + if "failure" in expect: + assert isinstance(outcome, DiaryError), outcome + assert _kind(outcome) == expect["failure"] + else: + assert outcome == expect["token"] + + +@pytest.mark.parametrize( + "case", + [c for c in PETERSBURG["login_cases"] if c["set_cookie"]], + ids=lambda c: c["name"], +) +def test_session_cookie_rule_matches_the_vectors(case): + """Both readers of a session cookie — Petersburg's own and the shared one + «Сетевой город» uses — agree with the vectors: the cookie when the answer + carries a live one, nothing (so the body wins) when it carries a deletion.""" + response = httpx.Response( + case["status"], + headers=[("set-cookie", cookie) for cookie in case["set_cookie"]], + request=httpx.Request("POST", PETERSBURG["origin"] + PETERSBURG["login_path"]), + ) + token = case["expect"]["token"] + wanted = None if token == "body" else token + name = PETERSBURG["session_cookie"] + assert pbclient._session_cookie(response) == wanted + assert diary_http.session_cookie(response, name) == wanted + + +# -------------------------------------------------------------------------- +# What both sides share +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize("case", VECTORS["credential"]["cases"], ids=lambda c: repr(c["value"])) +def test_credential_charset_rule_matches_the_vectors(case): + """What the phone checks before it registers a session is what the server + checks when it takes one, and again before it sends one.""" + pattern = VECTORS["credential"]["pattern"] + # The vector's class is the server's own, anchored and bounded. + assert pattern == "^" + diary_http._COOKIE_OCTETS.pattern[:-1] + "{1,4096}$" + assert diary_http.cookie_value_ok(case["value"]) is case["ok"] + assert (re.fullmatch(pattern, case["value"]) is not None) is case["ok"] + + +@pytest.mark.parametrize("case", VECTORS["header_token"]["cases"], ids=lambda c: repr(c["value"])) +def test_header_token_rule_matches_the_vectors(case): + pattern = VECTORS["header_token"]["pattern"] + assert pattern == "^" + diary_http._HEADER_TOKEN.pattern + "$" + assert diary_http.header_value_ok(case["value"]) is case["ok"] + assert (re.fullmatch(pattern, case["value"]) is not None) is case["ok"] + + +def test_user_agent_and_petersburg_origin_are_the_vectors(): + assert diary_http.USER_AGENT == VECTORS["user_agent"] + assert pbclient.USER_AGENT == VECTORS["user_agent"] + assert pbclient.BASE_URL == PETERSBURG["origin"] + assert pbclient.SESSION_COOKIE == PETERSBURG["session_cookie"] + + +def test_the_idle_window_is_the_vectors(): + """A session nobody uses for this long is purged by the cron, and the + phone says so on the screen — one number, held in both places.""" + assert timedelta(days=VECTORS["session"]["idle_days"]) == cron.DIARY_SESSION_TTL diff --git a/server/tests/test_diary_session.py b/server/tests/test_diary_session.py new file mode 100644 index 00000000..79516110 --- /dev/null +++ b/server/tests/test_diary_session.py @@ -0,0 +1,677 @@ +"""Registering a session the phone opened: ``POST /api/v1/diary/session``. + +The phone signs in with the diary itself, over its own connection, so the +password never reaches this server; it hands over the session the diary gave +it, once, and forgets it. What this file pins is what the server does with +that hand-over: + +- it is **checked** with a read of this server's own, from this server's + address, before anything is kept — and what the read hands back (a rotated + token, the pupils, the school) is what is kept and answered; +- nothing in the body that is not a session is accepted — not a password, not + a cookie that would smuggle a second one, not a region outside the + allow-list — and a refusal never repeats what was sent; +- the failures that say something about the session are counted against the + same limit as ``/login``'s wrong passwords, and the ones that say nothing + about it are not; +- ``/login`` itself is unchanged, bar the header every diary 503 now carries. + +Nothing here reaches a real diary. Petersburg's pooled client and «Сетевой +город»'s are each replaced by one over ``httpx.MockTransport``. +""" + +from __future__ import annotations + +import json +from datetime import UTC, date, datetime + +import httpx +import pytest +from httpx import ASGITransport +from sqlalchemy import select + +from app.api.diary import diary_login_limiter +from app.config import get_settings +from app.main import app +from app.models import DiarySession, JoinAttempt, SchoolClass +from app.providers.diary import http as diary_http +from app.providers.netschool import client as nsclient +from app.providers.netschool import regions +from app.providers.petersburg import client as pbclient +from app.services import diary as service + +#: A Petersburg session as the phone would hand it over: three base64url parts. +JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MDIxIn0.c2lnbmF0dXJlLWZyb20tdGhlLXBob25l" +ROTATED = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MDIxIn0.cm90YXRlZC1ieS10aGUtcmVhZA" +CHILDREN_PATH = "/api/journal/person/related-child-list" +SCHEDULE_PATH = "/api/journal/schedule/list-by-education" + +CHILD = { + "identity": {"id": 4021}, + "firstname": "Пётр", + "surname": "Иванов", + "educations": [ + {"education_id": 90210, "group_id": 771, "group_name": "9А", + "institution_name": "ГБОУ СОШ № 1"} + ], +} + + +@pytest.fixture +async def client(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac + + +@pytest.fixture +async def petersburg(monkeypatch, FakeUpstream): + """Petersburg's upstream, answering the pupils by default.""" + fake = FakeUpstream({CHILDREN_PATH: {"items": [CHILD]}}) + + async def shared(): + return httpx.AsyncClient( + base_url=pbclient.BASE_URL, transport=httpx.MockTransport(fake.handler) + ) + + monkeypatch.setattr(pbclient, "shared_client", shared) + return fake + + +class _NetSchoolUpstream: + """«Сетевой город»'s regional server: the bootstrap's four answers, any of + which a test replaces, and every request it was sent.""" + + def __init__(self) -> None: + self.seen: list[httpx.Request] = [] + self.routes: dict[str, httpx.Response | object] = { + "/webapi/student/diary/init": {"students": [ + {"studentId": 11, "nickName": "Иванов Иван", "classId": 3}]}, + "/webapi/years/current": {"id": 2026, "startDate": "2026-09-01", + "endDate": "2027-05-31"}, + "/webapi/context": {"organizationName": "Гимназия № 7"}, + "/webapi/grade/assignment/types": [{"id": 3, "name": "Домашнее задание"}], + } + + def handler(self, request: httpx.Request) -> httpx.Response: + self.seen.append(request) + route = self.routes.get(request.url.path) + if isinstance(route, httpx.Response): + return route + if route is None: + return httpx.Response(404, json={}) + return httpx.Response(200, json=route) + + +@pytest.fixture +async def netschool(monkeypatch): + fake = _NetSchoolUpstream() + + async def shared(): + return httpx.AsyncClient( + transport=httpx.MockTransport(fake.handler), cookies=diary_http.NoCookieJar() + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + return fake + + +@pytest.fixture +def no_diary_secret(monkeypatch): + """A deployment without ``DIARY_SECRET``; see ``test_diary_api``'s twin.""" + monkeypatch.setattr(get_settings(), "diary_secret", "", raising=False) + yield + get_settings.cache_clear() + + +def _petersburg_body(**over) -> dict: + return {"provider": "petersburg", "login": "parent@example.com", + "credential": {"token": JWT}} | over + + +def _netschool_body(**over) -> dict: + return { + "provider": "netschool", + "login": "ivanova", + "region": "zabaikalsky", + "school_id": 42, + "credential": { + "at": "56574745368264517434263", + "cookies": {"NSSESSIONID": "sess-phone", "ESRNSec": "esrn-phone"}, + "ver": "639", + "time_out": 900000, + }, + } | over + + +async def _register(client, body: dict) -> httpx.Response: + return await client.post("/api/v1/diary/session", json=body) + + +async def _attempts(session) -> int: + return len(list(await session.scalars(select(JoinAttempt)))) + + +# -------------------------------------------------------------------------- +# What is kept +# -------------------------------------------------------------------------- + + +async def test_a_petersburg_session_is_validated_upstream_once_and_sealed( + client, session, petersburg +): + response = await _register(client, _petersburg_body()) + + assert response.status_code == 200, response.text + # One read, with the phone's token as the session cookie, from here. + (call,) = petersburg.seen + assert call.url.path == CHILDREN_PATH + assert f"X-JWT-Token={JWT}" in call.headers["cookie"] + + row = await session.scalar(select(DiarySession)) + assert row.upstream_token != JWT # sealed, not stored as it came + assert service.upstream_of(row) == JWT + assert row.provider == "petersburg" and row.region is None + assert row.login == "parent@example.com" + assert row.upstream_ok_at is not None + + +async def test_the_token_handed_back_is_ours_and_the_upstream_one_is_never_echoed( + client, session, petersburg +): + response = await _register(client, _petersburg_body()) + + body = response.json() + assert JWT not in response.text + assert set(body) == { + "token", "login", "provider", "region", "school_id", "school_name", "zone", "students", + } + row = await session.scalar(select(DiarySession)) + from app.security import hash_token + + assert row.token_hash == hash_token(body["token"]) + + +async def test_a_refreshed_token_from_the_validating_call_is_what_is_kept( + client, session, petersburg +): + def rotating(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"data": {"items": [CHILD]}}, + headers={"set-cookie": f"X-JWT-Token={ROTATED}; Path=/"}, + ) + + petersburg.routes[CHILDREN_PATH] = rotating + response = await _register(client, _petersburg_body()) + + assert response.status_code == 200, response.text + row = await session.scalar(select(DiarySession)) + assert service.upstream_of(row) == ROTATED + + +async def test_a_netschool_session_is_bootstrapped_before_it_is_kept(client, session, netschool): + response = await _register(client, _netschool_body()) + + assert response.status_code == 200, response.text + # The four bootstrap calls, in order, all to the allow-listed origin and + # none with a password: there is none. + assert [r.url.path for r in netschool.seen] == [ + "/webapi/student/diary/init", + "/webapi/years/current", + "/webapi/context", + "/webapi/grade/assignment/types", + ] + origin = httpx.URL(regions.get("zabaikalsky").origin) + assert {(r.url.scheme, r.url.host) for r in netschool.seen} == {(origin.scheme, origin.host)} + assert all(r.headers["at"] == "56574745368264517434263" for r in netschool.seen) + assert all( + r.headers["cookie"] == "NSSESSIONID=sess-phone; ESRNSec=esrn-phone" + for r in netschool.seen + ) + + row = await session.scalar(select(DiarySession)) + assert row.provider == "netschool" and row.region == "zabaikalsky" + sealed = json.loads(service.upstream_of(row)) + assert sealed["year_id"] == 2026 + assert sealed["types"] == {"3": "Домашнее задание"} + assert sealed["school"] == "Гимназия № 7" + assert sealed["school_id"] == 42 + assert sealed["ver"] == "639" and sealed["time_out"] == 900000 + + body = response.json() + assert body["provider"] == "netschool" + assert body["region"] == "zabaikalsky" + assert body["school_id"] == 42 + assert body["school_name"] == "Гимназия № 7" + assert body["zone"] == "Asia/Chita" + assert "sess-phone" not in response.text and "56574745368264517434263" not in response.text + + +async def test_the_students_come_back_with_the_token(client, petersburg, netschool): + first = (await _register(client, _petersburg_body())).json() + assert first["students"] == [{ + "id": 4021, "first_name": "Пётр", "last_name": "Иванов", "middle_name": None, + "full_name": "Иванов Пётр", "school": "ГБОУ СОШ № 1", "class_name": "9А", + }] + second = (await _register(client, _netschool_body())).json() + assert [s["id"] for s in second["students"]] == [11] + assert second["students"][0]["school"] == "Гимназия № 7" + + +# -------------------------------------------------------------------------- +# What is refused before anything goes upstream +# -------------------------------------------------------------------------- + + +async def test_a_region_outside_the_allow_list_is_422_with_no_call(client, session, netschool): + response = await _register(client, _netschool_body(region="atlantis")) + + assert response.status_code == 422 + assert netschool.seen == [] + assert await _attempts(session) == 0 + + +async def test_an_esia_only_region_is_422_with_no_call(client, session, netschool): + """altai-krai, primorye and tula let families in through Госуслуги only; no + session the phone could open with a password is one of theirs.""" + for region in ("altai-krai", "primorye", "tula"): + response = await _register(client, _netschool_body(region=region)) + assert response.status_code == 422, region + assert netschool.seen == [] + assert await _attempts(session) == 0 + + +async def test_a_password_in_the_body_is_refused(client, session, petersburg, netschool): + """No door on this endpoint takes a password, by mistake or otherwise.""" + for body in ( + _petersburg_body(password="hunter2"), + _netschool_body(password="hunter2"), + _petersburg_body(credential={"token": JWT, "password": "hunter2"}), + ): + response = await _register(client, body) + assert response.status_code == 422, body + assert "hunter2" not in response.text + assert petersburg.seen == [] and netschool.seen == [] + assert await session.scalar(select(DiarySession)) is None + + +async def test_the_body_is_discriminated_by_provider(client, petersburg, netschool): + """Each provider's body is its own shape: Petersburg's carries no region, + «Сетевой город»'s must carry one and a school, and a provider nobody + implements is not a body at all.""" + refused = [ + _petersburg_body(region="zabaikalsky"), + {k: v for k, v in _netschool_body().items() if k != "region"}, + {k: v for k, v in _netschool_body().items() if k != "school_id"}, + _netschool_body(credential={"token": JWT}), + _petersburg_body(provider="moscow"), + {k: v for k, v in _petersburg_body().items() if k != "provider"}, + ] + for body in refused: + response = await _register(client, body) + assert response.status_code == 422, body + assert petersburg.seen == [] and netschool.seen == [] + + assert (await _register(client, _petersburg_body())).status_code == 200 + assert (await _register(client, _netschool_body())).status_code == 200 + + +async def test_a_cookie_value_that_would_inject_a_second_cookie_is_refused(client, netschool): + for cookies in ( + {"NSSESSIONID": "x; ESRNSec=forged"}, + {"NSSESSIONID": "x", "ESRNSec": "y, z"}, + {"NSSESSIONID": "x", "Tracking": "t"}, + ): + body = _netschool_body() + body["credential"]["cookies"] = cookies + response = await _register(client, body) + assert response.status_code == 422, cookies + assert netschool.seen == [] + + +async def test_a_header_value_with_a_line_break_is_refused(client, netschool): + body = _netschool_body() + body["credential"]["at"] = "5657474536\r\nX-Evil: 1" + response = await _register(client, body) + + assert response.status_code == 422 + assert netschool.seen == [] + + +async def test_a_jwt_that_is_not_a_jwt_is_refused(client, petersburg): + for token in ("not-a-jwt-at-all-really", f"{JWT}; X-Other=1", "a.b.c", "a" * 5000): + response = await _register(client, _petersburg_body(credential={"token": token})) + assert response.status_code == 422, token + assert petersburg.seen == [] + + +async def test_a_refused_body_never_echoes_what_it_carried(client): + """FastAPI's 422 repeats each refused value back as ``input``. Here that + value is an upstream session, or a password somebody should not have + sent, and neither goes back out.""" + body = _netschool_body(password="hunter2") + body["credential"]["cookies"] = {"NSSESSIONID": "secret; ESRNSec=forged"} + response = await _register(client, body) + + assert response.status_code == 422 + assert "hunter2" not in response.text + assert "secret" not in response.text + assert all("input" not in error for error in response.json()["detail"]) + # It still says where the problem is. + assert any(error["loc"][-1] == "password" for error in response.json()["detail"]) + + +# -------------------------------------------------------------------------- +# What the upstream said, and what it costs the caller +# -------------------------------------------------------------------------- + + +async def test_a_session_the_upstream_will_not_accept_from_here_is_409_and_counted( + client, session, petersburg, netschool +): + """The session worked on the phone seconds ago; from here it does not. + Not a 401 with ``X-Diary-Reauth``: asking for the password again would go + round the same loop. Counted, because it is also what a replay of a + session that was never real looks like.""" + petersburg.routes[CHILDREN_PATH] = lambda request: httpx.Response(401, json={}) + first = await _register(client, _petersburg_body()) + netschool.routes["/webapi/student/diary/init"] = httpx.Response(401, json={}) + second = await _register(client, _netschool_body()) + + for response in (first, second): + assert response.status_code == 409, response.text + assert "X-Diary-Reauth" not in response.headers + assert await _attempts(session) == 2 + assert await session.scalar(select(DiarySession)) is None + + +async def test_an_account_with_no_pupil_is_403(client, session, petersburg, netschool): + petersburg.routes[CHILDREN_PATH] = {"items": []} + first = await _register(client, _petersburg_body()) + netschool.routes["/webapi/student/diary/init"] = {"students": []} + second = await _register(client, _netschool_body()) + + for response in (first, second): + assert response.status_code == 403, response.text + assert response.json()["detail"] == "В этой учётной записи нет ученика" + assert await _attempts(session) == 2 + assert await session.scalar(select(DiarySession)) is None + + +async def test_a_refusing_region_is_503_and_not_counted(client, session, netschool): + """The region drops this server's address. Nothing judged the session, so + nothing is counted — and the header says which 503 it is.""" + netschool.routes["/webapi/student/diary/init"] = httpx.Response( + 200, text="

Доступ к сайту запрещён

", headers={"content-type": "text/html"} + ) + response = await _register(client, _netschool_body()) + + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == "address-refused" + assert await _attempts(session) == 0 + + +async def test_the_upstream_being_down_is_503_and_not_counted(client, session, petersburg): + petersburg.routes[CHILDREN_PATH] = lambda request: httpx.Response(502, text="bad gateway") + response = await _register(client, _petersburg_body()) + + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == "upstream" + assert await _attempts(session) == 0 + + +async def test_an_unreadable_answer_is_502_and_counted(client, session, petersburg, netschool): + petersburg.routes[CHILDREN_PATH] = {"items": "not a list"} + first = await _register(client, _petersburg_body()) + netschool.routes["/webapi/student/diary/init"] = [{"studentId": 11}] + second = await _register(client, _netschool_body()) + + for response in (first, second): + assert response.status_code == 502, response.text + assert await _attempts(session) == 2 + + +async def test_without_a_diary_secret_it_is_503_and_nothing_goes_upstream( + client, session, petersburg, no_diary_secret +): + response = await _register(client, _petersburg_body()) + + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == "disabled" + assert response.json()["detail"] == "Дневник на этом сервере выключен." + assert petersburg.seen == [] + assert await _attempts(session) == 0 + + +async def test_sign_in_and_registration_failures_share_one_limit( + client, petersburg, LOGIN_PATH, with_token +): + """A caller who spent ``/login``'s ten wrong passwords does not get ten + more tries by session, and the other way round: one limiter, one bucket.""" + petersburg.routes[LOGIN_PATH] = with_token + for _ in range(diary_login_limiter.limit): + wrong = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "wrong"} + ) + assert wrong.status_code == 401 + + blocked = await _register(client, _petersburg_body()) + assert blocked.status_code == 429 + assert "Retry-After" in blocked.headers + + +async def test_registration_failures_count_against_the_password_sign_in( + client, petersburg, LOGIN_PATH, with_token +): + petersburg.routes[CHILDREN_PATH] = lambda request: httpx.Response(401, json={}) + for _ in range(diary_login_limiter.limit): + assert (await _register(client, _petersburg_body())).status_code == 409 + + petersburg.routes[LOGIN_PATH] = with_token + blocked = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "correct"} + ) + assert blocked.status_code == 429 + + +# -------------------------------------------------------------------------- +# What a registered session is afterwards +# -------------------------------------------------------------------------- + + +async def test_a_registered_session_reads_like_a_signed_in_one(client, petersburg): + petersburg.routes[SCHEDULE_PATH] = {"items": [ + {"date": "15.09.2026", "subject_name": "Алгебра", "number": 1, "office": "12"}]} + token = (await _register(client, _petersburg_body())).json()["token"] + headers = {"Authorization": f"Bearer {token}"} + + students = await client.get("/api/v1/diary/students", headers=headers) + assert students.status_code == 200 + assert [s["id"] for s in students.json()] == [4021] + + lessons = await client.get( + "/api/v1/diary/students/4021/schedule?from=2026-09-14&to=2026-09-20", headers=headers + ) + assert lessons.status_code == 200, lessons.text + assert lessons.json()[0]["subject"] == "Алгебра" + # And every read carries the session that was handed over. + assert all(f"X-JWT-Token={JWT}" in r.headers["cookie"] for r in petersburg.seen) + + +async def test_the_login_finds_the_corrections_a_password_sign_in_left( + client, petersburg, LOGIN_PATH, with_token +): + """Corrections are keyed by the login, case-folded. A family that used to + sign in with a password and now registers from the phone keeps them.""" + petersburg.routes[LOGIN_PATH] = with_token + petersburg.routes[SCHEDULE_PATH] = {"items": [ + {"date": "15.09.2026", "subject_name": "Алгебра", "number": 1, "office": "12"}]} + signed_in = await client.post( + "/api/v1/diary/login", json={"login": "Parent@Example.com", "password": "correct"} + ) + old = {"Authorization": f"Bearer {signed_in.json()['token']}"} + schedule = "/api/v1/diary/students/4021/schedule?from=2026-09-14&to=2026-09-20" + target = (await client.get(schedule, headers=old)).json()[0]["target"] + put = await client.put( + "/api/v1/diary/students/4021/overrides", + headers=old, + json={"target": target, "field": "room", "value": "204"}, + ) + assert put.status_code == 200, put.text + + token = (await _register(client, _petersburg_body(login="parent@example.com"))).json()["token"] + lesson = (await client.get(schedule, headers={"Authorization": f"Bearer {token}"})).json()[0] + assert lesson["room"] == "204" + + +async def test_a_registered_session_is_invisible_to_the_bot(client, session, petersburg): + """Showing a phone's session in the bot is deliberately left for later: the + row belongs to no Telegram account and no class, so no bot screen finds + it — even with a device token of a class bound to the same diary sent.""" + from app.bot.handlers import diary as bot_diary + + klass = SchoolClass(name="9А", join_code="PHONE42", diary_provider="petersburg") + session.add(klass) + await session.commit() + joined = await client.post("/api/v1/join", json={"code": "PHONE42"}) + device = joined.json()["token"] + + response = await client.post( + "/api/v1/diary/session", json=_petersburg_body(), headers={"X-Device-Token": device} + ) + assert response.status_code == 200, response.text + + row = await session.scalar(select(DiarySession)) + assert row.telegram_id is None and row.class_id is None + assert await bot_diary._session_for(session, 42, klass) is None + + +async def test_a_device_token_never_authorises_a_diary_read(client, session, school_class): + """The class token and the diary token are two bearers on two endpoint + families; neither opens the other's.""" + joined = await client.post("/api/v1/join", json={"code": "TEST42"}) + device = joined.json()["token"] + + response = await client.get( + "/api/v1/diary/students", headers={"Authorization": f"Bearer {device}"} + ) + assert response.status_code == 401 + + +# -------------------------------------------------------------------------- +# The rest of the diary's surface this batch touched +# -------------------------------------------------------------------------- + + +async def test_the_old_login_endpoint_is_unchanged(client, petersburg, LOGIN_PATH, with_token): + """Older apps still call it, and read exactly two fields.""" + petersburg.routes[LOGIN_PATH] = with_token + response = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "correct"} + ) + + assert response.status_code == 200 + assert set(response.json()) == {"token", "login"} + assert response.json()["login"] == "parent@example.com" + + +@pytest.mark.parametrize( + ("answer", "reason"), + [ + (lambda request: httpx.Response(503, json={}), "upstream"), + (lambda request: httpx.Response(403, text="

Access denied

", + headers={"content-type": "text/html"}), "address-refused"), + ], + ids=["upstream", "address-refused"], +) +async def test_every_diary_503_says_which_kind_it_is( + client, petersburg, netschool, LOGIN_PATH, answer, reason +): + """The header the app switches on instead of reading Russian, on ``/login`` + as much as anywhere: before it, «выключен на сервере» and «дневник не + отвечает» were one status and two sentences to parse.""" + if reason == "upstream": + petersburg.routes[LOGIN_PATH] = answer + response = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "x"} + ) + else: + netschool.routes["/webapi/logindata"] = answer(None) + response = await client.post( + "/api/v1/diary/login", + json={"login": "parent", "password": "x", "provider": "netschool", + "region": "zabaikalsky", "school_id": 42}, + ) + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == reason + + +async def test_a_read_that_finds_the_diary_down_says_so_in_the_header(client, petersburg): + token = (await _register(client, _petersburg_body())).json()["token"] + petersburg.routes[CHILDREN_PATH] = lambda request: httpx.Response(503, json={}) + + response = await client.get( + "/api/v1/diary/students", headers={"Authorization": f"Bearer {token}"} + ) + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == "upstream" + + +async def test_the_password_sign_in_without_a_key_says_disabled( + client, petersburg, no_diary_secret +): + response = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "correct"} + ) + assert response.status_code == 503 + assert response.headers["X-Diary-Unavailable"] == "disabled" + assert response.json() == {"detail": "Дневник на этом сервере выключен."} + + +async def test_capabilities_lists_only_password_regions(client): + response = await client.get("/api/v1/diary/capabilities") + + assert response.status_code == 200 + body = response.json() + assert body["enabled"] is True and body["registration"] is True + assert body["providers"]["petersburg"] == {} + listed = body["providers"]["netschool"]["regions"] + assert listed == [r.key for r in regions.listed()] + assert not {"altai-krai", "primorye", "tula"} & set(listed) + + +async def test_capabilities_says_disabled_without_a_secret(client, no_diary_secret): + response = await client.get("/api/v1/diary/capabilities") + + assert response.status_code == 200 + assert response.json()["enabled"] is False + + +async def test_the_zone_handed_back_is_the_one_the_diary_cuts_its_day_at(monkeypatch): + """What the phone is told and what this server reads as «today» for the + same session come from one rule. At 16:30 UTC it is already tomorrow in + Chita and still today in Moscow — the instant a second rule would show.""" + from app.providers.netschool import provider as nsprovider + from app.providers.petersburg.provider import PetersburgProvider + + class Frozen(datetime): + @classmethod + def now(cls, tz=None): + moment = datetime(2026, 9, 7, 16, 30, tzinfo=UTC) + return moment.astimezone(tz) if tz is not None else moment + + monkeypatch.setattr(nsprovider, "datetime", Frozen) + monkeypatch.setattr(pbclient, "datetime", Frozen) + + assert service.zone_for("netschool", "zabaikalsky") == "Asia/Chita" + connection = nsprovider.NetSchoolProvider().open(json.dumps( + {"v": 1, "region": "zabaikalsky", "school_id": 1, "at": "a", "cookies": {}})) + assert connection.today() == date(2026, 9, 8) + + assert service.zone_for("petersburg") == "Europe/Moscow" + assert PetersburgProvider().open(JWT).today() == date(2026, 9, 7) + + # Every region the allow-list serves has a zone this Python knows. + for region in regions.listed(password_only=False): + assert service.zone_for("netschool", region.key) == region.zone diff --git a/server/tests/test_join_modes.py b/server/tests/test_join_modes.py index 68be4d03..574a9a64 100644 --- a/server/tests/test_join_modes.py +++ b/server/tests/test_join_modes.py @@ -95,6 +95,67 @@ async def test_an_open_class_still_joins_on_the_class_code(client, session, scho assert token.telegram_id is None and token.linked_at is None +async def test_join_tells_the_phone_which_diary_its_class_reads(client, session, school_class): + """A phone that joined a class can sign in to the class's diary without + searching for its school: the join says which server and which «scid».""" + school_class.diary_provider = "netschool" + school_class.diary_region = "amur" + school_class.diary_school_id = 1234 + school_class.diary_school_name = "Гимназия № 1" + await session.commit() + + response = await _join(client, "TEST42") + + assert response.status_code == 200, response.text + assert response.json()["diary"] == { + "provider": "netschool", + "region": "amur", + "school_id": 1234, + "school_name": "Гимназия № 1", + } + + +async def test_a_petersburg_binding_has_no_region_or_school(client, session, school_class): + school_class.diary_provider = "petersburg" + await session.commit() + + response = await _join(client, "TEST42") + + assert response.json()["diary"] == { + "provider": "petersburg", "region": None, "school_id": None, "school_name": None, + } + + +@pytest.mark.parametrize( + ("region", "school_id"), + [("atlantis", 5), ("tula", 5), ("amur", None)], + ids=["dropped-region", "gosuslugi-only-region", "no-school"], +) +async def test_a_class_on_a_dropped_region_reads_as_unbound( + client, session, school_class, region, school_id +): + """Read through the registry, like every other reader of the binding: a + region since dropped from the allow-list, one that takes no password, or a + binding that never got its school tells the phone «no diary» rather than + pointing it at one this server would refuse.""" + school_class.diary_provider = "netschool" + school_class.diary_region = region + school_class.diary_school_id = school_id + await session.commit() + + response = await _join(client, "TEST42") + + assert response.status_code == 200, response.text + assert response.json()["diary"] is None + + +async def test_an_unbound_class_carries_no_diary(client, school_class): + response = await _join(client, "TEST42") + + assert response.status_code == 200, response.text + assert response.json()["diary"] is None + + async def test_an_invite_only_class_refuses_the_class_code(client, session, invite_class): """Said plainly, not as «unknown code». diff --git a/server/tests/test_netschool_client.py b/server/tests/test_netschool_client.py index 168c0d07..ade34a66 100644 --- a/server/tests/test_netschool_client.py +++ b/server/tests/test_netschool_client.py @@ -208,3 +208,222 @@ def _req(login, password, region, school_id): from app.providers.diary.base import SignInRequest return SignInRequest(login=login, password=password, region=region, school_id=school_id) + + +# -------------------------------------------------------------------------- +# A session this code did not write itself +# +# The phone now opens a «Сетевой город» session and hands it over, so the +# stored session is no longer only what `login` produced. What goes into a +# header is checked on the way out, whatever wrote it. +# -------------------------------------------------------------------------- + + +def _serve(monkeypatch, handler): + """Replace the pooled client with one on a mock transport, without touching + ``httpx.AsyncClient`` itself — so a test can also drive the ASGI app.""" + + async def shared(): + return httpx.AsyncClient( + transport=httpx.MockTransport(handler), cookies=diary_http.NoCookieJar() + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + + +@pytest.mark.parametrize( + "stored", + [ + {"at": "at-A\r\nX-Evil: 1", "cookies": {"NSSESSIONID": "s"}}, + {"at": "at-A", "cookies": {"NSSESSIONID": "s; ESRNSec=forged"}}, + {"at": "at-A", "cookies": {"NSSESSIONID": "s", "Tracking": "t"}}, + {"at": 123, "cookies": {}}, + {"at": "at-A", "cookies": ["NSSESSIONID=s"]}, + ], + ids=["line-break-in-at", "semicolon-in-cookie", "unknown-cookie", "number-at", "cookie-list"], +) +async def test_a_stored_value_that_is_not_header_safe_is_never_sent(monkeypatch, stored): + """A value that would become a second header or a second cookie is a dead + session, and nothing leaves: no request at all is made with it.""" + sent: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={}) + + _serve(monkeypatch, handler) + client = nsclient.NetSchoolClient(region_for("zabaikalsky"), dict(stored)) + with pytest.raises(SessionExpired): + await client.keep_alive() + assert sent == [] + + +def _bootstrap_routes(recorder: list[httpx.Request]): + def handler(request: httpx.Request) -> httpx.Response: + recorder.append(request) + path = request.url.path + if path == "/webapi/student/diary/init": + return httpx.Response(200, json={"students": [ + {"studentId": 11, "nickName": "Иванов Иван", "classId": 3}]}) + if path == "/webapi/years/current": + return httpx.Response(200, json={"id": 2026, "startDate": "2026-09-01", + "endDate": "2027-05-31"}) + if path == "/webapi/context": + return httpx.Response(200, json={"organizationName": "Школа № 1"}) + if path == "/webapi/grade/assignment/types": + return httpx.Response(200, json=[{"id": 3, "name": "Домашнее задание"}]) + return httpx.Response(404, json={}) + + return handler + + +async def test_adopt_keeps_only_the_fields_it_knows(monkeypatch): + """Whatever else the handed-over JSON carries — a password a careless client + put there, a cookie nobody asked for, a ``ver`` of null — is not sealed.""" + from app.providers.diary.base import AdoptRequest + + seen: list[httpx.Request] = [] + _serve(monkeypatch, _bootstrap_routes(seen)) + handed = { + "at": "at-phone", + "cookies": {"NSSESSIONID": "sess-phone", "ESRNSec": "", "Tracking": "t"}, + "ver": None, + "password": "hunter2", + "school": "forged", + } + adopted = await NetSchoolProvider().adopt( + AdoptRequest(credential=json.dumps(handed), region="zabaikalsky", school_id=42) + ) + + session = json.loads(adopted.credential) + assert set(session) == { + "v", "region", "school_id", "at", "cookies", + "year_id", "year_start", "year_end", "school", "types", + } + assert session["cookies"] == {"NSSESSIONID": "sess-phone"} + assert session["school"] == "Школа № 1" # the upstream's, not the phone's + assert session["school_id"] == 42 and session["region"] == "zabaikalsky" + assert "hunter2" not in adopted.credential + assert [s.id for s in adopted.students] == [11] + assert adopted.school_name == "Школа № 1" + # The four bootstrap calls, in order, all to the allow-listed origin. + assert [r.url.path for r in seen] == [ + "/webapi/student/diary/init", + "/webapi/years/current", + "/webapi/context", + "/webapi/grade/assignment/types", + ] + assert {r.url.host for r in seen} == {"region.zabedu.ru"} + assert all(r.headers["at"] == "at-phone" for r in seen) + + +async def test_adopt_refuses_a_region_the_route_should_have_refused(): + """The route checks the allow-list first, so reaching here without it is a + programming error — a ValueError, and no request.""" + from app.providers.diary.base import AdoptRequest + + for region, school in (("atlantis", 1), ("tula", 1), ("zabaikalsky", None)): + with pytest.raises(ValueError): + await NetSchoolProvider().adopt( + AdoptRequest(credential="{}", region=region, school_id=school) + ) + + +async def test_a_diary_init_that_is_not_an_object_is_unreadable(monkeypatch): + """A list where ``diary/init`` should be an object used to raise + AttributeError out of the bootstrap — a 500 on the sign-in.""" + from app.providers.diary.errors import UnexpectedResponse + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=[{"studentId": 11}]) + + _serve(monkeypatch, handler) + client = nsclient.NetSchoolClient(region_for("zabaikalsky"), {"at": "at-A", "cookies": {}}) + with pytest.raises(UnexpectedResponse): + await NetSchoolProvider.bootstrap(client) + + +async def test_a_missing_ver_is_never_sent_as_the_word_none(monkeypatch): + """A region that sends no ``cacheVer`` used to have None stored, and the + logout — and the SecurityWarning acknowledgement — posted ``ver=None``. + Sessions sealed before the fix still hold that None, so the reading side + is held too.""" + posted: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/webapi/logindata": + return httpx.Response(200, json={"schoolLogin": True}) + posted.append(request.content.decode()) + return httpx.Response(200, json={}) + + _serve(monkeypatch, handler) + region = region_for("zabaikalsky") + + fresh = nsclient.NetSchoolClient(region) + await fresh.login_allowed() + assert "ver" not in fresh.session + + for session in ({"at": "at-A"}, {"at": "at-A", "ver": None}): + await nsclient.NetSchoolClient(region, dict(session)).logout() + assert posted == ["at=at-A&ver=", "at=at-A&ver="] + assert all("None" not in body for body in posted) + + +async def test_a_school_whose_id_is_true_is_not_a_school(monkeypatch): + """``isinstance(True, int)`` is true in Python, so ``{"id": true}`` was kept + as the school with id 1 — a row the admin could bind a class to.""" + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=[ + {"id": True, "name": "Не школа"}, + {"id": 7, "name": "Гимназия № 7", "addressString": "ул. Мира, 3"}, + ]) + + _serve(monkeypatch, handler) + rows = await nsclient.NetSchoolClient(region_for("zabaikalsky")).schools_search("гимназия") + assert rows == [{"id": 7, "name": "Гимназия № 7", "address": "ул. Мира, 3"}] + + +MALFORMED_SIGN_INS = { + "logindata-array": {"/webapi/logindata": [1]}, + "salt-in-cyrillic": {"/webapi/auth/getdata": {"salt": "соль", "lt": "1", "ver": "2"}}, + "timeout-in-words": {"/webapi/login": {"at": "at-A", "timeOut": "soon"}}, + "login-array": {"/webapi/login": ["x"]}, + "at-a-number": {"/webapi/login": {"at": 123}}, + "role-with-no-roles": {"/webapi/login": {"entryPoint": "/choose-session-role"}}, +} + + +@pytest.mark.parametrize("override", MALFORMED_SIGN_INS.values(), ids=MALFORMED_SIGN_INS.keys()) +async def test_a_malformed_sign_in_answer_is_never_a_500(monkeypatch, override): + """Each of these walked out of the client as AttributeError, + UnicodeEncodeError, ValueError, TypeError or an internal exception, and + ``POST /api/v1/diary/login`` answered 500 with a stack trace. Now each is + one of the diary's own answers: a status the app has a sentence for.""" + from httpx import ASGITransport + + from app.main import app + + defaults = { + "/webapi/logindata": LOGINDATA_OK, + "/webapi/auth/getdata": {"lt": "1", "ver": "2", "salt": "3"}, + "/webapi/login": {"at": "at-A"}, + "/webapi/student/diary/init": {"students": [{"studentId": 11, "nickName": "Иван"}]}, + "/webapi/years/current": {"id": 2026}, + "/webapi/context": {}, + "/webapi/grade/assignment/types": [], + } + routes = {**defaults, **override} + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json=routes.get(request.url.path, {})) + + _serve(monkeypatch, handler) + async with httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as api: + response = await api.post( + "/api/v1/diary/login", + json={"login": "parent", "password": "hunter2", "provider": "netschool", + "region": "zabaikalsky", "school_id": 42}, + ) + assert response.status_code != 500, response.text + assert response.status_code in (200, 401, 502, 503) diff --git a/server/tests/vectors/diary_protocol.json b/server/tests/vectors/diary_protocol.json new file mode 100644 index 00000000..a946e6d1 --- /dev/null +++ b/server/tests/vectors/diary_protocol.json @@ -0,0 +1,156 @@ +{ + "version": 1, + "about": "Known answers for the two diary sign-in protocols, read by the server's tests/test_diary_protocol_vectors.py and the phone's DiaryProtocolVectorsTest. The file is the oracle, not either codebase: a change here is a change to both implementations. Bodies are compared as decoded values, never as bytes (OkHttp and httpx encode the same form differently).", + "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", + "session": {"idle_days": 30}, + "petersburg": { + "origin": "https://dnevnik2.petersburgedu.ru", + "login_path": "/api/user/auth/login", + "session_cookie": "X-JWT-Token", + "login_fields": {"type": "email", "activation_code": null, "_isEmpty": false}, + "login_cases": [ + {"name": "cookie wins over body", "status": 200, "content_type": "application/json", "body": "{\"data\":{\"token\":\"body\"}}", "set_cookie": ["X-JWT-Token=cookie; Path=/"], "expect": {"token": "cookie"}}, + {"name": "two paths, last wins", "status": 200, "content_type": "application/json", "body": "{\"data\":{\"token\":\"body\"}}", "set_cookie": ["X-JWT-Token=old; Path=/", "X-JWT-Token=new; Path=/api"], "expect": {"token": "new"}}, + {"name": "deletion is not a session", "status": 200, "content_type": "application/json", "body": "{\"data\":{\"token\":\"body\"}}", "set_cookie": ["X-JWT-Token=; Max-Age=0; Path=/"], "expect": {"token": "body"}}, + {"name": "an expired cookie is not a session", "status": 200, "content_type": "application/json", "body": "{\"data\":{\"token\":\"body\"}}", "set_cookie": ["X-JWT-Token=gone; Max-Age=0; Path=/"], "expect": {"token": "body"}}, + {"name": "body token is trimmed", "status": 200, "content_type": "application/json", "body": "{\"data\":{\"token\":\" body \"}}", "set_cookie": [], "expect": {"token": "body"}}, + {"name": "html 200", "status": 200, "content_type": "text/html", "body": "", "set_cookie": [], "expect": {"failure": "unexpected"}}, + {"name": "json that is not an object", "status": 200, "content_type": "application/json", "body": "[1]", "set_cookie": [], "expect": {"failure": "unexpected"}}, + {"name": "data null with a message", "status": 200, "content_type": "application/json", "body": "{\"data\":null,\"message\":\"Ошибка\"}", "set_cookie": [], "expect": {"failure": "unexpected"}}, + {"name": "400", "status": 400, "content_type": "application/json", "body": "{}", "set_cookie": [], "expect": {"failure": "bad_credentials"}}, + {"name": "401", "status": 401, "content_type": "application/json", "body": "{}", "set_cookie": [], "expect": {"failure": "bad_credentials"}}, + {"name": "403", "status": 403, "content_type": "application/json", "body": "{}", "set_cookie": [], "expect": {"failure": "bad_credentials"}}, + {"name": "500", "status": 500, "content_type": "application/json", "body": "{}", "set_cookie": [], "expect": {"failure": "unavailable"}}, + {"name": "502", "status": 502, "content_type": "text/html", "body": "", "set_cookie": [], "expect": {"failure": "unavailable"}}, + {"name": "no token", "status": 200, "content_type": "application/json", "body": "{\"data\":{}}", "set_cookie": [], "expect": {"failure": "unexpected"}} + ] + }, + "netschool": { + "session_cookies": ["NSSESSIONID", "ESRNSec"], + "login_form_fields": ["loginType", "scid", "un", "pw", "pw2", "lt", "ver"], + "flow": { + "about": "What every *_cases row runs inside: logindata, getdata and login answer these unless the row replaces one of them. A login_cases row with tried_role true is answered choose-session-role with a parent role first.", + "login": "parent", + "password": "hunter2", + "school_id": 42, + "logindata": {"schoolLogin": true, "cacheVer": "639"}, + "getdata": {"salt": "333", "lt": "1", "ver": "2"}, + "role_question": { + "entryPoint": "/choose-session-role", + "accountInfo": { + "userRoles": [ + {"role": {"id": 12, "name": "Родитель"}} + ] + } + } + }, + "hash": [ + {"salt": "333", "password": "hunter2", "pw": "3b1ae8b", "pw2": "3b1ae8bcd9069bb33af6092eb0e2c9e7"}, + {"salt": "1234567890", "password": "Пароль123", "pw": "381d33374", "pw2": "381d333743568b67dec7ba54fa756f3f"}, + {"salt": "42", "password": "a", "pw": "9", "pw2": "90ec2fd877780695341d79e6369d633e"}, + {"salt": "42", "password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "pw": "22b601dce1fb41876cb70f9a72487045", "pw2": "22b601dce1fb41876cb70f9a72487045"}, + {"salt": "42", "password": "ё Ё №", "pw": "83b34", "pw2": "83b344855b2ca73f65118b6d5b8af3e9"}, + {"salt": "42", "password": "ü", "failure": "bad_credentials"}, + {"salt": "42", "password": "😀", "failure": "bad_credentials"}, + {"salt": "42", "password": "a\u0098b", "failure": "bad_credentials"} + ], + "logindata_cases": [ + {"body": {"schoolLogin": false}, "expect": "sign_in_unsupported"}, + {"body": {"schoolLogin": null}, "expect": "sign_in_unsupported"}, + {"body": [1], "expect": "unexpected"}, + {"body": {"schoolLogin": true, "cacheVer": "639"}, "expect": "ok", "ver": "639"}, + {"body": {"cacheVer": 639}, "expect": "ok", "ver": "639"}, + {"body": {}, "expect": "ok", "ver": null}, + {"body": {"cacheVer": null}, "expect": "ok", "ver": null}, + {"body": {"cacheVer": true}, "expect": "ok", "ver": null} + ], + "getdata_cases": [ + {"body": {"salt": "сол", "lt": "1", "ver": "2"}, "expect": "unavailable"}, + {"body": {"lt": "1"}, "expect": "unavailable"}, + {"body": {"salt": null, "lt": "1"}, "expect": "unavailable"}, + {"body": {"salt": "333"}, "expect": "unavailable"}, + {"body": [1], "expect": "unavailable"}, + {"body": {"salt": 333, "lt": 1, "ver": 2}, "expect": "ok", "form": {"lt": "1", "ver": "2", "pw2": "3b1ae8bcd9069bb33af6092eb0e2c9e7"}}, + {"body": {"salt": "333", "lt": "1", "ver": null}, "expect": "ok", "form": {"lt": "1", "ver": "", "pw2": "3b1ae8bcd9069bb33af6092eb0e2c9e7"}} + ], + "login_cases": [ + {"status": 409, "body": {"message": "Неверный пароль"}, "expect": {"failure": "bad_credentials", "message": "Неверный пароль"}}, + {"status": 409, "body": {"errorMessage": "Пользователь не найден"}, "expect": {"failure": "bad_credentials", "message": "Пользователь не найден"}}, + {"status": 409, "body": [1], "expect": {"failure": "bad_credentials", "message": null}}, + {"status": 429, "body": {}, "expect": {"failure": "unavailable"}}, + {"status": 503, "body": {}, "expect": {"failure": "unavailable"}}, + {"status": 200, "body": ["x"], "expect": {"failure": "unexpected"}}, + {"status": 200, "body": {"at": "x", "timeOut": "soon"}, "expect": {"at": "x", "time_out": null}}, + {"status": 200, "body": {"at": "x", "timeOut": "900000"}, "expect": {"at": "x", "time_out": null}}, + {"status": 200, "body": {"at": "x", "timeOut": 900000}, "expect": {"at": "x", "time_out": 900000}}, + {"status": 200, "body": {"at": 123}, "expect": {"failure": "bad_credentials", "message": null}}, + {"status": 200, "body": {"message": "Неверный пароль"}, "expect": {"failure": "bad_credentials", "message": "Неверный пароль"}}, + {"status": 200, "body": {"at": "a b"}, "expect": {"failure": "unexpected"}}, + {"status": 200, "body": {"entryPoint": 5, "at": "x"}, "expect": {"at": "x", "time_out": null}}, + {"status": 200, "body": {"entryPoint": "/choose-session-role", "accountInfo": {"userRoles": [{"role": {"id": 12, "name": "Родитель"}}]}}, "tried_role": false, "expect": {"needs_role": true, "rolegroup": "12"}}, + {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": false, "expect": {"failure": "unexpected"}}, + {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": true, "expect": {"failure": "bad_credentials", "message": null}} + ], + "role_pick": [ + {"body": {"accountInfo": {"userRoles": [{"role": {"id": 7, "name": "Учитель"}}, {"role": {"id": 12, "name": "Родитель"}}]}}, "expect": "12"}, + {"body": {"userRoles": [{"id": 5, "name": "Администратор"}]}, "expect": "5"}, + {"body": {}, "expect": null}, + {"body": {"userRoles": [{"id": true, "name": "Родитель"}, {"id": "9", "name": "Родитель"}]}, "expect": "9"}, + {"body": {"userRoles": [{"role": {"id": 7.5, "name": "Родитель"}}, {"role": {"id": 7}}]}, "expect": "7"}, + {"body": {"accountInfo": [1]}, "expect": null}, + {"body": {"userRoles": "x"}, "expect": null} + ], + "refusal": { + "markers": ["Доступ к сайту", "Request forbidden", "Access denied", "blocked"], + "cases": [ + {"status": 403, "content_type": "application/json", "body": "{}", "refused": true}, + {"status": 200, "content_type": "text/html", "body": "

Access denied

", "refused": true}, + {"status": 200, "content_type": "text/plain", "body": "you are blocked", "refused": true}, + {"status": 200, "content_type": "text/html", "body": "

Доступ к сайту ограничен

", "refused": true}, + {"status": 200, "content_type": "application/json", "body": "{\"a\":\"Access denied\"}", "refused": false}, + {"status": 200, "content_type": "text/html", "body": "

ok

", "refused": false} + ] + }, + "schools_search": { + "path": "/webapi/schools/search", + "query_parameter": "name", + "query_cut_code_points": 60, + "query_cases": [ + {"query": "Школа № 5", "sent": "Школа № 5"}, + {"query": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя", "sent": "яяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяяя"}, + {"query": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", "sent": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀"} + ], + "cases": [ + {"body": [{"id": 1, "name": "Школа № 5", "addressString": "ул. Ленина, 1"}, {"id": true, "name": "x"}, {"id": "5", "name": "y"}, {"id": 2}], "expect": [{"id": 1, "name": "Школа № 5", "address": "ул. Ленина, 1"}]}, + {"body": [{"id": 3, "name": " Лицей № 2 ", "addressString": " "}, {"id": 4, "name": " "}, {"id": 5, "name": 7}, {"id": 6.0, "name": "z"}, "row"], "expect": [{"id": 3, "name": "Лицей № 2", "address": null}]}, + {"body": {"error": 1}, "expect": "unexpected"} + ] + } + }, + "credential": { + "pattern": "^[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]{1,4096}$", + "cases": [ + {"value": "a;b", "ok": false}, + {"value": "eyJ.a-b_c", "ok": true}, + {"value": "a\r\nb", "ok": false}, + {"value": "", "ok": false}, + {"value": "a b", "ok": false}, + {"value": "a\"b", "ok": false}, + {"value": "a,b", "ok": false}, + {"value": "a\\b", "ok": false}, + {"value": "abc=+/", "ok": true}, + {"value": "ключ", "ok": false} + ] + }, + "header_token": { + "pattern": "^[A-Za-z0-9._~+/=-]+$", + "cases": [ + {"value": "56574745368264517434263", "ok": true}, + {"value": "a b", "ok": false}, + {"value": "a\nb", "ok": false}, + {"value": "", "ok": false}, + {"value": "a;b", "ok": false}, + {"value": "Zm9v+YmFy/=~._-", "ok": true} + ] + } +} From 68cd8070f0952fbf53849683d04ebe9ab1fdd925 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:15:11 +0000 Subject: [PATCH 12/30] Find the regions a school may be in, without letting onboarding spend the bot's allowance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner asked that typing a school's name on the first run's region screen list the regions it may be in (#141). DaData is the only nationwide source, and its key must never be in the APK, so the phone asks the server: `GET /api/v1/directory/school-regions?q=`, anonymous. - Each hit is placed by the two-digit code of DaData's `region_kladr_id`, then by its region text against the catalog's `dadata_names`; one the catalog cannot place comes back with DaData's own label. Hits are grouped by region, best rank first, with a few cities and example names each, and a branch in another region is no longer folded into its head's row. - A name that is only a type word and a short number («Школа № 5», «СОШ 12») exists in every region. It is answered `generic` without calling DaData, and so is a truncated answer spread over many regions: the phone then says so and asks for the region instead. The stop words come from the catalog, so the phone and the server read one list. - Anonymous means two limits. Every call past validation counts against the caller (`JoinThrottle.record`, 20 per 15 minutes; the window is 900 s like every throttle on that table, because its pruning is global, and a test pins it). And a daily allowance: 4,000 of DaData's 10,000 requests, counted per Moscow day in the new `usage_counters` table (`services/quota.py`, one atomic INSERT … ON CONFLICT … WHERE … RETURNING). The empty-answer retry is charged too, and skipped when nothing is left. The bot's and `/manage/schools`' searches are unchanged and never charged to it, so onboarding cannot use up the search the bot's create-class step depends on. - Every 503 says which case in `X-Directory-Unavailable: disabled | spent | upstream`, with `Retry-After` until Moscow midnight when the day is spent. Migration `0016` creates `usage_counters` and nothing else: additive, destroys nothing, and goes on with `0015` before #140 merges. `EXPECTED_REVISION` is `0016`. Unverified: whether DaData's party rows carry `region_kladr_id` (the name fallback exists for that), the codes 90/93/94/95, DaData's own day boundary, and two requests racing for the last unit on Postgres (checked on SQLite only). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/directory.py | 143 +++++ server/app/db.py | 2 +- server/app/main.py | 6 + server/app/models.py | 29 + server/app/providers/dadata/client.py | 26 +- server/app/providers/dadata/mapper.py | 32 +- server/app/providers/dadata/models.py | 10 + server/app/schemas.py | 50 ++ server/app/security.py | 34 +- server/app/services/quota.py | 156 ++++++ server/app/services/schools.py | 188 ++++++- .../versions/0016_usage_counters.py | 76 +++ server/tests/test_directory.py | 503 ++++++++++++++++++ server/tests/test_quota.py | 189 +++++++ server/tests/test_schools.py | 85 +++ 15 files changed, 1509 insertions(+), 20 deletions(-) create mode 100644 server/app/api/directory.py create mode 100644 server/app/services/quota.py create mode 100644 server/migrations/versions/0016_usage_counters.py create mode 100644 server/tests/test_directory.py create mode 100644 server/tests/test_quota.py diff --git a/server/app/api/directory.py b/server/app/api/directory.py new file mode 100644 index 00000000..fd1aa2e2 --- /dev/null +++ b/server/app/api/directory.py @@ -0,0 +1,143 @@ +"""The school directory, for a phone that belongs to no class yet. + +One question: «which regions is a school of this name in». The phone asks it +on its first screen, before it has a class, a diary or any token at all, so +that somebody who types «лицей 1535» is offered Москва rather than a list of +eighty-nine regions to scroll. It is a convenience and nothing depends on it: +picking the region from the list always works, and every failure here says so. + +**Anonymous, and therefore metered twice.** Every call past validation counts +against its caller (twenty in fifteen minutes, on the table `/join` counts in), +and every request it makes upstream is spent from the anonymous share of the +directory's daily allowance (``services/quota.py``) — so neither one address +nor many can spend what the bot and ``/manage/schools`` need to create a +class. Those two keep their own search, unchanged and unmetered here. + +Every 503 carries ``X-Directory-Unavailable`` — ``disabled``, ``spent`` or +``upstream`` — for the same reason every diary 503 carries its own header: the +app picks its sentence without reading the Russian. +""" + +from __future__ import annotations + +from dishka.integrations.fastapi import FromDishka +from fastapi import APIRouter, HTTPException, Query, Request, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.api.public import caller_bucket +from app.api.routing import DishkaAnnotatedRoute +from app.providers import dadata +from app.schemas import SchoolRegionOut, SchoolRegionsOut +from app.security import JoinThrottle +from app.services import quota +from app.services import schools as schools_service + +router = APIRouter( + route_class=DishkaAnnotatedRoute, prefix="/api/v1/directory", tags=["directory"] +) + +#: Searches one caller may make in a quarter of an hour, **all** of them +#: counted — a search that finds its school has spent the same upstream request +#: as one that finds nothing. Twenty is a person trying spellings with room to +#: spare, and a school's NAT full of phones on an open day will meet it; they +#: then pick the region from the list, which is what the limit costs. +#: +#: The window is `/join`'s and the diary sign-in's, and has to be: the three +#: share one table, and every recorded attempt prunes the whole table to its +#: own window (``JoinThrottle``). +directory_limiter = JoinThrottle(limit=20, window=900.0) + +#: The header every 503 here carries, and its three values. +UNAVAILABLE_HEADER = "X-Directory-Unavailable" + +DISABLED_DETAIL = "Поиск школ не настроен — выберите регион из списка" +SPENT_DETAIL = "Поиск школ на сегодня исчерпан — выберите регион из списка" +UPSTREAM_DETAIL = "Поиск школ сейчас недоступен — выберите регион из списка" +THROTTLED_DETAIL = "Слишком много поисков подряд. Выберите регион из списка или попробуйте позже." + + +def _unavailable(detail: str, reason: str, *, retry_after: int | None = None) -> HTTPException: + headers = {UNAVAILABLE_HEADER: reason} + if retry_after is not None: + headers["Retry-After"] = str(retry_after) + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=detail, headers=headers + ) + + +@router.get("/school-regions", response_model=SchoolRegionsOut) +async def school_regions( + request: Request, + q: str | None = Query(None, description="Название школы, как его пишут люди"), + *, + session: FromDishka[AsyncSession], +) -> SchoolRegionsOut: + """The regions a school called ``q`` may be in, best-ranked first. + + In this order, and the order is the contract: + + 1. a caller over its limit is 429 with ``Retry-After``; + 2. a query under three characters is 422, **not counted** — nothing was + asked of anybody; + 3. everything after that is counted against the caller; + 4. no directory key on this deployment is 503 ``disabled``; + 5. a name that is only a kind of school and a small number («школа № 5») + is 200 with ``generic`` and no upstream call; anything else spends from + today's anonymous share, and a spent share is 503 ``spent`` with + ``Retry-After`` until the next day; + 6. the directory failing, in any way, is 503 ``upstream``. + + Not per keystroke: the phone asks on submit or after a pause in typing. + """ + # Scoped, so twenty searches do not spend a phone's thirty join attempts, + # and hashed with the scope inside it — see `caller_bucket` for why a + # prefix on the digest is a 500 on Postgres. + client = caller_bucket(request, scope="directory:") + retry_after = await directory_limiter.blocked_for(session, client) + if retry_after is not None: + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=THROTTLED_DETAIL, + headers={"Retry-After": str(int(retry_after) + 1)}, + ) + + try: + query = schools_service.normalise_query(q) + except schools_service.SearchError as error: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) + ) from error + + await directory_limiter.record(session, client) + + if not schools_service.available(): + raise _unavailable(DISABLED_DETAIL, "disabled") + + try: + found = await schools_service.regions_for(session, query) + except quota.AllowanceSpent as spent: + raise _unavailable(SPENT_DETAIL, "spent", retry_after=spent.retry_after) from spent + except dadata.DirectoryError as error: + # The bot's own wording for these ends «введите название вручную», + # which is the bot's way out and not the phone's. DaData's refusal of + # the key or of its own daily allowance lands here too: it is the + # owner's to fix, and to the person holding the phone it is the same + # «not now». + raise _unavailable(UPSTREAM_DETAIL, "upstream") from error + + return SchoolRegionsOut( + query=found.query, + regions=[ + SchoolRegionOut( + region=group.region, + code=group.code, + label=group.label, + schools=group.schools, + cities=group.cities, + examples=group.examples, + ) + for group in found.groups + ], + truncated=found.truncated, + generic=found.generic, + ) diff --git a/server/app/db.py b/server/app/db.py index 9fbbc6e5..e07ea7c8 100644 --- a/server/app/db.py +++ b/server/app/db.py @@ -134,7 +134,7 @@ def rows_affected(result: Any) -> int: #: inside a request. A constant that has to be kept in step by hand would rot, #: so ``tests/test_schema_version.py`` pins it to the real head and fails the #: build if a new revision lands without updating it. -EXPECTED_REVISION = "0015" +EXPECTED_REVISION = "0016" async def current_revision(session: AsyncSession) -> str | None: diff --git a/server/app/main.py b/server/app/main.py index dd4c0ff1..2d04349b 100644 --- a/server/app/main.py +++ b/server/app/main.py @@ -18,6 +18,7 @@ from app.api.cron import router as cron_router from app.api.diary import router as diary_router from app.api.diary_web import router as diary_web_router +from app.api.directory import router as directory_router from app.api.edit import router as edit_router from app.api.manage import router as manage_router from app.api.public import router as public_router @@ -136,6 +137,11 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # endpoint a client calls, and it is the one HTML this project serves — see # app/api/diary_web.py for why a password may not be typed into a chat. app.include_router(diary_web_router) +# The school directory a phone asks before it has a class: anonymous, and +# metered per caller and per day (app/api/directory.py). Its imports are the +# school search's own, which `manage_router` already loads, and the region +# catalog it reads is parsed on the first search, not here. +app.include_router(directory_router) app.include_router(edit_router) # The management surface: what the bot's /subjects, /bells, /class, /devices, # /log, /stats, /export, /import and access requests do, for a class admin diff --git a/server/app/models.py b/server/app/models.py index 7298ce92..a2df0da1 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -578,6 +578,35 @@ class JoinAttempt(Base): created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True) +class UsageCounter(Base): + """Units of a shared external allowance spent per calendar day, so one door + cannot spend another's. + + DaData gives a key ten thousand requests a day, and two doors spend them: + the bot and ``/manage/schools``, behind a class admin, and the anonymous + directory the phone asks before it has any class at all. Without a cap on + the second, anybody with a loop could spend the whole day's allowance and + leave an admin creating a class with «Лимит запросов исчерпан». + + Not in ``join_attempts``: that table is pruned globally to the shortest + throttle window on every recorded failure (``JoinThrottle.record``) and by + the cron after an hour, so a day's count kept there would be cut to fifteen + minutes without anything saying so. + + One row per scope per day and nothing ever deletes one: a year of a single + scope is 365 rows of three columns, and yesterday's row is what says how + close yesterday came to the cap. + """ + + __tablename__ = "usage_counters" + + #: Which allowance, such as ``dadata:anon`` (``services/quota.py``). + scope: Mapped[str] = mapped_column(String(32), primary_key=True) + #: The provider's day, in the zone ``services/quota.py`` counts in. + day: Mapped[Date] = mapped_column(SADate, primary_key=True) + used: Mapped[int] = mapped_column(Integer, nullable=False) + + class DeviceToken(Base): """Read-only token handed to an Android device after it enters a join code.""" diff --git a/server/app/providers/dadata/client.py b/server/app/providers/dadata/client.py index 9b53ff8f..b0a226f6 100644 --- a/server/app/providers/dadata/client.py +++ b/server/app/providers/dadata/client.py @@ -12,19 +12,21 @@ GitHub project that tried this links to — answer 404 today. What does exist is the ЕГРЮЛ company register, which every school is in because every school is one, and DaData is the search over it that people actually use (119 files on -GitHub call this exact URL). The cost is a request per keystroke-ish search and -a key in the environment; -the alternative is a snapshot that is wrong by September and says nothing -about it. - -One client per process, not one per request: a search is three or four calls -in a row as somebody types, and three TLS handshakes is most of the wait. +GitHub call this exact URL). The cost is a request per search — two when the +first finds nothing, see :func:`suggest_schools` — and a key in the +environment; the alternative is a snapshot that is wrong by September and says +nothing about it. Nobody calls it per keystroke: the bot searches on a sent +message and the phone on submit or after a pause in typing. + +One client per process, not one per request: a person narrowing a search asks +three or four times in a row, and three TLS handshakes is most of the wait. """ from __future__ import annotations import asyncio import logging +from collections.abc import Awaitable, Callable from typing import Any import httpx @@ -127,6 +129,7 @@ async def suggest_schools( query: str, *, region: str | None = None, + may_retry: Callable[[], Awaitable[bool]] | None = None, ) -> list[dict[str, Any]]: """Raw suggestions for one search. @@ -134,6 +137,13 @@ async def suggest_schools( Петербург», «Татарстан»). A hint, not a filter: the upstream's ``locations`` narrows hard, and a school just over a city boundary is still the school the child goes to. + @param may_retry asked before the second request an empty first answer + makes, and that request is skipped — with ``[]`` — when it answers + false. The second request costs the allowance exactly what the first + did, so a caller that meters its share has to be asked for it rather + than find out afterwards; the anonymous directory passes its daily + spend here. ``None``, which is what the bot and ``/manage/schools`` + pass, retries as it always has. @raises NotConfigured when this deployment has no key. """ token = _token() @@ -159,6 +169,8 @@ async def suggest_schools( # who typed their own school's name that it does not exist, ask again # without the filter and keep whatever is in the education group. One # extra request, only ever on an empty result. + if may_retry is not None and not await may_retry(): + return [] payload.pop("okved", None) return [ item diff --git a/server/app/providers/dadata/mapper.py b/server/app/providers/dadata/mapper.py index 4aa70cb1..1efdf5a6 100644 --- a/server/app/providers/dadata/mapper.py +++ b/server/app/providers/dadata/mapper.py @@ -81,26 +81,38 @@ def to_school(item: dict[str, Any]) -> School | None: address=_text(address, "unrestricted_value") or _text(address, "value"), city=_text(address_data, "city") or _text(address_data, "settlement"), region=_text(address_data, "region_with_type") or _text(address_data, "region"), + region_code=_region_code(address_data), active=_status_of(data) == _LIVE_STATUS, ) -def to_schools(items: list[dict[str, Any]]) -> list[School]: +def to_schools(items: list[dict[str, Any]], *, per_region: bool = False) -> list[School]: """The readable ones, in the order the upstream ranked them. Deduplicated by registration number: a school that has been reorganised can appear twice in one answer under two spellings of the same name, and two identical rows in a picker is a question with no right answer. + + @param per_region keep one row per registration number **per region** + instead of one per number. A branch (филиал) is registered under its + head school's OGRN, so the bot's picker, which has always deduplicated + on the number, shows the two as one — and is left that way. The + directory's question is «which regions is this school in», and folding + a branch into its head answers it with one region where there are two. Keyed on the + region's code and, for a row without one, on the register's own name + for the region: the code is not on every row, and a branch read + without it is still in another region. """ schools: list[School] = [] - seen: set[str] = set() + seen: set[tuple[str, str | None]] = set() unreadable = 0 for item in items: school = to_school(item) if school is None: unreadable += 1 continue - key = school.ogrn or school.full_name + where = (school.region_code or school.region) if per_region else None + key = (school.ogrn or school.full_name, where) if key in seen: continue seen.add(key) @@ -199,6 +211,20 @@ def _capitalise(word: str) -> str: return lowered +def _region_code(address_data: dict[str, Any]) -> str | None: + """The subject code at the front of ``region_kladr_id``, or ``None``. + + A KLADR id is thirteen digits whose first two are the region — «78» for + Saint Petersburg, «16» for Tatarstan. Anything else in the field (a code + of a new shape, a stray letter) gives ``None`` rather than a guess, and + the caller falls back to the region's name. ASCII digits only: ``isdigit`` + alone accepts «²», which is a digit to Unicode and to nobody else. + """ + kladr = _text(address_data, "region_kladr_id") + code = kladr[:2] if kladr else "" + return code if len(code) == 2 and code.isascii() and code.isdigit() else None + + def _status_of(data: dict[str, Any]) -> str: state = data.get("state") if isinstance(state, dict): diff --git a/server/app/providers/dadata/models.py b/server/app/providers/dadata/models.py index 56d1a8cf..53910a90 100644 --- a/server/app/providers/dadata/models.py +++ b/server/app/providers/dadata/models.py @@ -32,7 +32,17 @@ class School(BaseModel): #: list needs the short one and the card the long one. address: str | None = None city: str | None = None + #: The region as the register writes it — «Респ Татарстан», «г Москва». + #: Shown when nothing better is known, and matched against the catalog's + #: spellings when :attr:`region_code` is missing. region: str | None = None + #: The region's two-digit subject code, cut from the address's KLADR id + #: («1600000000000» → «16»), or ``None`` when the row carries none. A code + #: rather than the name because the name comes in several spellings and + #: the code in one, so it is what places a school in the region catalog + #: first. Not on ``SchoolOut``: the bot and ``/manage/schools`` never + #: needed it, and adding it there would be a wire change for nothing. + region_code: str | None = None #: Whether the register still considers it operating. A liquidated school #: is kept rather than hidden: a class created in May may well belong to #: one merged over the summer, and «ликвидирована» beside the name is more diff --git a/server/app/schemas.py b/server/app/schemas.py index 47403dec..cf6a809f 100644 --- a/server/app/schemas.py +++ b/server/app/schemas.py @@ -1514,3 +1514,53 @@ class RequestDecisionOut(BaseModel): # The role actually granted, or ``null`` for a declined request. role: RoleName | None = None who: str + + +# --------------------------------------------------------------------------- +# The school directory, anonymous: which regions a school may be in +# --------------------------------------------------------------------------- + + +class SchoolRegionOut(BaseModel): + """One region the search found schools in.""" + + #: The region catalog's key («tatarstan»), the one the phone's bundled copy + #: of the same catalog knows. ``null`` when the directory named a region + #: the catalog cannot place — then ``label`` says what it called it. + region: str | None = None + #: The two-digit subject code: the catalog's for a placed region, the + #: directory's own for one it could not place. + code: str | None = None + #: The directory's own name for the region («г Байконур»), and only for + #: an unplaced one: a placed region is named from the catalog, in the + #: reader's language. + label: str | None = None + #: Hits in this region among the twenty the directory returns at most. + schools: int + #: Up to three towns, best-ranked first. + cities: list[str] = Field(default_factory=list) + #: Up to three school names as a person writes them. + examples: list[str] = Field(default_factory=list) + + +class SchoolRegionsOut(BaseModel): + """What ``GET /api/v1/directory/school-regions`` answers. + + Picking the region from the list always works; this only saves the + scrolling. So every failure of it is a 503 that says «выберите регион из + списка», and an answer that places nothing is an empty list rather than + an error. + """ + + #: As searched: whitespace collapsed, cut to 150 characters. + query: str + #: Best-ranked region first, at most ten. + regions: list[SchoolRegionOut] = Field(default_factory=list) + #: The directory's own ceiling of twenty was reached, so these are the + #: regions of the first twenty matches, not of all of them. + truncated: bool = False + #: The name is too common to place — «школа № 5» is in every region. + #: Answered with no upstream call when the name is only a kind of school + #: and a small number; after one when twenty matches span four regions or + #: more. The phone says so and shows the list. + generic: bool = False diff --git a/server/app/security.py b/server/app/security.py index e1ca3b85..43462c4b 100644 --- a/server/app/security.py +++ b/server/app/security.py @@ -80,7 +80,7 @@ def normalise_phone(raw: str) -> str: class JoinThrottle: - """Sliding-window limit on failed join attempts, counted in the database. + """Sliding-window limit on attempts per caller, counted in the database. Not in memory. The previous implementation kept a dict and justified it on the deployment being "a single uvicorn worker sharing one event loop" — true @@ -90,12 +90,21 @@ class JoinThrottle: the endpoint it guards hands out a permanent read token for a real class's timetable, homework and teacher names. - Only failures are recorded, so a classroom of pupils joining from one school - NAT is never blocked by each other's successes. + `/join` and the diary sign-in record only failures, so a classroom of + pupils joining from one school NAT is never blocked by each other's + successes. The school directory records every call (:meth:`record`), + because there each call spends a request from an allowance somebody else + pays for, whether or not it finds anything. - Both methods take the caller's session and are awaited inside the request, + **Every instance must use the same window.** They share one table, and + each recorded attempt prunes the *whole* table to its own window, not just + its own key's rows — so a limiter with a longer window than the others + would have its history cut to theirs without anything saying so. + ``test_every_throttle_on_the_attempts_table_uses_one_window`` holds it. + + Every method takes the caller's session and is awaited inside the request, which makes this a couple of indexed queries on a table holding one window's - worth of failures. That is the price of a limit that is real. + worth of attempts. That is the price of a limit that is real. """ __slots__ = ("limit", "window") @@ -135,7 +144,20 @@ async def blocked_for(self, session: AsyncSession, key: str) -> float | None: return max(remaining, 0.0) async def record_failure(self, session: AsyncSession, key: str) -> None: - """Counts one failed attempt, and clears out expired ones.""" + """Counts one failed attempt, and clears out expired ones. + + A name for what `/join` and the diary sign-in count, which is only what + went wrong. It is the same row as :meth:`record`'s. + """ + await self.record(session, key) + + async def record(self, session: AsyncSession, key: str) -> None: + """Counts one attempt, whatever came of it, and clears out expired ones. + + For a caller that counts every call rather than only the failures — + the school directory, where a search that finds its school has spent + the same upstream request as one that finds nothing. Commits. + """ from app.models import JoinAttempt now = _utcnow() diff --git a/server/app/services/quota.py b/server/app/services/quota.py new file mode 100644 index 00000000..b2a8a0e3 --- /dev/null +++ b/server/app/services/quota.py @@ -0,0 +1,156 @@ +"""Daily allowances of somebody else's service, spent from the database. + +One exists today: DaData's ten thousand requests a day, which the bot and +``/manage/schools`` spend behind a class admin and the anonymous school +directory spends for anybody at all. The anonymous door gets a fixed share and +stops there, so that no amount of anonymous searching leaves an admin creating +a class with «Лимит запросов исчерпан». + +Counted in ``usage_counters`` (migration ``0016``), not in memory and not in +``join_attempts``. Not in memory for the reason ``JoinThrottle`` gives: on +Vercel every concurrent invocation is its own process. Not in +``join_attempts`` because that table is pruned to fifteen minutes on every +recorded attempt, and a day's count kept there would quietly become a quarter +of an hour's. + +The spend is one statement — insert the day's row or add to it, but only while +the sum stays under the cap — so two invocations spending the last unit at the +same instant cannot both have it. There is no read-then-write here for them to +race through. +""" + +from __future__ import annotations + +import math +from datetime import UTC, datetime, time, timedelta +from datetime import date as Date +from zoneinfo import ZoneInfo + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models import UsageCounter + +#: The anonymous directory's share of DaData's allowance. +DADATA_ANONYMOUS = "dadata:anon" + +#: Of DaData's 10,000 a day, which counts every kind of suggestion together. +#: The other 6,000 are the bot's and ``/manage/schools``', which nothing here +#: meters: those are admins creating a class, a few searches each, and they are +#: the ones this cap exists to protect. +ANONYMOUS_DAILY_UNITS = 4000 + +#: Where a day starts. DaData is a Moscow company and its allowance is assumed +#: to reset at Moscow midnight — assumed, because nothing in its documentation +#: says which clock it counts by. If it counts in UTC the worst case is two +#: anonymous days' worth inside one of DaData's, 8,000, which still leaves the +#: admins two thousand. +QUOTA_ZONE = ZoneInfo("Europe/Moscow") + + +class AllowanceSpent(Exception): + """Today's share is gone; ``retry_after`` seconds until the next day's.""" + + def __init__(self, retry_after: int) -> None: + super().__init__(f"the daily allowance is spent; it resets in {retry_after} s") + self.retry_after = retry_after + + +def _aware(now: datetime | None) -> datetime: + # A naive `now` is UTC, which is what every other clock in this project + # hands around (`security._utcnow`); reading it as the server's local time + # would move the day's boundary with the host. + if now is None: + return datetime.now(UTC) + return now if now.tzinfo is not None else now.replace(tzinfo=UTC) + + +def quota_day(now: datetime | None = None) -> Date: + """The day an allowance is counted against: today in :data:`QUOTA_ZONE`.""" + return _aware(now).astimezone(QUOTA_ZONE).date() + + +def seconds_to_reset(now: datetime | None = None) -> int: + """Whole seconds until the next day in :data:`QUOTA_ZONE`, never 0. + + Never 0, because it goes into ``Retry-After`` and a client told to wait + no time at all asks again at once and is refused again. + """ + moment = _aware(now) + tomorrow = quota_day(moment) + timedelta(days=1) + midnight = datetime.combine(tomorrow, time.min, tzinfo=QUOTA_ZONE) + # Both sides in UTC: two datetimes sharing one tzinfo subtract as wall + # clocks, which is an hour out across a DST change. Moscow keeps none + # today; the zone is a constant somebody may change. + remaining = (midnight.astimezone(UTC) - moment.astimezone(UTC)).total_seconds() + return max(1, math.ceil(remaining)) + + +async def spend( + session: AsyncSession, scope: str, units: int, *, cap: int, day: Date +) -> bool: + """Take ``units`` from ``scope``'s allowance for ``day``, or refuse. + + One statement: ``INSERT (scope, day, units) ON CONFLICT (scope, day) DO + UPDATE SET used = used + units WHERE used + units <= cap RETURNING used``. + A row comes back when the units were taken; none when the ``WHERE`` held + the row as it was, which is a refusal that changed nothing. Postgres and + SQLite (3.35 and later) both read it, and both are what this runs on. + + Commits, because a unit that was spent is spent whatever the request does + next: it is about to become a request to DaData, which counts it either + way. + + @return whether the units were taken. + """ + if units <= 0: + raise ValueError("spend at least one unit") + # The insert that opens a day is not guarded by the WHERE, which only + # applies to the update, so a first spend larger than the cap is refused + # here instead. + if units > cap: + return False + + statement = ( + _upsert(session.get_bind().dialect.name) + .values(scope=scope, day=day, used=units) + .on_conflict_do_update( + index_elements=[UsageCounter.scope, UsageCounter.day], + set_={"used": UsageCounter.used + units}, + where=UsageCounter.used + units <= cap, + ) + .returning(UsageCounter.used) + ) + taken = (await session.execute(statement)).scalar_one_or_none() + await session.commit() + return taken is not None + + +async def used(session: AsyncSession, scope: str, day: Date) -> int: + """How much of ``scope`` has been spent on ``day``; 0 for a day not begun. + + A column read, not ``session.get``: the spend writes past the ORM, and the + session factory does not expire on commit, so an object loaded before a + spend would go on reporting the count from before it. + """ + spent = await session.scalar( + select(UsageCounter.used).where(UsageCounter.scope == scope, UsageCounter.day == day) + ) + return spent or 0 + + +def _upsert(dialect: str): + """The insert that can say ``ON CONFLICT``, which is each dialect's own. + + Imported by the dialect in use: a SQLite process never needs Postgres's + compiler loaded, and this is on the path of an anonymous request. + """ + if dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert as postgres_insert + + return postgres_insert(UsageCounter) + if dialect == "sqlite": + from sqlalchemy.dialects.sqlite import insert as sqlite_insert + + return sqlite_insert(UsageCounter) + raise NotImplementedError(f"no atomic spend on {dialect}") diff --git a/server/app/services/schools.py b/server/app/services/schools.py index 4a2ad2bc..e59d36cd 100644 --- a/server/app/services/schools.py +++ b/server/app/services/schools.py @@ -13,15 +13,31 @@ query. Pretending otherwise would show «стр. 1 из 4» for a search that matched three hundred schools and quietly hide the other 280. -Nothing here touches the database. A school is stored as its name on -``SchoolClass.school``, which is what the class card has always shown. +Searching for a class touches no table: a school is stored as its name on +``SchoolClass.school``, which is what the class card has always shown. The +anonymous directory (:func:`regions_for`) is the one caller that writes, and +only to spend from its daily share of the upstream's allowance +(``services/quota.py``). + +**Two questions, one search.** The bot and ``/manage/schools`` ask «which +school is this» and get a page of schools. The phone, before it knows anything +about the person holding it, asks «which region is a school of this name in» +and gets the same twenty rows grouped by region — so that «лицей 1535» can +answer «Москва» and the region list can open on it. Same upstream, same query +rules, same errors; only what is done with the rows differs. """ from __future__ import annotations -from dataclasses import dataclass +import re +from dataclasses import dataclass, field +from datetime import datetime + +from sqlalchemy.ext.asyncio import AsyncSession +from app import catalog from app.providers import dadata +from app.services import quota #: Five to a screen. A Telegram inline keyboard of school names is one button #: per row — the names are long — and more than five turns the message into a @@ -136,3 +152,169 @@ def page_of( def stored_name(school: dadata.School) -> str: """What goes on ``SchoolClass.school`` once one is picked.""" return school.name[:MAX_NAME] + + +# --------------------------------------------------------------------------- +# Which regions a school of this name is in +# --------------------------------------------------------------------------- + +#: The most regions one answer names. Twenty rows can in principle be twenty +#: regions, and a list of twenty is the region picker again rather than an +#: answer. +REGION_GROUPS_MAX = 10 + +#: A full answer spread over this many regions or more is a name too common to +#: place — «Гимназия № 1» is in every one of them, and twenty rows are twenty of +#: several hundred — so the answer is «выберите регион», not a guess. +GENERIC_REGIONS = 4 + +#: What a group shows of itself: a few towns and a few names, enough to +#: recognise one's own school by, never the whole list. +GROUP_CITIES = 3 +GROUP_EXAMPLES = 3 + +#: A token of a folded query: the numero sign alone, a run of digits, or a run +#: of letters. The numero sign is its own token because people type «№5» as +#: often as «№ 5», and the catalog's list names it on its own. +_TOKENS = re.compile(r"№|\d+|[^\W\d_]+") + + +def _fold(text: str) -> str: + return text.casefold().replace("ё", "е") + + +def is_generic(query: str) -> bool: + """Whether ``query`` names a kind of school and a small number, and nothing else. + + «Школа № 5», «СОШ 12» and «гимназия 3» are in every region there is, so + asking the directory for them spends an upstream request on twenty rows + from twenty places and places nothing. With the words a school's name is + *made of* taken away (``catalog.school_words()``, the same list the phone + reads), what is left has to be something that tells schools apart: a + town, a name, or a number of three digits or more. «лицей 1535» and + «гимназия 1 Казань» are asked; «гимназия 3» is not. + """ + words = {_fold(word) for word in catalog.school_words()} + left = [token for token in _TOKENS.findall(_fold(query)) if token not in words] + return all(token.isdigit() and len(token) <= 2 for token in left) + + +@dataclass +class RegionGroup: + """The hits of one search that are in one region.""" + + #: The catalog's key, or ``None`` when the directory named a region the + #: catalog cannot place — then ``label`` is what the directory called it. + region: str | None + #: The two-digit subject code: the catalog's for a region it placed, the + #: directory's own for one it could not. + code: str | None + label: str | None + schools: int = 0 + cities: list[str] = field(default_factory=list) + examples: list[str] = field(default_factory=list) + + def add(self, school: dadata.School) -> None: + self.schools += 1 + if school.city and school.city not in self.cities and len(self.cities) < GROUP_CITIES: + self.cities.append(school.city) + if school.name not in self.examples and len(self.examples) < GROUP_EXAMPLES: + self.examples.append(school.name) + + +@dataclass(frozen=True) +class RegionSearch: + """Everything one «which region» search found.""" + + #: As searched: normalised and cut to :data:`MAX_QUERY`. + query: str + groups: list[RegionGroup] = field(default_factory=list) + #: The upstream's ceiling was reached; see :class:`SearchResult`. + truncated: bool = False + #: Too common to place — said instead of a list, or on top of one. + generic: bool = False + + +def place(school: dadata.School) -> catalog.CatalogRegion | None: + """The catalog region a register row is in, or ``None``. + + By code first, because the code has one spelling and the name several; by + the register's own name for the region only when the row carries no code + the catalog knows. Never by a partial name — that is ``by_dadata_name``'s + rule, and the reason «Алтай» cannot land in «Алтайский край». + """ + return catalog.by_code(school.region_code) or catalog.by_dadata_name(school.region) + + +def group_by_region(schools: list[dadata.School]) -> list[RegionGroup]: + """The schools, grouped by the region each is in, best-ranked region first. + + A group's place is its best hit's, and since the rows arrive in the + upstream's rank order that is simply the order the groups were first seen + in — no two hits share a rank, so there is never a tie to break by size. + A row that names no region at all — no code, no name — is left out: a + group without a region is no answer to «which region». + """ + groups: dict[tuple[str | None, ...], RegionGroup] = {} + for school in schools: + region = place(school) + if region is not None: + key: tuple[str | None, ...] = ("catalog", region.key) + group = groups.get(key) or RegionGroup(region=region.key, code=region.code, label=None) + elif school.region_code or school.region: + # Kept apart by the register's own spelling, folded like the + # catalog folds it, so «г Байконур» and «г. Байконур» are one. + key = ("register", school.region_code, catalog.normalise_name(school.region or "")) + group = groups.get(key) or RegionGroup( + region=None, code=school.region_code, label=school.region + ) + else: + continue + group.add(school) + groups[key] = group + return list(groups.values()) + + +async def regions_for( + session: AsyncSession, raw_query: str | None, *, now: datetime | None = None +) -> RegionSearch: + """The regions a school called ``raw_query`` may be in. + + A generic name is answered here, with no upstream call and nothing spent. + Anything else spends one unit of the anonymous daily share before it is + sent, and a second only if the upstream's empty-answer retry is made — + which it is not, when that second unit is not there. + + @raises SearchError when the query is too short to search with. + @raises quota.AllowanceSpent when today's anonymous share is gone. + @raises app.providers.dadata.DirectoryError when the directory is not + configured, not answering, or answering something new. + """ + query = normalise_query(raw_query) + if is_generic(query): + return RegionSearch(query=query, generic=True) + + day = quota.quota_day(now) + + async def spend_one() -> bool: + # The cap is read at the call, not bound at import, so the allowance + # can be changed in one place and a test can lower it. + return await quota.spend( + session, quota.DADATA_ANONYMOUS, 1, cap=quota.ANONYMOUS_DAILY_UNITS, day=day + ) + + if not await spend_one(): + raise quota.AllowanceSpent(quota.seconds_to_reset(now)) + + items = await dadata.suggest_schools(query, may_retry=spend_one) + groups = group_by_region(dadata.to_schools(items, per_region=True)) + truncated = len(items) >= dadata.MAX_SUGGESTIONS + return RegionSearch( + query=query, + groups=groups[:REGION_GROUPS_MAX], + truncated=truncated, + # Only a *full* answer can be too common to place: fewer than twenty + # rows is everything the register has, and five regions of it is five + # real answers. + generic=truncated and len(groups) >= GENERIC_REGIONS, + ) diff --git a/server/migrations/versions/0016_usage_counters.py b/server/migrations/versions/0016_usage_counters.py new file mode 100644 index 00000000..b39437fe --- /dev/null +++ b/server/migrations/versions/0016_usage_counters.py @@ -0,0 +1,76 @@ +"""Count the anonymous school directory's share of DaData's daily allowance. + +Revision ID: 0016 +Revises: 0015 +Create Date: 2026-09-25 + +The phone asks ``GET /api/v1/directory/school-regions`` before it belongs to +any class, so nothing about the caller is known and a per-address throttle is +the only other limit on it. DaData's key allows ten thousand requests a day, +and the bot and ``/manage/schools`` need that same allowance to create a +class. ``usage_counters`` holds one row per allowance per day, spent atomically +by ``services/quota.spend``, so the anonymous door stops at its own share and +never reaches the admins'. + +A table of its own rather than rows in ``join_attempts``: that table is pruned +to the shortest throttle window on every recorded attempt and by the cron after +an hour, which would cut a day's count to fifteen minutes. + +**Destroys nothing.** One new table; no existing row is read or rewritten. + +**Apply this BEFORE the merge**, the ordinary additive order: the new code +spends from the table, and the old code never mentions it. + +The DDL is the model's own, as ``CLAUDE.md`` requires — +``CreateTable(UsageCounter.__table__).compile(dialect=postgresql.dialect())`` +prints exactly:: + + CREATE TABLE usage_counters ( + scope VARCHAR(32) NOT NULL, + day DATE NOT NULL, + used INTEGER NOT NULL, + PRIMARY KEY (scope, day) + ) + +``tests/test_quota.py`` holds the revision to that text. Applied through the +Neon connector with ``alembic_version`` stamped in the same transaction; on +local SQLite the table arrives through ``create_all``, which is why the guard +below asks first. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import context, op + +revision: str = "0016" +down_revision: str | None = "0015" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def _missing(table: str) -> bool: + # A database built by `create_all` after the model landed — `0001` on an + # empty file, or `scripts.init_db` — already has the table, and creating it + # again is a hard error rather than a no-op. + if context.is_offline_mode(): + return True + return not sa.inspect(op.get_bind()).has_table(table) + + +def upgrade() -> None: + if not _missing("usage_counters"): + return + op.create_table( + "usage_counters", + sa.Column("scope", sa.String(length=32), nullable=False), + sa.Column("day", sa.Date(), nullable=False), + sa.Column("used", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("scope", "day"), + ) + + +def downgrade() -> None: + op.drop_table("usage_counters") diff --git a/server/tests/test_directory.py b/server/tests/test_directory.py new file mode 100644 index 00000000..a1afdde6 --- /dev/null +++ b/server/tests/test_directory.py @@ -0,0 +1,503 @@ +"""The anonymous school directory: ``GET /api/v1/directory/school-regions``. + +What a phone with no class asks on its first screen — «which regions is a +school of this name in» — and everything that stands between that question and +somebody else's allowance: + +- the answer is the directory's twenty rows grouped by the region catalog's + keys, best-ranked region first, placed by the KLADR code before the name; +- a name too common to place is said to be, and «школа № 5» costs no upstream + request at all; +- every call past validation counts against its caller, twenty in a quarter + of an hour, on the table `/join` counts in and with `/join`'s window; +- every upstream request is spent from the anonymous daily share, the + empty-answer retry included, while the bot's search is not metered here at + all. + +Nothing reaches DaData: the pooled client is replaced by one over +``httpx.MockTransport`` that answers each request with the next body and +keeps what was sent. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import httpx +import pytest +from httpx import ASGITransport +from sqlalchemy import func, select + +from app.api import cron, diary, directory, public +from app.config import get_settings +from app.main import app +from app.models import JoinAttempt, UsageCounter +from app.providers.dadata import client as dadata_client +from app.services import quota +from app.services import schools as schools_service + +APP = Path(__file__).resolve().parent.parent / "app" +PATH = "/api/v1/directory/school-regions" + + +def row( + name: str, + *, + ogrn: str, + city: str | None = None, + region: str | None = None, + kladr: str | None = None, +) -> dict: + """One ``suggest/party`` suggestion, carrying only what the mapper reads.""" + address: dict = {} + if city: + address["city"] = city + if region: + address["region_with_type"] = region + if kladr: + address["region_kladr_id"] = kladr + return { + "value": name, + "data": { + "ogrn": ogrn, + "okved": "85.14", + "name": {"short_with_opf": name}, + "state": {"status": "ACTIVE"}, + "address": {"value": city or "", "data": address}, + }, + } + + +@pytest.fixture +async def client(): + transport = ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac + + +@pytest.fixture +def upstream(monkeypatch): + """A configured directory answering with ``answer(...)``'s bodies in turn. + + ``sent`` is every request that went out, because how many went out is + what the allowance is counted in. + """ + monkeypatch.setattr(get_settings(), "dadata_token", "") + sent: list[httpx.Request] = [] + bodies: list[object] = [{"suggestions": []}] + + def handler(request: httpx.Request) -> httpx.Response: + sent.append(request) + body = bodies[min(len(sent) - 1, len(bodies) - 1)] + if isinstance(body, httpx.Response): + return body + return httpx.Response(200, json=body) + + fake = httpx.AsyncClient( + base_url=dadata_client.BASE_URL, transport=httpx.MockTransport(handler) + ) + + async def shared(): + return fake + + monkeypatch.setattr(dadata_client, "shared_client", shared) + + class Upstream: + requests = sent + + @staticmethod + def answer(*answers: object) -> None: + bodies[:] = [ + a if isinstance(a, httpx.Response) else {"suggestions": a} for a in answers + ] + + return Upstream + + +async def _attempts(session) -> int: + return await session.scalar(select(func.count()).select_from(JoinAttempt)) or 0 + + +async def _spent_today(session) -> int: + return await quota.used(session, quota.DADATA_ANONYMOUS, quota.quota_day()) + + +# ---- the answer ------------------------------------------------------------- + + +async def test_a_distinctive_name_is_grouped_by_region_best_first(client, upstream): + upstream.answer( + [ + row('ГБОУ "ЛИЦЕЙ № 1535"', ogrn="1", city="Москва", kladr="7700000000000"), + row('МБОУ "ЛИЦЕЙ № 1535"', ogrn="2", city="Казань", kladr="1600000000000"), + row('ГБОУ "ЛИЦЕЙ № 1535" КОРПУС 2', ogrn="3", city="Москва", kladr="7700000000000"), + row('МАОУ "ЛИЦЕЙ № 1535"', ogrn="4", city="Набережные Челны", kladr="1600000000000"), + row('МБОУ "ЛИЦЕЙ № 1535 Б"', ogrn="5", city="Елабуга", kladr="1600000000000"), + row('МБОУ "ЛИЦЕЙ № 1535 В"', ogrn="6", city="Альметьевск", kladr="1600000000000"), + ] + ) + + response = await client.get(PATH, params={"q": " лицей 1535 "}) + + assert response.status_code == 200, response.text + body = response.json() + assert body["query"] == "лицей 1535" + assert body["truncated"] is False and body["generic"] is False + # Moscow first because its first hit was ranked first, although Tatarstan + # has more of them: the upstream's rank is what says which school is meant. + assert [(r["region"], r["code"], r["schools"]) for r in body["regions"]] == [ + ("moscow", "77", 2), + ("tatarstan", "16", 4), + ] + moscow, tatarstan = body["regions"] + assert moscow["cities"] == ["Москва"] + assert moscow["examples"] == ['ГБОУ "Лицей № 1535"', 'ГБОУ "Лицей № 1535" корпус 2'] + # Three towns and three names at most, in rank order: a hint, not a list. + assert tatarstan["cities"] == ["Казань", "Набережные Челны", "Елабуга"] + assert len(tatarstan["examples"]) == 3 + # A placed region is named by the catalog, in the reader's language. + assert moscow["label"] is None and tatarstan["label"] is None + assert len(upstream.requests) == 1 + + +async def test_the_region_comes_from_the_kladr_code(client, upstream): + """The code has one spelling and the name several, so the code wins — + even over a name the catalog would have read as somewhere else.""" + upstream.answer( + [row('МБОУ "ЛИЦЕЙ № 1535"', ogrn="1", region="Респ Башкортостан", kladr="1600000000000")] + ) + + body = (await client.get(PATH, params={"q": "лицей 1535"})).json() + + assert [r["region"] for r in body["regions"]] == ["tatarstan"] + + +async def test_the_region_falls_back_to_its_name_without_a_code(client, upstream): + """Whether party rows carry ``region_kladr_id`` at all is unverified, so + the register's own name for the region is the second way in.""" + upstream.answer( + [ + row('МБОУ "ЛИЦЕЙ № 1535"', ogrn="1", region="Респ Татарстан"), + row('МБОУ "ЛИЦЕЙ № 1535 А"', ogrn="2", region="Респ Татарстан", kladr="ab00000000000"), + ] + ) + + body = (await client.get(PATH, params={"q": "лицей 1535"})).json() + + assert [(r["region"], r["code"], r["schools"]) for r in body["regions"]] == [ + ("tatarstan", "16", 2) + ] + + +async def test_a_region_the_catalog_cannot_place_comes_back_with_its_label(client, upstream): + """Baikonur is leased, not a subject: it has a KLADR code (99) and no + place in the catalog. Said with the register's own words rather than + dropped or forced into the nearest name.""" + upstream.answer( + [ + row('МБОУ "ШКОЛА № 245"', ogrn="1", city="Байконур", region="г Байконур", + kladr="9900000000000"), + row('МБОУ "ШКОЛА № 245"', ogrn="2", city="Казань", kladr="1600000000000"), + # Nothing at all about where: no answer to «which region», left out. + row('АНО "ШКОЛА № 245"', ogrn="3"), + ] + ) + + body = (await client.get(PATH, params={"q": "школа 245"})).json() + + assert body["regions"] == [ + { + "region": None, + "code": "99", + "label": "г Байконур", + "schools": 1, + "cities": ["Байконур"], + "examples": ['МБОУ "Школа № 245"'], + }, + { + "region": "tatarstan", + "code": "16", + "label": None, + "schools": 1, + "cities": ["Казань"], + "examples": ['МБОУ "Школа № 245"'], + }, + ] + + +async def test_a_branch_in_another_region_is_not_folded_into_its_head(client, upstream): + """A филиал is registered under its head school's OGRN. The bot's picker + has always shown the two as one, and still does; the directory's question + is about regions, and there are two of them.""" + head = row('ГБОУ "ШКОЛА № 1580"', ogrn="1027700000001", city="Москва", kladr="7700000000000") + branch = row( + 'ФИЛИАЛ ГБОУ "ШКОЛА № 1580"', ogrn="1027700000001", city="Химки", kladr="5000000000000" + ) + upstream.answer([head, branch]) + + body = (await client.get(PATH, params={"q": "школа 1580"})).json() + assert [r["region"] for r in body["regions"]] == ["moscow", "moscow-oblast"] + + found = await schools_service.search("школа 1580") + assert len(found.schools) == 1 + + +async def test_a_type_word_and_a_short_number_is_answered_without_dadata( + client, upstream, session +): + for query in ["Школа № 5", "СОШ 12", "гимназия 3", "МБОУ СОШ №7", "лицей N 2"]: + response = await client.get(PATH, params={"q": query}) + assert response.status_code == 200, query + assert response.json()["generic"] is True, query + assert response.json()["regions"] == [] + + assert upstream.requests == [] + assert await _spent_today(session) == 0 + + # And a name that does tell schools apart is asked. + upstream.answer([row('ГБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="7700000000000")]) + for query in ["лицей 1535", "гимназия 1 Казань"]: + assert (await client.get(PATH, params={"q": query})).json()["generic"] is False + assert len(upstream.requests) == 2 + + +async def test_twenty_hits_across_many_regions_is_generic(client, upstream): + codes = ["77", "78", "16", "50", "66"] + upstream.answer( + [ + row(f'МБОУ "ГИМНАЗИЯ № 1{i}"', ogrn=str(i), kladr=f"{codes[i % 5]}00000000000") + for i in range(20) + ] + ) + + body = (await client.get(PATH, params={"q": "гимназия 1 имени"})).json() + + assert body["truncated"] is True + assert body["generic"] is True + # Still said, for a phone that wants to offer them: generic is on top of + # the list, not instead of it. + assert len(body["regions"]) == 5 + + +async def test_fewer_than_twenty_hits_in_many_regions_is_a_real_answer(client, upstream): + """Nineteen rows is everything the register has, so five regions of it are + five places the school really is.""" + codes = ["77", "78", "16", "50", "66"] + upstream.answer( + [row(f'МБОУ "ЛИЦЕЙ № 1{i}"', ogrn=str(i), kladr=f"{codes[i % 5]}00000000000") + for i in range(19)] + ) + + body = (await client.get(PATH, params={"q": "лицей имени"})).json() + + assert body["truncated"] is False + assert body["generic"] is False + + +async def test_at_most_ten_regions_are_named(client, upstream): + codes = [f"{n:02d}" for n in range(1, 21)] + upstream.answer( + [row(f'МБОУ "ЛИЦЕЙ № {i}"', ogrn=str(i), kladr=f"{codes[i]}00000000000") for i in range(20)] + ) + + body = (await client.get(PATH, params={"q": "лицей имени"})).json() + + assert len(body["regions"]) == schools_service.REGION_GROUPS_MAX == 10 + assert [r["code"] for r in body["regions"]] == codes[:10] + + +# ---- what it refuses, and what it counts ------------------------------------ + + +async def test_a_short_query_is_422_and_spends_nothing(client, upstream, session): + for params in [{"q": "шк"}, {"q": " "}, {}]: + response = await client.get(PATH, params=params) + assert response.status_code == 422 + assert "3 символа" in response.json()["detail"] + + assert upstream.requests == [] + assert await _attempts(session) == 0 + assert await _spent_today(session) == 0 + + +async def test_every_call_counts_against_the_caller(client, upstream, session, monkeypatch): + """A search that finds its school spent the same upstream request as one + that finds nothing, so success is counted too — unlike `/join`, where a + classroom's successes must never lock the classroom out.""" + upstream.answer([row('ГБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="7700000000000")]) + for _ in range(10): + assert (await client.get(PATH, params={"q": "лицей 1535"})).status_code == 200 + for _ in range(5): + assert (await client.get(PATH, params={"q": "школа 5"})).status_code == 200 + # A refusal past validation is a call too. + monkeypatch.setattr(get_settings(), "dadata_token", "") + for _ in range(5): + assert (await client.get(PATH, params={"q": "лицей 1535"})).status_code == 503 + + assert await _attempts(session) == 20 + refused = await client.get(PATH, params={"q": "лицей 1535"}) + assert refused.status_code == 429 + assert 0 < int(refused.headers["Retry-After"]) <= 901 + # Refused at the door: not counted again, and nothing went upstream. + assert await _attempts(session) == 20 + assert len(upstream.requests) == 10 + + # Its own bucket: twenty searches have not spent a phone's join attempts. + joined = await client.post("/api/v1/join", json={"code": "NOSUCH12"}) + assert joined.status_code == 404 + + +async def test_the_daily_allowance_stops_the_search_and_says_until_when( + client, upstream, session, monkeypatch +): + monkeypatch.setattr(quota, "ANONYMOUS_DAILY_UNITS", 2) + upstream.answer([row('ГБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="7700000000000")]) + for _ in range(2): + assert (await client.get(PATH, params={"q": "лицей 1535"})).status_code == 200 + assert await _spent_today(session) == 2 + + longest = quota.seconds_to_reset() + response = await client.get(PATH, params={"q": "лицей 1535"}) + shortest = quota.seconds_to_reset() + + assert response.status_code == 503 + assert response.headers["X-Directory-Unavailable"] == "spent" + assert "на сегодня" in response.json()["detail"] + assert "выберите регион" in response.json()["detail"] + # Until Moscow midnight, when the next day's share begins. + assert shortest <= int(response.headers["Retry-After"]) <= longest + assert len(upstream.requests) == 2 + assert await _spent_today(session) == 2 + + # A generic name never needed the allowance, so it is still answered. + assert (await client.get(PATH, params={"q": "школа 5"})).json()["generic"] is True + + +async def test_the_empty_result_retry_is_charged_and_skipped_when_nothing_is_left( + client, upstream, session, monkeypatch +): + """The retry without the ОКВЭД filter is a second DaData request, and a + unit is a request: it is asked for, and not made when it is not there.""" + monkeypatch.setattr(quota, "ANONYMOUS_DAILY_UNITS", 3) + upstream.answer([], [row('МБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="1600000000000")]) + + first = await client.get(PATH, params={"q": "лицей 1535"}) + assert [r["region"] for r in first.json()["regions"]] == ["tatarstan"] + assert len(upstream.requests) == 2 + assert await _spent_today(session) == 2 + + # One unit left: the first request has it, the retry does not happen, and + # the answer is an honest empty one rather than an error. + upstream.answer([]) + second = await client.get(PATH, params={"q": "лицей 1535"}) + assert second.status_code == 200 + assert second.json()["regions"] == [] + assert len(upstream.requests) == 3 + assert await _spent_today(session) == 3 + + +async def test_the_bots_search_is_not_charged_to_the_anonymous_allowance(upstream, session): + """The bot and `/manage/schools` are admins creating a class — the ones + the anonymous cap exists to protect. Their search is exactly what it was: + unmetered here, retrying on an empty answer as it always has.""" + upstream.answer([], [row('МБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="1600000000000")]) + + found = await schools_service.search("лицей 1535") + + assert [school.region_code for school in found.schools] == ["16"] + assert len(upstream.requests) == 2 + assert await session.scalar(select(func.count()).select_from(UsageCounter)) == 0 + + +async def test_a_spend_past_the_cap_changes_nothing(session): + day = quota.quota_day() + + taken = [await quota.spend(session, "test:scope", 1, cap=2, day=day) for _ in range(4)] + + assert taken == [True, True, False, False] + assert await quota.used(session, "test:scope", day) == 2 + # A spend that would cross the cap is refused whole, not in part. + assert await quota.spend(session, "test:other", 1, cap=2, day=day) + assert not await quota.spend(session, "test:other", 2, cap=2, day=day) + assert await quota.used(session, "test:other", day) == 1 + + +async def test_without_a_dadata_key_it_is_503(client, monkeypatch, session): + monkeypatch.setattr(get_settings(), "dadata_token", " ") + + response = await client.get(PATH, params={"q": "лицей 1535"}) + + assert response.status_code == 503 + assert response.headers["X-Directory-Unavailable"] == "disabled" + assert response.json()["detail"] == directory.DISABLED_DETAIL + assert "Retry-After" not in response.headers + assert await _spent_today(session) == 0 + + +@pytest.mark.parametrize( + "answer", + [ + httpx.Response(503), + httpx.Response(429, json={"message": "Daily limit exceeded"}), + httpx.Response(200, text="maintenance"), + ], + ids=["down", "dadata-quota", "unreadable"], +) +async def test_a_directory_failure_is_503_and_offers_the_list(client, upstream, answer): + """The bot's sentences for these end «введите название вручную», which is + the bot's way out; the phone's is the region list.""" + upstream.answer(answer) + + response = await client.get(PATH, params={"q": "лицей 1535"}) + + assert response.status_code == 503 + assert response.headers["X-Directory-Unavailable"] == "upstream" + assert response.json()["detail"] == directory.UPSTREAM_DETAIL + assert "вручную" not in response.text + + +# ---- the table it shares ----------------------------------------------------- + + +def _throttles_built_in_app() -> list[tuple[str, ast.Call]]: + """Every ``JoinThrottle(...)`` written anywhere under ``app/``.""" + found = [] + for path in sorted(APP.rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + name = getattr(node.func, "id", None) or getattr(node.func, "attr", None) + if name == "JoinThrottle": + found.append((str(path.relative_to(APP)), node)) + return found + + +def test_every_throttle_on_the_attempts_table_uses_one_window(): + """Each recorded attempt prunes the **whole** table to its own limiter's + window, and the cron sweeps it to an hour. A limiter with a longer window + than the others would have its history silently cut to theirs; one with a + shorter window would cut theirs. So there is one window, and it is here. + + Found by reading the source rather than by listing the three known + limiters, so a fourth cannot arrive without being asked this. + """ + built = _throttles_built_in_app() + assert sorted(path for path, _ in built) == [ + "api/diary.py", + "api/directory.py", + "api/public.py", + ] + + for path, call in built: + window = next((k.value for k in call.keywords if k.arg == "window"), None) + if window is None and len(call.args) >= 2: + window = call.args[1] + assert isinstance(window, ast.Constant), path + assert float(window.value) == 900.0, path + + live = [public.join_limiter, diary.diary_login_limiter, directory.directory_limiter] + assert {limiter.window for limiter in live} == {900.0} + assert cron.JOIN_ATTEMPT_TTL.total_seconds() >= 900.0 + assert directory.directory_limiter.limit == 20 diff --git a/server/tests/test_quota.py b/server/tests/test_quota.py new file mode 100644 index 00000000..e3db75fd --- /dev/null +++ b/server/tests/test_quota.py @@ -0,0 +1,189 @@ +"""The daily allowance, and the revision that gives it a table. + +``services/quota.py`` counts somebody else's allowance per day in +``usage_counters``; ``0016`` is what makes that table on a database that +predates it. What is pinned here: + +- a day is Moscow's, and ``Retry-After`` runs to Moscow midnight, never 0; +- a spend is all or nothing and changes nothing when it is refused; +- the revision builds on Postgres exactly the DDL the model declares — the + rule ``CLAUDE.md`` sets for every revision, held by a test rather than by + whoever applies it — and on a database that lacks the table it creates it, + and on the way down drops it. + +Nothing here connects to Postgres. The Postgres half renders the revision +offline, the way ``alembic upgrade --sql`` would, in this process. +""" + +from __future__ import annotations + +import importlib.util +import io +import os +import sqlite3 +import subprocess +import sys +from datetime import UTC, date, datetime, timedelta, timezone +from pathlib import Path + +import pytest +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy.dialects import postgresql +from sqlalchemy.schema import CreateTable + +from app.models import UsageCounter +from app.services import quota + +SERVER_ROOT = Path(__file__).resolve().parent.parent +REVISION = SERVER_ROOT / "migrations" / "versions" / "0016_usage_counters.py" + + +# ---- the day -------------------------------------------------------------- + + +def test_the_day_is_moscows(): + """21:30 UTC on the 25th is half past midnight on the 26th in Moscow, and + the 26th's share is the one being spent.""" + assert quota.quota_day(datetime(2026, 9, 25, 20, 59, tzinfo=UTC)) == date(2026, 9, 25) + assert quota.quota_day(datetime(2026, 9, 25, 21, 30, tzinfo=UTC)) == date(2026, 9, 26) + + +def test_a_naive_now_is_read_as_utc_like_every_other_clock_here(): + assert quota.quota_day(datetime(2026, 9, 25, 21, 30)) == date(2026, 9, 26) + + +def test_the_reset_is_at_moscow_midnight_whatever_zone_now_is_in(): + ten_to = datetime(2026, 9, 25, 20, 50, tzinfo=UTC) + assert quota.seconds_to_reset(ten_to) == 600 + # The same instant written in another zone is the same ten minutes. + assert quota.seconds_to_reset(ten_to.astimezone(timezone(timedelta(hours=-7)))) == 600 + + +def test_the_reset_is_never_zero_seconds_away(): + """«Retry after 0» is «retry now», which is refused again at once.""" + midnight = datetime(2026, 9, 25, 21, 0, tzinfo=UTC) + assert quota.seconds_to_reset(midnight) == 24 * 3600 + assert quota.seconds_to_reset(midnight - timedelta(microseconds=1)) == 1 + + +# ---- the spend ------------------------------------------------------------ + + +async def test_scopes_and_days_are_counted_apart(session): + today, tomorrow = date(2026, 9, 25), date(2026, 9, 26) + + assert await quota.spend(session, "a", 2, cap=2, day=today) + assert not await quota.spend(session, "a", 1, cap=2, day=today) + assert await quota.spend(session, "b", 1, cap=2, day=today) + assert await quota.spend(session, "a", 1, cap=2, day=tomorrow) + + assert await quota.used(session, "a", today) == 2 + assert await quota.used(session, "b", today) == 1 + assert await quota.used(session, "a", tomorrow) == 1 + assert await quota.used(session, "c", today) == 0 + + +async def test_a_first_spend_larger_than_the_cap_writes_nothing(session): + """The insert that opens a day is not guarded by the update's WHERE, so + the refusal has to happen before it — or the day would open over the cap.""" + assert not await quota.spend(session, "a", 3, cap=2, day=date(2026, 9, 25)) + assert await quota.used(session, "a", date(2026, 9, 25)) == 0 + assert await session.get(UsageCounter, ("a", date(2026, 9, 25))) is None + + +async def test_a_spend_of_nothing_is_a_mistake_not_a_free_pass(session): + with pytest.raises(ValueError): + await quota.spend(session, "a", 0, cap=2, day=date(2026, 9, 25)) + + +# ---- the revision --------------------------------------------------------- + + +def _revision(): + spec = importlib.util.spec_from_file_location("revision_0016", REVISION) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _words(sql: str) -> str: + return " ".join(sql.replace(";", " ").split()) + + +def test_the_revision_builds_on_postgres_exactly_what_the_model_declares(monkeypatch): + """``CLAUDE.md``: take the DDL from the model. The revision's own + ``create_table`` is rendered for Postgres, offline, and has to be the + model's ``CREATE TABLE`` word for word — so a column changed in the model + and not here, or here and not in the model, fails before anybody applies + it through the Neon connector.""" + revision = _revision() + assert (revision.revision, revision.down_revision) == ("0016", "0015") + # Offline there is no database to ask whether the table exists; the + # module's own guard answers «missing» in that mode, as here. + monkeypatch.setattr(revision, "_missing", lambda table: True) + + rendered = io.StringIO() + context = MigrationContext.configure( + dialect_name="postgresql", opts={"as_sql": True, "output_buffer": rendered} + ) + with Operations.context(context): + revision.upgrade() + + model = CreateTable(UsageCounter.__table__).compile(dialect=postgresql.dialect()) + assert _words(rendered.getvalue()) == _words(str(model)) + + dropped = io.StringIO() + context = MigrationContext.configure( + dialect_name="postgresql", opts={"as_sql": True, "output_buffer": dropped} + ) + with Operations.context(context): + revision.downgrade() + assert _words(dropped.getvalue()) == "DROP TABLE usage_counters" + + +def _alembic(database: Path, *args: str) -> subprocess.CompletedProcess: + env = dict(os.environ, DATABASE_URL=f"sqlite+aiosqlite:///{database}") + return subprocess.run( + [sys.executable, "-m", "alembic", *args], + env=env, + cwd=str(SERVER_ROOT), + capture_output=True, + text=True, + ) + + +def test_the_revision_creates_the_table_where_it_is_missing_and_drops_it_going_down(tmp_path): + """Run for real, on a database that is at ``0015`` and has no such table. + + The chain from nothing never gets here — ``0001`` builds today's whole + schema, the table with it, and this revision finds it and does nothing, + which is the other half and is checked first. So the table is taken away + and the stamp put back, which is exactly a database that predates it. + """ + database = tmp_path / "quota.db" + database.touch() + + built = _alembic(database, "upgrade", "head") + assert built.returncode == 0, built.stderr + + with sqlite3.connect(database) as db: + db.execute("DROP TABLE usage_counters") + db.execute("UPDATE alembic_version SET version_num = '0015'") + + upgraded = _alembic(database, "upgrade", "head") + assert upgraded.returncode == 0, upgraded.stderr + with sqlite3.connect(database) as db: + columns = {row[1]: row for row in db.execute("PRAGMA table_info(usage_counters)")} + assert set(columns) == {"scope", "day", "used"} + # (cid, name, type, notnull, default, pk) + assert [columns[name][5] for name in ("scope", "day")] == [1, 2] + assert columns["used"][3] == 1 + assert db.execute("select version_num from alembic_version").fetchall() == [("0016",)] + + downgraded = _alembic(database, "downgrade", "0015") + assert downgraded.returncode == 0, downgraded.stderr + with sqlite3.connect(database) as db: + tables = {row[0] for row in db.execute("select name from sqlite_master")} + assert "usage_counters" not in tables + assert "join_attempts" in tables diff --git a/server/tests/test_schools.py b/server/tests/test_schools.py index bfed74af..29574d57 100644 --- a/server/tests/test_schools.py +++ b/server/tests/test_schools.py @@ -414,3 +414,88 @@ async def test_one_suggestion_of_the_wrong_shape_does_not_shout_or_lose_the_othe # One request, because the first answer was not empty. assert len(sent) == 1 + + +# ---- the region a row is in -------------------------------------------------- + + +def test_the_region_code_is_read_from_the_address_kladr_id(): + """The first two digits of the thirteen are the subject: «78» is Saint + Petersburg however the register spells the name beside it.""" + item = suggestion() + item["data"]["address"]["data"]["region_kladr_id"] = "7800000000000" + school = m.to_school(item) + assert school.region_code == "78" + assert school.region == "г Санкт-Петербург" + # And the bot's wire shape does not grow a field for it. + from app.schemas import SchoolOut + + assert "region_code" not in SchoolOut(**school.model_dump()).model_dump() + + +@pytest.mark.parametrize("kladr", ["ab00000000000", "7", "²800000000000", "", None, 78]) +def test_a_kladr_id_that_is_not_digits_gives_no_code(kladr): + """No code rather than a guess: the name is still there to place it by.""" + item = suggestion() + item["data"]["address"]["data"]["region_kladr_id"] = kladr + school = m.to_school(item) + assert school.region_code is None + assert school.region == "г Санкт-Петербург" + + +def test_a_branch_is_one_row_for_the_bot_and_two_for_the_regions(): + """Same OGRN, two regions. The picker has always folded them and still + does; the directory keeps one per region, and falls back to the region's + name for a row that carries no code.""" + head = suggestion() + head["data"]["address"]["data"]["region_kladr_id"] = "7800000000000" + branch = suggestion() + branch["data"]["address"]["data"] = {"region_with_type": "Ленинградская обл"} + + assert len(m.to_schools([head, branch])) == 1 + assert len(m.to_schools([head, branch], per_region=True)) == 2 + # A true duplicate in one region is still one row either way. + assert len(m.to_schools([head, dict(head)], per_region=True)) == 1 + + +async def test_a_retry_the_caller_refuses_is_not_sent(monkeypatch): + """The second request costs what the first did, so a caller metering its + share is asked before it is made — and a «no» is an empty answer, not an + error.""" + sent = _answering(monkeypatch, {"suggestions": []}) + asked: list[bool] = [] + + async def nothing_left() -> bool: + asked.append(True) + return False + + found = await dadata_client.suggest_schools("лицей 1535", may_retry=nothing_left) + + assert found == [] + assert len(sent) == 1 + assert asked == [True] + + +async def test_a_retry_the_caller_allows_is_sent_as_before(monkeypatch): + sent = _answering(monkeypatch, {"suggestions": []}, {"suggestions": [suggestion()]}) + asked: list[bool] = [] + + async def plenty() -> bool: + asked.append(True) + return True + + found = await dadata_client.suggest_schools("лицей 1535", may_retry=plenty) + + assert len(found) == 1 + assert len(sent) == 2 + assert asked == [True] + + +async def test_an_answer_with_rows_never_asks_about_a_retry(monkeypatch): + sent = _answering(monkeypatch, {"suggestions": [suggestion()]}) + + async def never() -> bool: + raise AssertionError("asked about a retry that was not needed") + + assert len(await dadata_client.suggest_schools("лицей 1535", may_retry=never)) == 1 + assert len(sent) == 1 From 0a9a188a8b95a235dfe8bfff67cd397af3482ccc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 15:15:11 +0000 Subject: [PATCH 13/30] Stop telling families the bot's sign-in page sends the password straight to the diary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three texts people read just before typing a password said it went «прямо в дневник» and that the bot never saw it (#150). The page posts it to this server, which passes it to the diary for the sign-in and writes it down nowhere. The page's note, the signed-out card and the card with the sign-in link now say exactly that, still in one breath with «не в чате» and «нигде не сохраняется», which remain true. A test fails on any of the old wording, and the existing password test now also checks the logs, which that wording relies on. The texts say nothing about the app's own sign-in, which sends the password straight to the diary: an older app still posts it here, and the page cannot tell which one the reader has. The page's fallback for an answer it cannot read also named dnevnik2 whatever the class was bound to, so a «Сетевой город» family was sent to Петербург's diary to see whether theirs was down (#158). It now names the bound diary's own host, from the allow-list. `providers/diary/__init__.py`'s docstring describes the package as it now is, including both ways a session arrives. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/api/diary_web.py | 45 ++++++++++++++++--- server/app/bot/diary_render.py | 13 ++++-- server/app/bot/handlers/diary.py | 8 +++- server/app/providers/diary/__init__.py | 27 ++++++++--- server/tests/test_bot_diary.py | 5 +++ server/tests/test_diary_web.py | 62 ++++++++++++++++++++++++-- 6 files changed, 139 insertions(+), 21 deletions(-) diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index 76566236..9fa27aa4 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -42,7 +42,7 @@ import logging from html import escape from typing import NamedTuple -from urllib.parse import parse_qs +from urllib.parse import parse_qs, urlsplit from dishka.integrations.fastapi import FromDishka from fastapi import APIRouter, Request @@ -190,6 +190,17 @@ def _form(code: str, binding: Binding | None = None) -> HTMLResponse: # the `401` behind it were here from the first draft and nothing ever passed # one — an unused branch in a renderer is how a page ends up written for an # answer it will never be handed. + # + # The note under the button said the password went «прямо в дневник», and + # it never did: this form posts to our own path (`form-action 'self'`), and + # `sign_in_submit` hands the password to the provider (#150). So it says + # what is true of this page — typed here rather than in the chat, relayed + # by this server for the sign-in, kept nowhere — and nothing about the + # app, whose own sign-in skips this server but only from a build that has + # it; an older one still posts the password to `/api/v1/diary/login`, and + # this page cannot tell which one the reader holds. «Для входа» rather + # than «один раз»: «Сетевой город» may ask for a role and take a second + # login POST inside the same sign-in. return _page( "Вход в дневник", f"

Электронный дневник

" @@ -203,9 +214,11 @@ def _form(code: str, binding: Binding | None = None) -> HTMLResponse: "autocomplete=current-password required>" "" "" - "

Пароль уходит прямо в дневник и нигде не сохраняется — " - "ни у бота, ни в этой базе. Хранится только сессия дневника, " - "зашифрованной, и её всегда можно отозвать кнопкой «Выйти».

", + "

Пароль вводится здесь, а не в чате. Эта страница — на " + "сервере бота: он передаёт пароль дневнику для входа, и пароль нигде " + "не сохраняется — ни у бота, ни в этой базе. Хранится только сессия " + "дневника, в зашифрованном виде, и её всегда можно отозвать кнопкой " + "«Выйти».

", ) @@ -337,7 +350,7 @@ async def sign_in_submit( ) except DiaryError as error: # A wrong password costs the ticket; the diary being down does not. - verdict = _why(error) + verdict = _why(error, binding) if verdict.keep_ticket: await _unspend(session, ticket_id) return _closed( @@ -375,7 +388,25 @@ class _Verdict(NamedTuple): keep_ticket: bool -def _why(error: DiaryError) -> _Verdict: +def _site_of(binding: Binding) -> str: + """The address a family can open in a browser to see whether *their* + diary is up: the regional server for «Сетевой город», dnevnik2 otherwise. + + Taken from the allow-list, never from anything typed, so it is safe to + show. It used to be dnevnik2 whatever the class was bound to, which sent a + «Сетевой город» family to Петербург's diary to find out why theirs had + answered nonsense (#158). + """ + if binding.region: + from app.providers.netschool import regions + + region = regions.get(binding.region) + if region is not None: + return urlsplit(region.origin).netloc + return binding.provider.site or "dnevnik2.petersburgedu.ru" + + +def _why(error: DiaryError, binding: Binding) -> _Verdict: """The upstream's failure, said in a way the reader can act on. Only :class:`BadCredentials` is «неверный пароль». Everything else said so @@ -422,7 +453,7 @@ def _why(error: DiaryError) -> _Verdict: return _Verdict( "Дневник ответил непонятно — обычно это технические работы или проверка " "«я не робот». Пароль, скорее всего, ни при чём: откройте " - "dnevnik2.petersburgedu.ru в браузере, а потом попросите у бота новую ссылку.", + f"{_site_of(binding)} в браузере, а потом попросите у бота новую ссылку.", 502, keep_ticket=False, ) diff --git a/server/app/bot/diary_render.py b/server/app/bot/diary_render.py index 2af2efd1..720c5eac 100644 --- a/server/app/bot/diary_render.py +++ b/server/app/bot/diary_render.py @@ -164,11 +164,18 @@ def render_signed_out(genitive: str) -> str: case — «Санкт-Петербурга», «„Сетевого города“» — because there is more than one now, and a card that always said Petersburg would be wrong for the other. It is a fixed provider string, never anything a user typed, so it - goes in unescaped like the rest of this template.""" + goes in unescaped like the rest of this template. + + The last sentence used to say the password went from that page «прямо в + дневник». It goes to this server, which passes it on for the sign-in + (#150); the promise that survives is the one the page exists for — not in + the chat, and kept nowhere. `api/diary_web._form` says why neither text + speaks for the app.""" return ( "📒 Электронный дневник\n\n" f"Класс привязан к дневнику {genitive}. Вход — ваш личный: " "вы видите своего ребёнка, и никто из класса не видит его за вас.\n\n" - "Пароль не вводится в чат. Бот даст ссылку на страницу входа — " - "оттуда пароль уходит прямо в дневник и нигде не сохраняется." + "Пароль не вводится в чат. Бот даст ссылку на страницу входа " + "на своём сервере: сервер передаёт пароль дневнику для входа, " + "и пароль нигде не сохраняется." ) diff --git a/server/app/bot/handlers/diary.py b/server/app/bot/handlers/diary.py index 8796b5ce..48125df1 100644 --- a/server/app/bot/handlers/diary.py +++ b/server/app/bot/handlers/diary.py @@ -200,11 +200,15 @@ async def diary_sign_in( code = await diary_link.mint( session, telegram_id=callback.from_user.id, class_id=school_class.id ) + # The page posts the password to this server, which passes it to the diary + # for the sign-in and writes it down nowhere. This card used to say it went + # «прямо в дневник» and that the bot never saw it — false twice (#150), and + # the one sentence a parent reads before typing a password. await callback.message.edit_text( "🔐 Вход в дневник\n\n" f"Ссылка действует {diary_link.TICKET_MINUTES} минут и только один раз.\n\n" - "Пароль вводится на странице и уходит прямо в дневник — " - "ни бот, ни эта база его не видят и не сохраняют.\n\n" + "Пароль вводится на странице, а не в чате. Сервер бота передаёт его " + "дневнику для входа и нигде не сохраняет — ни у бота, ни в этой базе.\n\n" "Не пересылайте ссылку никому: она открывает вход в ваш аккаунт.", reply_markup=sign_in_keyboard(f"{base}/diary/signin/{code}"), disable_web_page_preview=True, diff --git a/server/app/providers/diary/__init__.py b/server/app/providers/diary/__init__.py index 70f1bd1d..0feb834f 100644 --- a/server/app/providers/diary/__init__.py +++ b/server/app/providers/diary/__init__.py @@ -7,16 +7,31 @@ - :mod:`app.providers.diary.models` — the models every provider returns; - :mod:`app.providers.diary.errors` — the failures every provider raises, each - one a different answer at the API edge; + one a different answer at the API edge, down to the address the upstream + will not talk to (:class:`AddressRefused`) and the sign-in a region does not + offer (:class:`SignInUnsupported`); - :mod:`app.providers.diary.base` — the :class:`DiaryProvider` and - :class:`DiaryConnection` protocols, and the :class:`SignInRequest` they take; + :class:`DiaryConnection` protocols, and the two ways a session reaches a + provider: :class:`SignInRequest`, a password that passes through this server + on its way upstream (the bot's sign-in page, and the + ``POST /api/v1/diary/login`` older apps still call), and + :class:`AdoptRequest`, a session the phone opened with the diary itself, + which the provider checks with a read of its own and answers with + :class:`Adopted`; - :mod:`app.providers.diary.http` — the shared HTTP client, whose cookie jar - keeps nothing so two families' sessions can never meet; + keeps nothing so two families' sessions can never meet, which follows no + redirect, and the one definition of a cookie or header value that is safe to + write (:func:`cookie_value_ok`, :func:`header_value_ok`); - :mod:`app.providers.diary.registry` — the map from a stored provider key to an implementation, and :func:`binding`, the one place that reads a class's diary binding. -Petersburg pre-dates this package and keeps every public name it had, as a -re-export of the very objects defined here — so no import anywhere breaks and -`isinstance` still holds across the two spellings. +Nothing is re-exported from here: each name is imported from the module above +that defines it, so importing this package costs no HTTP client. + +Petersburg pre-dates this package. Its old modules, +`app.providers.petersburg.models` and `.exceptions`, re-export the very +objects defined here, so the imports that used them still work and +`isinstance` holds across the two spellings. The one name nothing read, +``DiaryAccount``, is gone (#138). """ diff --git a/server/tests/test_bot_diary.py b/server/tests/test_bot_diary.py index 8ff1505e..e1ed8eb2 100644 --- a/server/tests/test_bot_diary.py +++ b/server/tests/test_bot_diary.py @@ -214,6 +214,11 @@ async def test_the_sign_in_link_is_one_ticket_pointed_at_the_form( # decide whether to forward it. assert "один раз" in callback.message.last assert "Не пересылайте" in callback.message.last + # #150: the page posts the password to this server, so the card must not + # say it goes «прямо в дневник» or that the bot never sees it. + assert "прямо в дневник" not in callback.message.last + assert "не видят" not in callback.message.last + assert "нигде не сохраняет" in callback.message.last async def test_signing_out_drops_the_session_and_returns_the_door( diff --git a/server/tests/test_diary_web.py b/server/tests/test_diary_web.py index 54b53322..33dd4d47 100644 --- a/server/tests/test_diary_web.py +++ b/server/tests/test_diary_web.py @@ -9,6 +9,7 @@ from __future__ import annotations import json +import logging import httpx import pytest @@ -16,6 +17,7 @@ from sqlalchemy import select from app.api import diary_web as from_app +from app.bot import diary_render from app.config import get_settings from app.main import app from app.models import DiaryLinkCode, DiarySession, SchoolClass @@ -134,10 +136,13 @@ async def test_signing_in_opens_a_session_bound_to_the_telegram_account( async def test_the_password_reaches_the_upstream_and_nothing_else( - web, upstream, ticket, session, LOGIN_PATH + web, upstream, ticket, session, LOGIN_PATH, caplog ): - """The whole argument for the page. It goes to dnevnik2 and is written - down nowhere — not in our row, not in a log, not in a chat.""" + """The whole argument for the page. It passes through this server to + dnevnik2 and is written down nowhere — not in our row, not in a log, not + in a chat. The log half was only this docstring's word until the page + started saying «нигде не сохраняется» on the strength of it (#150).""" + caplog.set_level(logging.DEBUG) def accepts_anything(request: httpx.Request) -> httpx.Response: response = httpx.Response(200, json={"data": {"token": "body-token"}}) @@ -159,6 +164,25 @@ def accepts_anything(request: httpx.Request) -> httpx.Response: ensure_ascii=False, ) assert "hunter2-secret" not in stored + assert "hunter2-secret" not in caplog.text + + +async def test_neither_text_says_the_password_skips_this_server(web, ticket): + """#150. The page said the password went «прямо в дневник», and so did the + bot's card that leads to it; the form posts to our own path, and the + handler hands the password on. Both now say it goes through this server, + and keep the two promises that are true: not in the chat, kept nowhere.""" + page = (await web.get(f"/diary/signin/{ticket}")).text + card = diary_render.render_signed_out("Санкт-Петербурга") + + # The fact the wording has to agree with: the browser posts here. + assert f'action="/diary/signin/{ticket}"' in page + for text in (page, card): + assert "прямо в дневник" not in text + assert "передаёт пароль дневнику для входа" in text + assert "нигде не сохраняется" in text + assert "а не в чате" in page + assert "Пароль не вводится в чат." in card async def test_a_ticket_is_worth_one_attempt_even_a_failed_one( @@ -290,6 +314,38 @@ async def test_a_diary_in_maintenance_is_not_reported_as_a_wrong_password( assert response.status_code == 502 +async def test_an_unreadable_netschool_answer_names_the_regions_own_server( + web, session, school_class, monkeypatch +): + """#158: the fallback sent a «Сетевой город» family to Петербург's diary. + + Opening the diary in a browser is the one check that tells a person + whether their diary is down — so it has to be *their* diary's address, + the regional server the class is bound to, not dnevnik2. + """ + from app.providers.diary.errors import UnexpectedResponse + + school_class.diary_provider = "netschool" + school_class.diary_region = "samara" + school_class.diary_school_id = 1234 + school_class.diary_school_name = "Школа № 1" + await session.commit() + code = await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + + async def unreadable(*args, **kwargs): + raise UnexpectedResponse + + monkeypatch.setattr(from_app.diary_service, "sign_in", unreadable) + + response = await web.post( + f"/diary/signin/{code}", data={"login": "parent", "password": "correct"} + ) + + assert response.status_code == 502 + assert "asurso.ru" in response.text + assert "dnevnik2.petersburgedu.ru" not in response.text + + async def test_an_unreadable_answer_still_costs_the_ticket( web, upstream, ticket, session, LOGIN_PATH, with_token ): From 6281dea192ec6a9ff326a4545b70530b02fb92fe Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 16:14:47 +0000 Subject: [PATCH 14/30] Document how a diary session now reaches the server, the region catalog and the anonymous school directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server half of #141 is in, and the documents that own each part now say what it does: - docs/api.md: `POST /api/v1/diary/session` and `GET /api/v1/diary/capabilities`, with both body shapes, every status and why "the diary refused this session from our address" is a 409 rather than a 401; `X-Diary-Unavailable` on every diary 503, `/diary/login`'s included; `JoinResponse.diary`; and `GET /api/v1/directory/school-regions` with its throttle, its share of DaData's day and `X-Directory-Unavailable`. The paragraph saying the app never talks to either diary is replaced: there are now two ways in and one API after. `/diary/login` stays, and says plainly that it receives the password. - docs/diaries.md: no Госуслуги sign-in and no WebView, and why (a Госуслуги session is the whole state-services account); the region catalog as generated data, its inputs, and the reason codes. docs/diaries/regions.md says which of its lines the generator parses. - docs/architecture.md, docs/bot.md, docs/deploy.md, docs/README.md: the phone-registered session, the catalog, the quota table and why it counts per Moscow day; the bot's new sign-in wording (#150), the regional host in the unreadable-answer text (#158), rebinding expiring sessions (#145); DaData counted at two requests on an empty answer (#150); 0015 and 0016 still to be applied before #140 merges. - README, CLAUDE.md, the migration skill: head 0016, 1915 server tests, 100 mypy modules, the honest status of registration and the directory. CLAUDE.md also names `/diary/session` as a source of the diary token and no longer calls the sealed credential Petersburg's alone. Left for the Android half's documents, because each is true of today's app and becomes false when native sign-in lands: docs/build.md's «Why HTTP and not HTTPS» (the wire carries a password today on /diary/login, and will not from the new app), docs/design.md's «the app does not talk to dnevnik2», and docs/guide.md's diary section. The Android test count is untouched. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/skills/migration/SKILL.md | 2 +- CLAUDE.md | 22 +- README.md | 35 +++- docs/README.md | 14 +- docs/api.md | 321 ++++++++++++++++++++++++++---- docs/architecture.md | 117 +++++++++-- docs/bot.md | 38 +++- docs/deploy.md | 61 ++++-- docs/diaries.md | 94 ++++++++- docs/diaries/regions.md | 7 + 10 files changed, 612 insertions(+), 99 deletions(-) diff --git a/.claude/skills/migration/SKILL.md b/.claude/skills/migration/SKILL.md index b34cf9dd..ed9fc112 100644 --- a/.claude/skills/migration/SKILL.md +++ b/.claude/skills/migration/SKILL.md @@ -5,7 +5,7 @@ description: Write and apply an Alembic revision for this project — including # A migration, start to finish -Head is **`0015`**. Nothing after `0001` may use `create_all`. +Head is **`0016`**. Nothing after `0001` may use `create_all`. ## 1. Decide the direction diff --git a/CLAUDE.md b/CLAUDE.md index 791d317c..1f3a33eb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,7 +45,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 1668 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 1915 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at @@ -53,7 +53,7 @@ Server, from `server/`: there. That shipped once. `tests/test_test_imports.py` now refuses a test module that imports another one at all — a shared fixture belongs in `conftest.py`, which pytest loads by path rather than by import -- **`python -m mypy`** — one question, of all 97 modules, in seconds: does anything reach +- **`python -m mypy`** — one question, of all 100 modules, in seconds: does anything reach for an attribute its type does not have? Configured in `pyproject.toml`, where every other error code is switched off by name with its count and its reason. Not in CI — the owner has not been asked — but run it before you push server code @@ -305,12 +305,14 @@ points Hilt does not inject cleanly. real code. - **There are two independent bearer tokens.** The device token from `POST /api/v1/join` (`api/deps.py:current_device`) and the diary session token from - `POST /api/v1/diary/login` (`api/diary.py:current_diary`). A phone can be joined to a class + `POST /api/v1/diary/session` — a session the phone opened with the diary itself — or the + older `POST /api/v1/diary/login` (`api/diary.py:current_diary`). A phone can be joined to a class without a diary account and signed in to a diary without a class; neither implies the other, and one token meaning both would have to be re-minted whenever either half changed. They go in the same `Authorization: Bearer` header on different endpoint families — check which one an endpoint depends on before moving it. -- **The diary needs `DIARY_SECRET` or it does not run.** The Petersburg session token is +- **The diary needs `DIARY_SECRET` or it does not run.** The upstream session — Petersburg's + token or «Сетевой город»'s bearer and cookies, however it arrived — is the one stored credential that cannot be a hash (it is replayed upstream on every call), so it is sealed with Fernet — `app/crypto.py`. No key means the feature refuses at the door rather than falling back to plaintext, because a silent fallback is invisible and @@ -339,7 +341,7 @@ points Hilt does not inject cleanly. a half-applied revision cannot claim to be whole. And say what a revision destroys before running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a sentence the owner needs *before* the transaction, not after. -- **Migrations are Alembic and the head is `0015`, which goes on before this batch's merge.** `0001` is a guarded +- **Migrations are Alembic and the head is `0016`, which goes on with `0015` before this batch's merge.** `0001` is a guarded `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds @@ -371,7 +373,15 @@ points Hilt does not inject cleanly. rewrite no row; a NULL `provider` on an existing session means Petersburg, the only diary before the column. Its downgrade expires every non-Petersburg session before dropping the columns that tell one apart, so reverted code - cannot replay a credential at the wrong upstream. + cannot replay a credential at the wrong upstream. `0016` creates + `usage_counters`: one row per counter per Moscow day, which is how the + anonymous school directory's share of DaData's daily allowance is spent + without touching the share the bot's create-class search needs — a table of + its own, because `join_attempts` is pruned to fifteen minutes on every + recorded attempt and would cut a day's count to a quarter of an hour. It + creates a table and nothing else — additive, the ordinary shape, rewrites + and destroys no row — and goes on **before** the merge, together with + `0015`; its downgrade drops the table and with it nothing but the counts. Nothing after `0001` may use `create_all`. Beware the enum: `SAEnum(SomeStrEnum)` stores the member **name**, so a `server_default` written as `.value` is a string the ORM cannot read back — which on `classes` is a diff --git a/README.md b/README.md index bd3223c4..718891ff 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ The checks CI runs: ```bash ruff check app tests scripts migrations -python -m pytest -q +pytest -q -n auto ``` The schema is Alembic: `alembic upgrade head` with a working `DATABASE_URL`, from a @@ -197,8 +197,8 @@ Read this before planning a release. | Check | Result | | --- | --- | | `ruff check app tests scripts migrations` | clean | -| `python -m mypy` | clean, 97 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 1668 tests, green, about four minutes — the command CI runs | +| `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | +| `pytest -q -n auto` | 1915 tests, green, about four minutes — the command CI runs | | `./gradlew test` | 968 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | @@ -241,6 +241,17 @@ service, but it says nothing about what that service actually answers. No browse opened the sign-in page for either, and the first live session, for both, is the owner's (#121, #135). +Nor has a session ever been **registered**. `POST /api/v1/diary/session` is the door through +which a client that signed in with the diary itself hands over the session, so that the +password never reaches this server; it is exercised against the known-answer vectors both +sign-in protocols share and against hand-written answers, never against a live diary. The +question it rests on is open: whether either diary accepts a session opened on a phone in +Russia when this deployment, in Frankfurt, replays it. If not, the answer is a `409` by +design, and the password routes — the bot's page and the older `/diary/login`, both of which +still pass the password through this server — are what is left. The four calls «Сетевой +город» registration makes have not been timed against Vercel's 30-second ceiling, and a +session registered from a phone is invisible to the bot (#143). + **Week parity was computed from the ISO week number, and that broke once every five or six years.** In an ISO year with 53 weeks, week 53 and week 1 stand next to each other and are both odd: Monday 28 December 2026 and Monday 4 January 2027 both came out as numerator, @@ -324,6 +335,15 @@ a stub in place of the registry. Something else was verified: with no key, the s answers `503` with the words «введите название вручную», and a class is created as before. What the registry actually answers to «гимназия 3 Казань», nobody has checked. +The same holds for the anonymous directory the first run asks, +`GET /api/v1/directory/school-regions`. It places a school by the subject code at the front +of DaData's `region_kladr_id`, and whether DaData's rows for organisations carry that field at +all is unknown — the fallback by the region's name exists for that case, and every one of the +catalog's DaData spellings it would fall back on is unverified too, as are the codes of the +four regions admitted in 2022. The daily cap assumes DaData's day turns at Moscow midnight, +which nothing documents, and that two requests cannot both spend its last unit has been +checked on SQLite only. + **A flag that meant nothing.** The class card in the bot had a «🔓 Открыть класс / 🔒 Закрыть класс» button and a «Тип класса: публичный / закрытый» line. **Not one** code path read the flag behind them: an administrator who "closed" a class closed nothing, and the @@ -401,10 +421,11 @@ one of them is proved by a test rather than by a screen. Robolectric, against a fake. Which of the four a phone shows when pointed at production, nobody has watched. * **`/api/v1/warmup` itself has not been read since #61**, when it answered - `{"status":"ok","api_version":1,"schema":"0013"}`. Production is at `0015` now, so it - should say so, and that one request is the cheapest check of whether the migration and - the code that needs it actually met — but the deployment previews sit behind Vercel's - protection, and nobody has made the check against production either. + `{"status":"ok","api_version":1,"schema":"0013"}`. Production was last recorded at `0014`; + the code on this branch expects `0016`, and `0015` and `0016` are to be applied before #140 + merges, after which it should say `0016`. That one request is the cheapest check of whether + the migrations and the code that needs them actually met — but the deployment previews sit + behind Vercel's protection, and nobody has made the check against production either. * **`docker compose up` has not been run.** There is no Docker in this environment: the compose file was parsed and its dependency conditions asserted. The `migrate` service and the revisions now in the image are written and never watched coming up. diff --git a/docs/README.md b/docs/README.md index c5a8e82f..b98cde64 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,10 +26,10 @@ answer is not here it is in the code, and there is usually a link to it. | [widget.md](widget.md) | twelve sizes, seven states, the update schedule, why not a tick once a minute | | [build.md](build.md) | standing the project up from a clone and how much of `server/.env` each step needs, the eight secrets Actions holds and what reads them, building the APK in Actions and locally, signing with your own key, a release from a tag, Actions minutes and where they go, the bundled typeface, pointing the app at a server | | [deploy.md](deploy.md) | Vercel plus Neon or your own server, the webhook, migrations, why the server has no clock of its own | -| [api.md](api.md) | the whole `/api/v1` contract: reads, writes, class management, the electronic diary — Петербург and «Сетевой город» behind one contract | +| [api.md](api.md) | the whole `/api/v1` contract: reads, writes, class management, the electronic diary — Петербург and «Сетевой город» behind one contract, signed into by this server or registered from a session the client opened itself — and the anonymous school directory | | [architecture.md](architecture.md) | why the bot is the backend, the timetable resolution model, the five Android modules, the service layer, the tests | | [design.md](design.md) | the design system: what was taken from Essentials, what was fixed, and the reasoning behind every visible decision in the interface | -| [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from | +| [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from — except for one section, the region catalog the server and the app read, which is generated from this survey | | [diaries/](diaries/) | **the reference pages of [diaries.md](diaries.md)**: one page per platform with its hosts, sign-in flows, headers and the full route table read out of the open-source clients, and one page with the evidence for every region. Nothing in them has been tried against a live diary | | [app/](app/) | **not a document — the guide the app draws.** `guide.ru.md` is the source, `guide.en.md` the translation, `manifest.json` says which version they are and which app version they describe. The app fetches these files from this repository and falls back to the copy built into the APK | @@ -57,8 +57,14 @@ the user will actually see, it quotes it in Russian, because that is what is on for signing and for the fallback tick. `CRON_SECRET` is the one name in two of the three, and nothing checks that the two values match. - **The two different tokens** — [api.md](api.md): the device token comes from - `POST /api/v1/join`, the diary token from `POST /api/v1/diary/login`, and neither implies - the other. + `POST /api/v1/join`, the diary token from `POST /api/v1/diary/session` (a session the + client opened itself) or `POST /api/v1/diary/login` (a password), and neither implies the + other. +- **Where a diary password goes** — [api.md](api.md#the-electronic-diary) and + [architecture.md](architecture.md): registration keeps it off this server; `/diary/login` + and the bot's sign-in page pass it through to the diary once and store it nowhere. +- **Why there is no Госуслуги sign-in** — [diaries.md](diaries.md#what-it-means-for-this-project): + a Госуслуги session is the person's whole state-services account. - **Who lets a phone into a class** — [api.md](api.md), "Who lets a phone in: the class code or the bot", and [bot.md](bot.md), "Who lets a phone in": a class has two join modes, and in one of them the class code opens nothing. diff --git a/docs/api.md b/docs/api.md index 089c47b8..f277fe97 100644 --- a/docs/api.md +++ b/docs/api.md @@ -27,10 +27,23 @@ Content-Type: application/json "class_id": 1, "class_name": "9А", "school": "Демо-школа", - "timezone": "Europe/Moscow" + "timezone": "Europe/Moscow", + "diary": { "provider": "netschool", "region": "samara", "school_id": 1234, + "school_name": "МБОУ Школа № 5" } } ``` +`diary` is the electronic diary the class is bound to in the bot, so that a phone joining a +bound class can sign in there without searching for its school: `provider` is `petersburg` +or `netschool`, and for «Сетевой город» `region` is the allow-list's key and `school_id` the +diary's own school id. It is `null` when the class has no binding **this server can use** — +none at all, a region since dropped from the allow-list, a region that takes only +Госуслуги, or a «Сетевой город» binding whose school step was never finished — because it +is read through the same `registry.binding()` the bot reads, and a phone must never be +pointed at a diary this server would refuse. The field is additive: an older app ignores +it. It says which diary, and nothing more; the phone still needs a diary session of its own +([The electronic diary](#the-electronic-diary)). + The token is stored server-side only as a SHA-256 hash, so a database leak does not yield working credentials. Every later request carries it: @@ -934,12 +947,16 @@ runs between requests: | What | When it is deleted | Why | | --- | --- | --- | | Abandoned bot dialogues (`fsm_states`) | after two days | `fsm_purged`; the «current class» preference sits in the same table and is exempt, because it is written once and only read afterwards | -| Failed-join counters (`join_attempts`) | after an hour | `join_attempts_purged` | +| Throttle counters (`join_attempts`): failed joins, failed diary sign-ins, and every directory search | after an hour | `join_attempts_purged` | | Diary sessions (`diary_sessions`) | a day after the service refuses one, 30 days after it was last used | a live token for somebody else's service is inside | | Device tokens (`device_tokens`) | after 180 days of silence | every `POST /join` creates a row, and reinstalling the app leaves the old one for ever | | Diary sign-in tickets (`diary_link_codes`) | on expiry | `diary_links_purged` | | Personal connect codes (`device_invites`) | a day after they expire | `device_invites_purged`; a day rather than immediately, because "my code does not work" is asked within minutes, while who connected a phone is remembered by the device token itself | +One table is deliberately not swept: `usage_counters`, the directory's daily allowance, holds +one row per allowance per day — 365 rows of three columns a year — and yesterday's row is +what says how close yesterday came to the cap. + 180 days is comfortably longer than the summer holidays: a phone silent since the end of May has to work in September. A device in use is marked no less than once every 15 minutes, on any read. @@ -956,6 +973,15 @@ clock. Petersburg sessions are not pinged; they refresh from their own answers. on the external cron, not GitHub's fallback clock, which is too sparse to keep a session alive; [deploy.md](deploy.md#the-clock-the-server-has-none-and-githubs-will-not-do) says why. +Two guards keep the pings honest. A regional server that drops this deployment's address +answers every session on it the same way, so after its first such refusal the tick skips +that region's sessions not yet started — at most the pings already in flight are wasted — +and they wait for the next tick. And a ping's result is written back only to a row that +still holds the sealed credential the ping was sent with: a real read that rotated the +cookies while the ping was in the air is never overwritten with the older ones, and a ping +that failed on the old credential does not expire a row whose new one is fine. The two +counters count rows actually written, not pings sent. + ## `GET /api/v1/health` and `GET /api/v1/warmup` Both unauthenticated. `/health` returns `{"status": "ok", "api_version": 1}` and @@ -969,7 +995,7 @@ whether the schema is the one this code was written against. Three answers: | | Body | Meaning | | --- | --- | --- | -| `200` | `{"status": "ok", "api_version": 1, "schema": "0015"}` | the database is reachable and at the revision the code expects | +| `200` | `{"status": "ok", "api_version": 1, "schema": "0016"}` | the database is reachable and at the revision the code expects | | `200` | `{"status": "degraded", …, "schema": …, "expected_schema": …, "detail": …}` | both revisions named, and `detail` says **which way** they diverge | | `503` | `{"status": "down", "api_version": 1, "detail": "База недоступна."}` | the database could not be reached | @@ -1000,16 +1026,138 @@ There are two such services behind this one surface — «Петербургск (`dnevnik2.petersburgedu.ru`) and «Сетевой город. Образование», the diary of about twenty regions — and **the API does not change between them.** Which one a session is with is decided at sign-in and stored on the session; every endpoint below is provider-neutral, and -the client reads the same shapes whichever diary answered. «Сетевой город» is server-side -only and has never been tried against a live server (see the README's honest status). +the client reads the same shapes whichever diary answered. Neither has ever been opened +against a live server from here (see the README's honest status). + +**Two ways in, one API after.** A diary session of ours is opened one of two ways. A client +that signs in with the diary itself — straight at the diary's own address, so that the +password goes to the diary and nowhere else — hands the session the diary gave it to +`POST /api/v1/diary/session`; this server reads with it once from its own address, seals it +and answers with a token of ours, and the client forgets its copy. A client that does not +sends the login and the password to `POST /api/v1/diary/login`, and this server signs in on +its behalf. From then on the two are indistinguishable: every read below goes through this +server with our token, and none of an upstream's parameters — Petersburg's `p_educations[]` +and `estimate_type_code`, «Сетевой город»'s `scid` and its weekly-diary shape — crosses the +boundary of our API. If a field is renamed up there tomorrow, one directory is what gets +fixed (`app/providers/petersburg/` or `app/providers/netschool/`), and neither the app nor +this document changes. + +The one exception is the registration body, which **is** the upstream's session and so +carries the upstream's names: Petersburg's `X-JWT-Token`, «Сетевой город»'s `at` bearer and +its two session cookies. That is the price of the password never reaching this server: the +diary's sign-in protocol then lives in the client as well as here, and the known-answer +vectors in `server/tests/vectors/diary_protocol.json` pin both sign-ins so that the two +implementations are tested against one set of bytes. + +### Before a password is typed: `GET /api/v1/diary/capabilities` + +```json +{ + "enabled": true, + "registration": true, + "providers": { + "petersburg": {}, + "netschool": { "regions": ["amur", "zabaikalsky", "kamchatka", "…"] } + } +} +``` -**The app never talks to either service directly.** None of an upstream's parameters — -Petersburg's `p_educations[]`, `X-JWT-Token`, `estimate_type_code`, or «Сетевой город»'s `at` -bearer and `scid` — crosses the boundary of our API. If a field is renamed up there tomorrow, -one directory is what gets fixed (`app/providers/petersburg/` or `app/providers/netschool/`), -and neither the app nor this document changes. +Anonymous, and it opens no database connection, so it is cheap to ask on every sign-in +screen. `enabled` is `false` when the deployment has no `DIARY_SECRET` — nothing a person +types will help, and a client should say so before asking for a password. `registration` +says this server takes a session a client opened itself; a server from before that answers +`404` here, which answers the question too. `netschool.regions` are the allow-list's keys +this server signs in to with a password: sixteen of the nineteen, because `altai-krai`, +`primorye` and `tula` take only Госуслуги and are never listed. A region missing from the +list is one a client should not send a password to, since the session it opened could not +be kept here. + +### Registering a session the client opened: `POST /api/v1/diary/session` + +``` +POST /api/v1/diary/session +{ "provider": "petersburg", "login": "parent@example.com", + "credential": { "token": "eyJhbGciOi…" } } +``` + +``` +POST /api/v1/diary/session +{ "provider": "netschool", "login": "ivanova.m", "region": "samara", "school_id": 1234, + "credential": { "at": "…", "cookies": { "NSSESSIONID": "…", "ESRNSec": "…" }, + "ver": "…", "time_out": 45 } } +``` + +```json +{ + "token": "…", + "login": "ivanova.m", + "provider": "netschool", + "region": "samara", + "school_id": 1234, + "school_name": "МБОУ Школа № 5", + "zone": "Europe/Samara", + "students": [ + { "id": 7, "first_name": "Маша", "last_name": "Иванова", "middle_name": null, + "full_name": "Иванова Маша", "school": null, "class_name": "5Б" } + ] +} +``` -### Signing in +The body is one of two shapes, chosen by `provider`, and every level of it refuses a key it +does not know: **a `password` key anywhere is a `422`**, so no client can send one here, by +mistake or otherwise. `login` is what the person typed into the client's own form. Nothing +upstream vouches for it; it names the session and keys the family's corrections (see +[Corrections over the diary](#corrections-over-the-diary)), so a client sends the same +string every time. For «Сетевой город», `region` must be an allow-listed key that takes a +password and `school_id` the diary's own school id — both checked before any upstream call, +so a region this server does not serve never receives a request. In `credential`, +Petersburg's `token` must be a JWT; `NSSESSIONID` is required and `ESRNSec`, `ver` and +`time_out` are sent only if the diary handed them over. Every value is checked as something +that can go back upstream whole — a cookie value holding `;` would smuggle a second cookie +onto every read, and an `at` holding a line break a second header — by the one definition in +`app/providers/diary/http.py`, which the clients writing those headers apply again. + +**The check is one read from here.** The server reads with the session once, from its own +address: Petersburg's list of pupils, or «Сетевой город»'s four bootstrap calls — the +pupils, the current school year, the context that names the school, and the assignment +types — which fill what a sealed session cannot read without. It then seals what it read +with, possibly rotated by those very reads, exactly as a password sign-in's session is +sealed. The answer never carries the upstream credential back. `token` and `login` sit where +`/login`'s answer has them, so a client decodes both the same way; `students` is what the +check already fetched; `zone` is the zone the diary cuts its days in — Petersburg's, or the +region's administrative centre — by the same rule the server's own «today» for this session +uses (`services/diary.zone_for`); `school_name` is what «Сетевой город» calls the school, +and `null` for Petersburg. + +| Status | What happened | Counted by the limiter | +| --- | --- | --- | +| `200` | the session works from here, and it is ours now | — | +| `403` | the diary took the session, and there is no pupil behind the account — a staff account, or a pupil's own account that does not list itself | yes | +| `409` | the diary refused, **from this server's address**, the session it had just handed the client. It is not the password | yes | +| `422` | not one of the two shapes, a value that cannot be sent upstream whole, or a region this server does not sign in to. `detail` names what was wrong and **never repeats the value**: FastAPI's validation answer normally echoes each refused value as `input`, and here that value is a session or a password | no | +| `429` | ten counted failures from this address within fifteen minutes, on `/login` and `/session` together; `Retry-After` says how long | — | +| `502` | the diary answered something nobody can read | yes | +| `503` | the diary is off on this server, refuses this server's address, or is not answering; `X-Diary-Unavailable` says which (see [Error codes](#error-codes)) | no | + +**`409` rather than `/login`'s `401` + `X-Diary-Reauth`.** The session worked on the client +seconds ago. Asking for the password again would open another one that fails the same way +from here, and the client would loop; what failed is where the session came from. A client +should say that it is not the password and **not retry by itself**. Whether either diary +accepts a session opened on a phone in Russia when it is replayed from this project's own +deployment — pinned to Vercel's Frankfurt region (`vercel.json`) — **has never been seen**: +no session has been registered against a live diary, and `409` is the designed answer for +the case where it is not. + +It shares `/login`'s limiter **and its bucket**, so ten wrong passwords on one do not buy +ten more tries on the other. What is counted follows the same line as `/login`'s: whatever +the upstream judged, which includes the `409` a replay of a session that was never real +produces; what is forgiven is what never reached it, or reached a diary that did not answer. + +**A registered session belongs to no class and no Telegram account.** The row carries +neither, so the bot's «📒 Мой дневник» does not see it; a phone and the bot hold separate +sessions, each signed in on its own. Linking the two is deliberately deferred (#143). + +### Signing in with a password: `POST /api/v1/diary/login` ``` POST /api/v1/diary/login @@ -1020,22 +1168,28 @@ POST /api/v1/diary/login { "token": "…", "login": "parent@example.com" } ``` -`provider`, `region` and `school_id` are optional. Absent `provider` means Petersburg, so a -phone that sends only a login and a password signs in there exactly as before. For «Сетевой -город», `provider` is `"netschool"`, `region` is a key into the server's own allow-list and +Unchanged by registration, and kept for the clients built before it. `provider`, `region` +and `school_id` are optional. Absent `provider` means Petersburg, so a client that sends +only a login and a password signs in there exactly as before. For «Сетевой город», +`provider` is `"netschool"`, `region` is a key into the server's own allow-list and `school_id` the upstream's school id; both are validated in the route before any upstream -call, so an unknown region or a missing school is a `422`, and a region that takes only -Госуслуги — or one whose server refuses this deployment's address — answers `503`, which the -sign-in limiter does not count because nothing there looked at the password. The bot already -binds a class to a region and a school for its own web sign-in form; these fields are for a -phone that will one day sign in to «Сетевой город» directly. - -**The password is not stored.** It is needed for exactly one request — the login to -somebody else's service — after which it is forgotten. Only the diary's own session is -stored, and it is refreshed on the fly: the service hands back a fresh token on almost every -answer and we overwrite ours with it, so a session in use does not die of age. When it does -finally stop being accepted, any request answers `401` with an `X-Diary-Reauth: required` -header — which is a request to ask for the password again, not "the token is wrong". +call, so an unknown region, a region the allow-list knows to take only Госуслуги, or a +missing school is a `422`. A region whose server answers at sign-in that it takes only +Госуслуги, or refuses this deployment's address, answers `503` with `X-Diary-Unavailable`, +and the sign-in limiter does not count it, because nothing there looked at the password. + +This route **receives the password**, and so does the bot's sign-in page (`/diary/signin`, +described in [bot.md](bot.md)), which is a separate route over the same sign-in: each passes +the password to the diary for the sign-in and writes it down nowhere. Only registration +keeps it off this server altogether. + +**The password is not stored**, on either route. It is needed for the sign-in to somebody +else's service — «Сетевой город» may ask for a role and take a second login request inside +the same sign-in — after which it is forgotten. Only the diary's own session is stored, and +it is refreshed on the fly: the service hands back a fresh token on almost every answer and +we overwrite ours with it, so a session in use does not die of age. When it does finally +stop being accepted, any request answers `401` with an `X-Diary-Reauth: required` header — +which is a request to sign in again, not "the token is wrong". The price of that decision is honest: a background sync of the diary lives no longer than the session. The alternative — keeping every family's password in the database to save one @@ -1046,11 +1200,12 @@ a class without a diary and to a diary without a class; one token meaning both w be re-minted whenever either half changed. Failed sign-ins are rate-limited per client address, ten per fifteen minutes, in a bucket of -their own: ten wrong diary passwords must not spend a phone's thirty `/join` attempts. Past -that the endpoint answers `429` with `Retry-After`, and it is counted in the database, like -the join limiter, because nothing in this deployment survives between requests. What the -limit is for is that this server's address must not become a way of guessing passwords -against somebody else's school diary. +their own shared by `/login` and `/session`: ten wrong diary passwords must not spend a +phone's thirty `/join` attempts, nor buy ten more tries by session. Past that both answer +`429` with `Retry-After`, and it is counted in the database, like the join limiter, because +nothing in this deployment survives between requests. What the limit is for is that this +server's address must not become a way of guessing passwords against somebody else's school +diary. ### What can be asked @@ -1159,12 +1314,21 @@ where they are visible as corrections and are reversible. | Code | What happened | What the app should do | | --- | --- | --- | | `401` | our session's token did not fit | ask them to sign in | -| `401` + `X-Diary-Reauth: required` | the diary's session expired | ask for the password again | +| `401` + `X-Diary-Reauth: required` | the diary's session expired | sign in again — a new session to register, or the password on `/login` | +| `403` | on `/diary/session` only: the account has no pupil | say so; signing in again will not change it | | `404` | this account has no such child | — | -| `422` | on reads, the date range is inverted or wider than 62 days; on `PUT .../overrides`, the correction was refused: an unknown `target`, an uncorrectable field, or an empty value where empty is not allowed | on a read, fix the range; on a correction, show `detail` | -| `429` | on `/diary/login`, ten failed sign-ins from this address inside fifteen minutes | wait out `Retry-After`, and do not blame the password | +| `409` | on `/diary/session` only: the diary will not take this session from this server | say it is not the password; do not retry by itself | +| `422` | on reads, the date range is inverted or wider than 62 days; on `PUT .../overrides`, the correction was refused: an unknown `target`, an uncorrectable field, or an empty value where empty is not allowed; on `/login` and `/session`, a body or a region this server will not sign in with | on a read, fix the range; on a correction, show `detail` | +| `429` | on `/diary/login` and `/diary/session` together, ten counted failures from this address inside fifteen minutes | wait out `Retry-After`, and do not blame the password | | `502` | the diary answered incomprehensibly | say that the service has changed | -| `503` | the diary is not answering | offer to retry | +| `503` + `X-Diary-Unavailable: disabled` | this deployment has no `DIARY_SECRET`; the diary is off here | say it is off on this server; nothing typed will help | +| `503` + `X-Diary-Unavailable: address-refused` | the region's server drops this server's address | say it is not the password, and not worth retrying | +| `503` + `X-Diary-Unavailable: upstream` | the diary is not answering, or at sign-in answered that it takes only Госуслуги | offer to retry later | + +**Every `503` under `/api/v1/diary` carries `X-Diary-Unavailable`**, `/login`'s included, +because the three cases want three different sentences and `detail` is Russian prose a +client should not parse. A `503` is also the one refusal the sign-in limiter never counts: +in each case nothing read what was typed. One code for two different things is the price of both the range and the correction being checked as a request body. What tells them apart is the **call**, not the answer: there is @@ -1236,8 +1400,10 @@ So what you have is the first twenty of an unknown number, and the only way to r school is a longer query — adding the town or the number. A client that shows "20 found" would lie about a search that matched three hundred schools. -**Every call is one search upstream**, whatever `page` says: the source has no offset and -there is nothing to resume. A client that pages should ask once with `page_size=20` and cut +**Every call is one search upstream** — two when the first finds nothing, because an empty +answer under the three school ОКВЭД codes is asked again without them and filtered to the +education group — whatever `page` says: the source has no offset and there is nothing to +resume. A client that pages should ask once with `page_size=20` and cut the answer itself — which is what both the bot and the app do. Four pages of five is four searches for one question. `page_size` runs from 1 to 20, and the default is 5 (the size of an inline keyboard). @@ -1253,3 +1419,84 @@ appears. Admin, even though it writes nothing: every call spends part of a daily limit on somebody else's service, and only your own class is reason enough to spend it. + +## Which regions a school is in: `GET /api/v1/directory/school-regions` + +The one directory question a phone may ask before it belongs to any class, has a diary or +holds any token: «which regions is a school of this name in», so that somebody who types +«лицей 1535» is offered Москва rather than a list of eighty-nine regions. **Anonymous.** +Nothing depends on it — picking the region from the list always works, and every failure +here says «выберите регион из списка». + +``` +GET /api/v1/directory/school-regions?q=лицей 1535 +``` + +```json +{ + "query": "лицей 1535", + "regions": [ + { "region": "moscow", "code": "77", "label": null, "schools": 2, + "cities": ["Москва"], "examples": ["ГБОУ \"Лицей № 1535\""] } + ], + "truncated": false, + "generic": false +} +``` + +It is the same search as `/manage/schools` — same upstream, same query rules, same twenty-row +ceiling — with the rows grouped by region instead of paged. A row is placed by the two-digit +subject code at the front of the register's `region_kladr_id` and, when that is missing or +unknown, by the register's own name for the region matched exactly against the region +catalog's spellings of it ([diaries.md](diaries.md#the-region-catalog)). `region` is then the +catalog's key, the one the phone's bundled copy of the same catalog knows, and a placed +region is named from the catalog in the reader's language. A row the catalog cannot place +comes back with `region: null`, the register's own `code`, and its own name in `label`; a +row naming no region at all is left out. Groups are ordered by their best-ranked hit, at most +ten; `schools` counts the hits in the region, `cities` and `examples` show up to three of +each. A branch registered under its head school's number but standing in another region is a +group of its own there, which the bot's picker — deduplicating on the number — never needed. + +`truncated` means what it means on `/manage/schools`: the ceiling of twenty was reached, so +these are the regions of the first twenty matches. `generic` means the name is too common to +place. It is answered **without asking the register** when, once the words a school's name is +made of are taken away (the catalog's `school_words`, the list the phone reads too), nothing +is left but a number of one or two digits — «Школа № 5», «СОШ 12», «гимназия 3» are in every +region; «лицей 1535» and «гимназия 1 Казань» are asked. It is also set, on top of the +regions found, when a full answer of twenty spans four regions or more. Either way a client +should say so and show the list. + +**Anonymous means two limits.** Every call past validation counts against its caller — twenty +in fifteen minutes, **found or not**, because a search that finds its school has spent the +same upstream request as one that does not — in a bucket of its own on the table `/join` +counts in, with the same fifteen-minute window, because every recorded attempt prunes that +whole table to its own window. And every request it sends upstream is spent from a daily +allowance: **4,000 of DaData's 10,000 requests a day**, counted per Moscow day in +`usage_counters` by one atomic statement (`services/quota.py`), the empty-answer retry +included — and skipped, with an empty answer, when the second unit is not there. The bot's +search and `/manage/schools` are not charged to it and not capped by it, so no amount of +anonymous searching leaves an admin creating a class with «Лимит запросов исчерпан». Why the +day is Moscow's is in [architecture.md](architecture.md#a-daily-allowance-counted-in-the-database). + +In this order, and the order is the contract: + +| Status | When | Counted against the caller | +| --- | --- | --- | +| `429` + `Retry-After` | the caller has spent its twenty | — | +| `422` | `q` is shorter than three characters after whitespace is collapsed; `detail` is a Russian sentence | no | +| `503` + `X-Directory-Unavailable: disabled` | this deployment has no `DADATA_TOKEN` | yes | +| `200` with `generic: true` | a type word and a small number, answered without the register | yes | +| `503` + `X-Directory-Unavailable: spent` + `Retry-After` | today's anonymous share is gone; `Retry-After` runs to Moscow midnight | yes | +| `503` + `X-Directory-Unavailable: upstream` | the register failed in any way — not answering, answering something new, or refusing the key or its own daily allowance | yes | +| `200` | the regions found, possibly none | yes | + +`q` is cut to 150 characters, and `query` in the answer is what was searched. The header says +which `503` it is for the reason the diary's does: the client picks its sentence without +reading the Russian. A client should ask on submit or after a pause in typing, never per +keystroke. + +Not verified: whether DaData's party rows carry `region_kladr_id` at all — the name fallback +exists for the case where they do not; the subject codes 90, 93, 94 and 95 of the four +regions admitted in 2022, which the catalog marks as unverified; every one of the catalog's +DaData spellings; DaData's own day boundary; and two requests racing for the last unit on +Postgres, which has been checked on SQLite only. Nothing here has been asked of a live DaData. diff --git a/docs/architecture.md b/docs/architecture.md index 000887cb..53ebd48d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -30,6 +30,7 @@ app/ ├── schemas.py the wire contract ├── security.py tokens, join codes, phone normalisation ├── di.py the container both shells take a session from +├── catalog/ the region catalog — generated data, never edited by hand ├── api/ read-only client endpoints ├── bot/ aiogram routers, roles, keyboards, renderers └── main.py FastAPI app; its lifespan owns the bot's polling task @@ -299,7 +300,7 @@ can swap wholesale. ## The service layer, and why the phone does not log in -`server/app/services/` is twenty-one modules of pure async functions over a session, and +`server/app/services/` is twenty-two modules of pure async functions over a session, and they exist for exactly one reason: every feature of the product now has two entrances, the bot and the app. Homework is added by a command in a chat and by a button on a phone; so are a substitution, an event and a special day. Two implementations of one rule would have @@ -369,9 +370,16 @@ no reader would see, was the change deliberately not made. `registry.py` answers two questions in one place. `provider_for(key)` maps a stored key to an implementation, importing the provider module lazily so neither upstream's HTTP client lands on the cold-start path of a request that does not use it. `binding(school_class)` resolves -what a class is bound to; the bot menu, the class card and the web form all call it, so "is -this class bound, and to what" has a single answer, and a class bound to a «Сетевой город» -region since dropped from the allow-list reads as unbound rather than as a dead name. +what a class is bound to; the bot menu, the class card, the web form and `POST /join`'s +`diary` field all call it, so "is this class bound, and to what" has a single answer, and a +class bound to a «Сетевой город» region since dropped from the allow-list reads as unbound +rather than as a dead name. Its mirror is `services/diary.reads_binding`, the one clause for +"which sessions does this binding read": the bot's lookup filters by it, and binding a class +to another diary or another region expires, in the same commit, the members' sessions it no +longer reads — a session is an account on one regional server, and one left live on the +server the class moved away from would go on being pinged by the keep-alive for nobody +(#145). Another school in the same region keeps them; unbinding expires nothing, because it +takes the door away and the sessions stay their owners' until they sign out. The boundary each provider draws is three files, and it holds them: @@ -407,19 +415,100 @@ that is not a bad row any more, it is a changed response shape, and a `WARNING` with the list of keys that arrived: an empty week caused by a renamed field and an empty week caused by the holidays look identical from above otherwise. -The password is not stored, for either diary. A login is needed for one request, after which -the upstream's own session is what lives on. Petersburg refreshes it from its own answers and -we simply keep the newest; «Сетевой город» idles a session out in 15–60 minutes, so the cron -tick keeps each live one alive with `GET /webapi/context` (the mechanism is in +The password is not stored, for either diary. What lives on is the upstream's own session. +Petersburg refreshes it from its own answers and we simply keep the newest; «Сетевой город» +idles a session out in 15–60 minutes, so the cron tick keeps each live one alive with +`GET /webapi/context` (the mechanism is in [deploy.md](deploy.md#the-clock-the-server-has-none-and-githubs-will-not-do), the counters in [api.md](api.md)). When a session dies either way, the request answers `401` with -`X-Diary-Reauth: required` and the app asks for the password again. The price is that a -background sync of the diary does not outlive the session; the price of the alternative is -every family's password in the database. +`X-Diary-Reauth: required` and the person signs in again. The price is that a background +sync of the diary does not outlive the session; the price of the alternative is every +family's password in the database. + +### Two ways a session arrives, and only one of them sees the password + +A session of ours used to be opened one way: the password came to this server — from the +app's `POST /api/v1/diary/login`, or from the bot's `/diary/signin` page — and the server +signed in. "Not stored" was true; "never seen" was not. So there is now a second door, +`POST /api/v1/diary/session`: a client signs in with the diary itself, straight at the +allow-listed origin, and hands over **the session** the diary gave it, never the password. +The server does not take that session on trust. It reads with it once, from its own address +— Petersburg's pupils, or «Сетевой город»'s four bootstrap calls, which also fill the year +and the type map a sealed session cannot read without — and only then seals it, through the +same `_open_row` a password sign-in goes through, so "what a session holds" has one answer +whichever door it came in by. The read is the whole check: a session the upstream will not +take from this address is worth nothing to keep, and a registration it refuses is a `409` +rather than a request for the password, because the password was never the problem and +asking for it again would loop. Whether either diary does take a session opened in Russia +and replayed from Frankfurt is exactly what has never been seen; the contract, the statuses +and the shared limiter are in [api.md](api.md#the-electronic-diary). + +The cost is that the sign-in protocol now lives on both sides — a client that registers +speaks it to the diary, and the server still speaks it for the bot and for older apps — and +two implementations of «Сетевой город»'s salted hash over a windows-1251 password agree +exactly until they do not. The known-answer +vectors in `server/tests/vectors/diary_protocol.json` are the one set of bytes both are +tested against; the Python half is driven over `httpx.MockTransport`, and #147 and #148 — +a sign-in that sent the word `None` upstream, and malformed answers that escaped as `500` — +were fixed in the same change. + +The other doors stay. `/diary/login` is unchanged for the apps that still call it. The bot's +page still relays the password — it posts to this server, which passes it to the diary once +and writes it nowhere — and since #150 **it says so**: the page and the two cards before it +used to promise the password went «прямо в дневник», which it never did. A registered +session carries no Telegram account and no class, so the bot does not see it and a family +signed in on the phone signs in again in the bot. Linking the two is deliberately deferred +(#143). It would need the class device token on a `/diary` request — the one place the two +bearer families would meet — and a linked session would inherit the bot's rules: the bot's +«Выйти» would sign the phone out too, deleting the class would take the phone's session with +it, and rebinding the class would expire it. Those are the owner's to weigh first. + +### The region catalog is generated, not written + +«Which region is this family in, and what can it do there» has one answer, and it is the +survey's. `server/app/catalog/data/regions.json` is generated from +[diaries/regions.md](diaries/regions.md), a hand-written overlay and the server's own +allow-list by `python -m scripts.region_catalog`, and committed; a test fails when the +committed file and its inputs disagree. Generated, because the alternative was prose parsed +at run time, or a second hand-kept list of eighty-nine regions that would disagree with the +survey within a month; committed, because the server reads it at run time and the app is to +bundle the same file, and neither should run a generator to start. The decisions it carries — which systems are a sign-in, +which a hand-off to the browser, why there is no Госуслуги sign-in anywhere — are written +down beside the survey, in [diaries.md](diaries.md#the-region-catalog). The server reads four +things from it: a region's key, its subject code, its names and DaData's spellings of it, +which is what placing a school from the company register needs; `app/catalog/` loads it on +first use rather than at import, so no other cold start pays for parsing it. + +### A daily allowance, counted in the database + +The school directory has two doors onto one DaData key and its ten thousand requests a day: +the bot and `/manage/schools`, behind a class admin, and +`GET /api/v1/directory/school-regions`, which a phone asks **anonymously** before it belongs +to anything. Without a cap on the second, anybody with a loop could spend the day and leave an +admin creating a class with «Лимит запросов исчерпан». So the anonymous door gets a fixed +share, 4,000, and stops there; the admins' side is not metered at all. + +The count is `usage_counters` (revision `0016`), one row per allowance per day, and not the +obvious alternatives. Not memory, for the reason every limiter here gives: on Vercel each +concurrent invocation is its own process. Not `join_attempts`, although the per-caller +throttle lives there: that table is pruned to fifteen minutes on every recorded attempt, and a +day's count kept in it would silently become a quarter of an hour's. The spend is a single +`INSERT … ON CONFLICT … DO UPDATE … WHERE used + n <= cap RETURNING`, so two invocations +reaching for the last unit cannot both have it — there is no read-then-write to race through +(checked on SQLite; on Postgres by construction, not by a test). A unit is spent **before** the +request it pays for, and the empty-answer retry asks for its own unit first, because DaData +counts a request whatever comes of it. + +The day is Moscow's (`services/quota.py:QUOTA_ZONE`), not UTC and not the server's. DaData is a +Moscow company and its allowance is assumed to turn at Moscow midnight — assumed, because +nothing in its documentation says which clock it counts by. If the assumption is wrong and it +counts in UTC, the worst case is two anonymous days inside one of DaData's, 8,000, which still +leaves the admins two thousand. The server's zone was never a candidate, because it moves +with the host. ## Testing -1668 tests on the server, 968 on Android; `pytest -q -n auto` and `./gradlew test`, both +1915 tests on the server, 968 on Android; `pytest -q -n auto` and `./gradlew test`, both offline, both in CI. On Android that is `:core:model` 125, `:core:data` 286, `:core:designsystem` 95, `:widget` 90, `:app` 368. @@ -439,6 +528,10 @@ The table below is the load-bearing part of that rather than the whole of it: | `server/tests/test_timezones.py` | all eleven Russian zones, ordering, bad-input fallback | pytest | | `server/tests/test_bot_message_limits.py` | that no renderer builds a message Telegram refuses at 4096 characters | pytest | | `server/tests/test_schema_version.py` | `EXPECTED_REVISION` equals the real Alembic head, and there is exactly one head | pytest | +| `server/tests/test_diary_session.py` | registering a session a client opened: both body shapes, a `password` key refused, no refused value echoed, every status and which of them the shared limiter counts | pytest + a fake upstream | +| `server/tests/test_diary_protocol_vectors.py` | both diaries' sign-in protocols against the known-answer vectors in `tests/vectors/diary_protocol.json`, the bytes the phone's port is tested against too | pytest + `httpx.MockTransport` | +| `server/tests/test_region_catalog.py` | that the committed catalog is what the generator writes, and that only Петербург and the sixteen password «Сетевой город» regions are a sign-in | pytest | +| `server/tests/test_directory.py`, `test_quota.py` | the anonymous school directory's order of refusals, the per-caller throttle, the daily share and its atomic spend, and `0016`'s DDL against the model | pytest | | `android/core/model/.../ScheduleEngineTest.kt` | every `DayState`, boundary conditions, event precedence, next-transition scheduling | JVM JUnit | | `android/widget/.../WidgetSizeClassTest.kt` | the launcher's nearest-breakpoint rule over real sizes, and that the ladder is monotonic | JVM JUnit | | `android/app/.../ResourceTranslationTest.kt` | every Russian string has an English twin, in every module that ships strings | JVM JUnit | diff --git a/docs/bot.md b/docs/bot.md index d73cf6d1..bea91b7a 100644 --- a/docs/bot.md +++ b/docs/bot.md @@ -480,24 +480,41 @@ region step probes that region's sign-in options first, so an admin learns once the school step searches the region's own server by name and offers what it found. Binding gives the class *nothing*: it puts one button on every member's menu, and behind that button is each member's own account with the bound diary. Nobody in the class sees anybody else's -child. +child. Binding another diary, or another «Сетевой город» region, expires in the same step the +members' sessions on the one the class left — they would otherwise go on being kept alive on +a server nobody here reads; another school in the same region keeps them, and unbinding +expires nothing. That is enforced rather than asserted. Every lookup in `handlers/diary.py` starts from `callback.from_user.id`, and a session is found by `(telegram_id, class_id)` and nothing else — so a crafted payload reaches the presser's own diary or nothing at all. The class half matters too: a parent in -two classes must not read one child's diary from the other class's screen. +two classes must not read one child's diary from the other class's screen. A diary +session registered from a phone (`POST /api/v1/diary/session`) carries neither, so the bot +does not see it and a family using both signs in twice; linking the two is deferred (#143). **The password never enters Telegram.** «🔐 Войти в дневник» hands out a link to `/diary/signin/`, a page this app serves itself. Its subtitle names the bound diary — and, for «Сетевой город», its region and school (the school name escaped, because it came from the upstream's search) — so the family can see where the password is going. -The password goes from that browser straight to the bound diary (dnevnik2 for Петербург, -the region's own server for «Сетевой город») and is written down nowhere — not in the chat -history, not on Telegram's servers, not in the notification on a locked screen, -not in the phone's backup. The form re-reads the class's binding at both the GET and the -submit, so a class unbound or rebound since the link was made refuses before the password -is sent, rather than sending it to a diary the family is no longer looking at. A ticket is +The form posts the password to this server, which passes it to the bound diary (dnevnik2 for +Петербург, the region's own server for «Сетевой город») for the sign-in and writes it down +nowhere — not in the chat history, not on Telegram's servers, not in the notification on a +locked screen, not in the phone's backup, not in this database and not in the log. + +The three texts a parent reads before typing it say exactly that. The card with the link: +«Пароль вводится на странице, а не в чате. Сервер бота передаёт его дневнику для входа и +нигде не сохраняет — ни у бота, ни в этой базе.» The card of somebody not yet signed in: +«Бот даст ссылку на страницу входа на своём сервере: сервер передаёт пароль дневнику для +входа, и пароль нигде не сохраняется.» The page's own note: «Пароль вводится здесь, а не в +чате. Эта страница — на сервере бота: он передаёт пароль дневнику для входа, и пароль нигде +не сохраняется…». Until #150 all three said the password went «прямо в дневник» and that the +bot never saw it, which was never true; a test now fails on the old wording. They make no +claim about the app either way: an app built before registration still posts the password to +this server, and the page cannot tell which one the reader holds. + +The form re-reads the class's binding at both the GET and the submit, so a class unbound or +rebound since the link was made refuses before the password is sent, rather than sending it to a diary the family is no longer looking at. A ticket is worth **one** sign-in for fifteen minutes for one Telegram account in one class; a GET checks it without spending it (Telegram fetches link previews by itself), a POST spends it before @@ -508,7 +525,10 @@ cannot read still costs it: a login form on Yii refuses a password with the same "200 with some HTML" a captcha arrives in, so forgiving that would turn the link into an unlimited password oracle against the upstream from our address. The page says so in words rather than blaming the password, which is what it used -to do for every failure that was not a plain 401. +to do for every failure that was not a plain 401, and names the bound diary's own +address to open in a browser — taken from the allow-list, never from anything typed. It +used to name dnevnik2 whatever the class was bound to, which sent a «Сетевой город» family +to Петербург's diary to see whether theirs was down (#158). The session is stored encrypted (`DIARY_SECRET`, `app/crypto.py`). Without that key the whole feature refuses at the door rather than falling back to diff --git a/docs/deploy.md b/docs/deploy.md index 00543123..1b137ea2 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -178,9 +178,11 @@ the variable and redeploying. ### The electronic diary -`DIARY_SECRET` is the key the electronic diary's session is encrypted with (`app/crypto.py`). -It is the only credential in the project that cannot be stored as a hash: the diary's token -is sent upstream on every request, so it is encrypted rather than hashed. +`DIARY_SECRET` is the key the electronic diary's session is encrypted with (`app/crypto.py`) +— every session, whether this server signed in with a password or a phone signed in itself +and registered what the diary gave it. It is the only credential in the project that cannot +be stored as a hash: the diary's token is sent upstream on every request, so it is encrypted +rather than hashed. ```bash python3 -c "import secrets; print(secrets.token_urlsafe(48))" @@ -190,7 +192,9 @@ Without it the diary is **switched off entirely** rather than running in plainte fallback to plaintext would be invisible — the feature answers, and the only difference is in a column nobody looks at — and deployments live like that for years. "Too short" counts as missing: anything under 32 characters is refused at the same door, and the startup log says -the diary is off rather than letting a set-but-unusable key look configured. +the diary is off rather than letting a set-but-unusable key look configured. A client can +tell before anybody types a password: `GET /api/v1/diary/capabilities` answers +`"enabled": false`, and every diary `503` carries `X-Diary-Unavailable: disabled`. Three things worth knowing about this key: @@ -232,21 +236,41 @@ company register, where every school appears simply because every school is a le and DaData, which is a search over it that people actually use. The key is taken from https://dadata.ru/profile/#info — you want the "API key", not the -"secret key". The free plan is 10,000 requests a day; the bot makes one request per search -and pages through the results locally, so the pages cost nothing. +"secret key". The free plan is 10,000 requests a day. A search is one request, and **two +when the first finds nothing**: an empty answer under the three school ОКВЭД codes is asked +again without them, so that somebody who typed their own school's name is not told it does +not exist. The results are paged locally, so the pages cost nothing. + +Two doors spend that allowance, and one of them is capped. The bot and +`GET /api/v1/manage/schools` search behind a class admin, a few searches per class created, +and are not metered here. `GET /api/v1/directory/school-regions` is asked +**anonymously**, by a phone that belongs to no class yet, so that door gets a fixed share: +**4,000 requests per Moscow day**, the empty-answer retry included, counted in the database +(`usage_counters`, revision `0016`). When the share is spent it answers `503` with +`X-Directory-Unavailable: spent` and «выберите регион из списка» until Moscow midnight, while +the other 6,000 stay for the bot's create-class step — which is what the cap exists to +protect. Each caller is also held to twenty searches in fifteen minutes. The share is a +constant (`ANONYMOUS_DAILY_UNITS` in `app/services/quota.py`), not a setting; on a paid plan +with a larger allowance, change it there. Whether DaData's own day turns at Moscow midnight +is not documented anywhere: if it counts in UTC, the worst case is two anonymous days inside +one of DaData's, 8,000, which still leaves the admins 2,000. Worth knowing: * **The key lives only in the server's environment.** It is not in the APK and must not be: - the phone asks our server (`GET /api/v1/manage/schools`), and the server goes upstream. + the phone asks our server (`GET /api/v1/manage/schools`, or the anonymous + `GET /api/v1/directory/school-regions` before it has a class), and the server goes + upstream. * **Twenty is a ceiling, not a number of matches.** DaData's endpoint is built for type-ahead suggestions: it returns no more than twenty at a time and has no offset ("the next twenty"). So the answer honestly says «показаны первые 20» rather than «найдено 20», and the only way to reach your school is to add the town or the number. * **A missing key is not a breakage.** The search answers 503 with the words «введите - название вручную», and a class is created as before. There is deliberately no fallback - list inside the project: a snapshot of the register would confidently answer with last - year's schools, and nothing on the screen would tell you which you were looking at. + название вручную», and a class is created as before; the anonymous directory answers + 503 with `X-Directory-Unavailable: disabled`, and the region is picked from the list. + There is deliberately no fallback list inside the project: a snapshot of the register + would confidently answer with last year's schools, and nothing on the screen would tell + you which you were looking at. ### The Neon connection string @@ -302,13 +326,17 @@ rewrote nothing. `0013` adds `uq_homework_per_subject_per_day`. `0014` widens stores the member name, so the column is as wide as the longest of them. `0015` adds the columns a second diary provider needs: `diary_sessions.provider` and `region` and the three keep-alive clocks, and `classes.diary_region`, `diary_school_id` and `diary_school_name` — -eight nullable columns, additive, applied before the merge. Its downgrade expires every +eight nullable columns, additive, to go on before the merge. Its downgrade expires every non-Petersburg session first, so code rolled back past this revision cannot read a «Сетевой -город» credential as Petersburg's and replay it at the wrong upstream. +город» credential as Petersburg's and replay it at the wrong upstream. `0016` creates +`usage_counters` — one row per external allowance per Moscow day, the anonymous school +directory's share of DaData's — and nothing else: one new table, no existing row read or +rewritten, additive, and it goes on **together with `0015`, before #140 merges**. Its +downgrade drops the table, which loses nothing but the counts. Everything up to `0012` checks with an inspector what is not in the database yet and does not rewrite existing tables, so those can be applied to a live class in the middle of a -school day. The head is `0015`. +school day. The head is `0016`. ### A migration goes BEFORE the deploy, not after @@ -341,7 +369,7 @@ into the database by hand: curl -s https://.vercel.app/api/v1/warmup ``` -`{"status":"ok","schema":"0015"}` means it all lines up. `"status":"degraded"` together with +`{"status":"ok","schema":"0016"}` means it all lines up. `"status":"degraded"` together with `expected_schema` names both revisions and says which way they diverged: «База отстала от кода» — the database is behind the code — is an incident, while «База впереди кода» — the database is ahead — is the normal window between steps 1 and 2, which the deploy closes. @@ -351,7 +379,8 @@ a ping meant to warm things up would keep waking a sleeping Neon. ### What to apply them with In practice this project's migrations are applied **through the Neon connector** rather than -with the `alembic` command — that is how `0005`–`0015` were applied. The Neon project is +with the `alembic` command — that is how `0005`–`0014` were applied, and how `0015` and +`0016` are to go on before #140 merges. The Neon project is called `lessons`; its identifier is not kept in the repository — anybody with access sees it in the Neon console anyway, and in a public repository it is just the address of somebody else's database. @@ -495,7 +524,7 @@ stack instead of being buried in the API's log, and so that a migration can be r with `docker compose run --rm migrate`. It needs only `DATABASE_URL`: `get_settings()` is never called there, so `BOT_TOKEN` and `OWNER_IDS` are not its business. `GET /api/v1/warmup` is what confirms the result, and it is the endpoint that can: it says -`{"status": "ok", "schema": "0015"}` when the two agree and names both revisions when they +`{"status": "ok", "schema": "0016"}` when the two agree and names both revisions when they do not. The app on the phone needs to reach the API. The options are a public IP with a forwarded diff --git a/docs/diaries.md b/docs/diaries.md index c3c5aba5..ded8b5d5 100644 --- a/docs/diaries.md +++ b/docs/diaries.md @@ -299,6 +299,7 @@ made ЕСИА the only way a family signs in: Дневник.ру per region, « and a password, which is what `/diary/signin` was built around. Almost no other region's diary does, so a second provider cannot reuse that page as it stands: it would have to accept a token a person brought from a browser, or drive ЕСИА, and the second is the fragile one. + This project does neither — see the next bullet but one. - **The largest single group is «Сетевой город»**, one route set on some fifty regional servers; after it come Дневник.ру and the МЭШ family. Any one of those is a provider that covers many regions at once. The platforms of one region each — КИАСУО, ЭПОС.Школа, the @@ -307,17 +308,96 @@ made ЕСИА the only way a family signs in: Дневник.ру per region, « routes of «Госуслуги Моя школа» are known from the official app, and a single batched call carries the whole diary; but the sign-in is Госуслуги's own, its `client_secret` is signed on Госуслуги's side, and the only way a third party has found in is a person signing in inside a - WebView. Until that is judged acceptable — technically and under the service's terms — the - manual half of this product, the class kept by hand in the bot, is the only half for those - regions, which is what #127 already says about every region that is not Петербург. -- **The platform that came second is «Сетевой город» (#135, #139), and its server side is now + WebView. **This project has decided not to take it**: a Госуслуги session is a session to the + person's whole state-services account, not to a school diary, and an app that captured one + would be holding far more than it reads. There is no Госуслуги sign-in, no WebView and no + cookie capture anywhere in it; for ТОР, the [region catalog](#the-region-catalog) hands off + to `https://www.gosuslugi.ru/school` in the browser, and the class kept by hand in the bot is + this project's half for those regions — which is what #127 already says about every region + that is not Петербург. +- **The platform that came second is «Сетевой город» (#135, #139), and its server side is written.** The owner chose it, and `server/app/providers/netschool/` reads it behind the - shared diary contract, from [its reference page](diaries/netschool.md). What #135 still - leaves to the owner is how a family signs in where a region offers only Госуслуги, and - whether ТОР «Моя школа» may be used at all. And the first step nothing has taken for any + shared diary contract, from [its reference page](diaries/netschool.md). The two questions + #135 left open are settled the same way as ТОР: the three regions that take only Госуслуги + (Алтайский край, Приморский край, Тульская) are a hand-off to their own server's page, never + a sign-in, and ТОР is a hand-off too. The sixteen that still take a password are signed into + — by this server with the password, or by a client that signs in itself and registers the + session ([api.md](api.md#the-electronic-diary)). And the first step nothing has taken for any platform is one real session against it: not one route in these pages has been seen answering, «Сетевой город» included. +## The region catalog + +This survey is also data. «Which region is this family in, and what can it do there» — a +sign-in, a hand-off to a page in the browser, or only the class code — is answered from it, +turned into a file once rather than parsed as prose: `server/app/catalog/data/regions.json`, +**generated** by `python -m scripts.region_catalog` (run from `server/`). The server reads it +to place a school found in the company register in a region +([api.md](api.md#which-regions-a-school-is-in-get-apiv1directoryschool-regions)), and the +same file is written for the app to bundle. It is therefore exactly as current as the survey +— September 2026 — and exactly as tested: nothing in it was read from a live diary either. + +**Three inputs, each trusted for one thing.** + +- [diaries/regions.md](diaries/regions.md) — which systems a region runs, in what role, on + which hosts, how sure the survey is. The regions table on this page is read only to + cross-check it row by row, because it is a tool's summary and cuts names off with «…»; the + month in its header («In use now (September 2026)») is held equal to the overlay's. +- `server/scripts/region_catalog.toml`, the overlay — what nothing in the repository derives: + each region's key, its two-digit subject code, its English name, zone, aliases and a few + cities, DaData's spellings of it, the platforms' names, and the phone's search lexicon. +- The server's allow-list (`app/providers/netschool/regions.py`) and Petersburg's `BASE_URL` + — every origin a sign-in may go to, and whether a «Сетевой город» region takes a password. + Copied, never retyped: the survey's hosts only have to *agree* with the allow-list, which + catches a server that moved in one file and not the other, and the nineteen «Сетевой город» + keys are the allow-list's own, byte for byte, because they are already stored in + `classes.diary_region`, `diary_sessions.region` and the sealed credential. + +**Never edit the JSON by hand.** A change to a region goes into regions.md or the overlay, and +the generator is run again. `server/tests/test_region_catalog.py` runs the generator's +`--check` and fails when the committed file is not what the survey, the overlay and the +allow-list imply, so a survey edit cannot ship without the catalog it implies. The generator +refuses rather than guesses — a system bullet it cannot read, a region the overlay and the +survey do not both have, an allow-listed origin missing from the survey's hosts, this page's +table disagreeing with regions.md about a region's diary, one DaData spelling claimed by two +regions — and names the region when it does. An edit to this page's regions table therefore +has a consequence in code now, and the tests say so. + +**What the catalog decides for each system a region runs:** + +| `action` | Which systems | What it means | +| --- | --- | --- | +| `signin` | «Петербургское образование»; «Сетевой город» in the sixteen allow-listed regions that take a password | a sign-in this project implements, with the session kept by the server ([api.md](api.md#the-electronic-diary)) | +| `handoff` | ТОР «Моя школа» wherever the survey lists it as in use, alongside or moving to; «Сетевой город» in `altai-krai`, `primorye` and `tula`, which take only Госуслуги | a page opened in the browser: `https://www.gosuslugi.ru/school` for ТОР, the region's own «Сетевой город» origin for the three | +| `none` | every other system, and any system the survey marks as previous or unclear | nothing to sign in to; the class kept in the bot is what there is | + +`test_only_petersburg_and_password_netschool_are_signable` holds that table: exactly those +seventeen systems are `signin`, every hand-off goes where the table says, and no field or text +from the survey's WebView era — an in-page sign-in surface, «на странице дневника» — can reach +the catalog. Where ТОР is not offered at all (Запорожская, Херсонская, and Севастополь with its +journal suspended), the catalog says `absent` and never recommends it. + +**Each region also names one system to put first**, with a reason code. The JSON carries only +the codes; the sentences are the phone's string resources keyed by them, so each has its +English twin checked like every other string. First match wins: + +| Reason | When | Regions, September 2026 | +| --- | --- | --- | +| `primary` | the region's main system is `signin` | 17 — Петербург and the sixteen password «Сетевой город» regions | +| `tor_primary` | the main system is ТОР «Моя школа» | 20 | +| `primary` + `esia_only` | the main system is a «Сетевой город» that takes only Госуслуги, handed off to its own origin | 3 | +| `unreachable` | the main system is a «Сетевой город» the allow-list leaves out — Волгоградская, whose server serves only `http`. Above `front_end` on purpose: that region also has «Госуслуги Моя школа» in front, and the family should first hear why their own diary cannot be opened | 1 | +| `front_end` | «Госуслуги Моя школа» is offered in front of the regional system, at medium confidence or better | 11 | +| `moving_to` | the region is moving to ТОР | 1 — Оренбургская | +| `no_diary` | there is no electronic diary | 1 — Севастополь | +| `unsupported` | anything else: a diary this project cannot read | 35 | + +Two modifiers ride on a reason: `unverified` on every `signin` recommendation, because nobody +has signed in to any of them for real, and `esia_only` as above. Not verified, beyond the +survey itself: the subject codes 90, 93, 94 and 95 of the four regions admitted in 2022, which +the overlay marks as believed rather than checked; every DaData spelling; and whether each +`web_url` host answers on https. + ## What is not covered - **Nothing here was tried against a live diary.** Every host refuses a connection from the diff --git a/docs/diaries/regions.md b/docs/diaries/regions.md index c2cd6116..7aeeb12d 100644 --- a/docs/diaries/regions.md +++ b/docs/diaries/regions.md @@ -9,6 +9,13 @@ says so — by the second round that went after the completeness critique's list Nothing here was read from a live diary: the evidence is regional portals, ministries, school sites and news, as of September 2026. +This page is also the input of the region catalog the server and the app read +([how it is built](../diaries.md#the-region-catalog)). `server/scripts/region_catalog.py` +parses each `## ` heading, the *Mandatory region.* line and the system bullets — role, +platform link, hosts, confidence — and nothing else: the «Open-source clients», «Notes.» and +«Checked:» bullets and the evidence indented under each system are for people. A change to a +parsed line needs the catalog regenerated, or `server/tests/test_region_catalog.py` fails. + ## Республика Адыгея - **in use now: [Дневник.ру](dnevnik-ru.md)** — Дневник.ру — РГИС «Цифровая образовательная платформа Республики Адыгея» (ООО «Дневник.ру»). Hosts: `dnevnik.ru`, `login.dnevnik.ru`, `schools.dnevnik.ru`. Confidence: high. From b19e6b2d0f9116b45bed9faa95001eb4c990ac6e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 17:15:28 +0000 Subject: [PATCH 15/30] Let a phone sign in to its own diary and hand our server only the session, and keep what it reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The data half of #141, in :core:data. The password now goes from the phone to the diary's own origin and nowhere else; our server receives the session the diary handed back, validates it with a call of its own, seals it, and answers with our diary bearer. The app no longer calls `POST /api/v1/diary/login`. Sign-in (wave A1): - `upstream/`: a provider HTTP client with none of our interceptors, no cookie jar and no redirects, whose only hosts are the https origins in the bundled region catalog (`OriginGuard`); Kotlin ports of the Petersburg and «Сетевой город» sign-ins, the windows-1251 table and the pw/pw2 hash carried in the code rather than trusted to the device's ICU; the phone-side school search against the region's own server. `UpstreamSession` lives in memory and is spent once registered or discarded. - The region catalog is `server/app/catalog/data/regions.json`, bundled in place as an asset, never copied; every case of `server/tests/vectors/diary_protocol.json` runs through the Kotlin code from the test classpath, over MockWebServer sockets where the case is a request, so the two implementations cannot drift apart silently. - `DiarySignIn` runs preflight (catalog, then `/diary/capabilities`), the diary sign-in, then `POST /api/v1/diary/session` with `credential`, and keeps only our bearer and a `DiaryTarget` (provider, region, school, login, zone; stored as one JSON key). A bare 401 now clears the token only (`clearDiaryToken`); signing out forgets the account (`forgetDiary`). - `DiarySignInProblem` is the one failure type every diary screen will switch on. It carries the phone half of #153: a 429 is a throttle, a 503 is read by `X-Diary-Unavailable`, a 504 or a socket timeout is a timeout, a 409 is «the diary refused this session from our address» with no automatic retry, a 422 is an app bug. The screen half of #153 is not done: the settings screen still draws three of these with one stand-in text. - The diary bearer is kept off `/diary/login`, `/diary/session` and `/diary/capabilities`; the class bearer off `/api/v1/directory/*` and `/api/v1/diary/*`. Neither interceptor had a test; both do now. - Settings → «Дневник» signs in through `DiarySignIn` with the stored target, or Petersburg when none is stored. Every :app test now uses one shared `FakeDiaryRepository`. What it keeps (wave A2): - `diary.db`, a second Room database (schema exported), written only by `DiaryRepositoryImpl`'s successful reads, with a generation guard so a read in flight during a sign-out is not written back after the clear. - `DiaryImport`: pupils, choice of pupil, terms, timetable, homework and marks, with weighted progress for the import screen, skippable phases and resume from the one that failed; `refreshIfStale` with a 30-minute freshness is the only refresh, driven by the app coming to the foreground. - `RegionSearch` over the 89 regions in Russian and English, aliases, cities, codes, the wrong keyboard layout and transliteration, and `SchoolDirectory` over `GET /api/v1/directory/school-regions` with its own `DirectoryProblem`. - `ShellMode` (none, class, diary) with the rule that arms periodic class sync only in class mode — the data half of #152 — and a diary-only phone as a mode of its own rather than the join screen — the data half of #151. Neither issue is closed until the app wires them. - `JoinResponse.diary` is kept on the stored session as the class's binding. - `SyncWorkerSourceTest` fails if the worker or the widget ever names the diary's repository, cache or import: there is no background diary read. Gates: `./gradlew test` 1187 JVM tests (968 before), `assembleDebug` and `assembleRelease` green; the only new Cyrillic in Kotlin is `UpstreamMarkers.kt`, the diaries' own words matched in their answers. Not covered: nothing has met a live diary or run on a device. Whether a diary accepts a session opened on a phone when our Frankfurt server replays it is open; 409 is the designed failure. TLS against the regional servers, Android's own windows-1251, Room on a device, and a Retry-After given as a date (read as no wait) are unverified. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .../lessons/ui/diary/DiaryScreen.kt | 8 + .../lessons/ui/diary/DiaryViewModel.kt | 51 +- .../ui/diary/DiaryCorrectionWritesTest.kt | 111 +--- .../ui/diary/DiarySignInOutcomeTest.kt | 129 ++-- .../lessons/ui/diary/FakeDiaryRepository.kt | 156 +++++ android/core/data/build.gradle.kts | 21 + .../1.json | 463 ++++++++++++++ .../core/data/catalog/RegionCatalog.kt | 186 ++++++ .../lessons/core/data/catalog/RegionLookup.kt | 76 +++ .../lessons/core/data/catalog/RegionSearch.kt | 245 ++++++++ .../core/data/catalog/SchoolDirectory.kt | 218 +++++++ .../core/data/datastore/LessonsPreferences.kt | 181 +++++- .../core/data/datastore/Memberships.kt | 40 +- .../lessons/core/data/di/LessonsContainer.kt | 164 ++++- .../lessons/core/data/diary/DiaryCache.kt | 321 ++++++++++ .../lessons/core/data/diary/DiaryCacheImpl.kt | 154 +++++ .../lessons/core/data/diary/DiaryDao.kt | 324 ++++++++++ .../lessons/core/data/diary/DiaryDatabase.kt | 59 ++ .../lessons/core/data/diary/DiaryEntities.kt | 146 +++++ .../lessons/core/data/diary/DiaryImport.kt | 121 ++++ .../core/data/diary/DiaryImportImpl.kt | 226 +++++++ .../core/data/diary/DiaryImportPlan.kt | 51 ++ .../lessons/core/data/diary/DiaryWindows.kt | 88 +++ .../core/data/diary/SeedingDiarySignIn.kt | 42 ++ .../core/data/network/AuthInterceptor.kt | 15 +- .../lessons/core/data/network/DiaryApi.kt | 47 +- .../core/data/network/DiaryAuthInterceptor.kt | 22 +- .../lessons/core/data/network/DirectoryApi.kt | 62 ++ .../core/data/network/NetworkModule.kt | 18 +- .../lessons/core/data/network/dto/DiaryDto.kt | 107 +++- .../lessons/core/data/network/dto/JoinDto.kt | 30 + .../core/data/repository/DiaryBinding.kt | 49 ++ .../core/data/repository/DiaryModels.kt | 84 ++- .../core/data/repository/DiaryRepository.kt | 35 +- .../data/repository/DiaryRepositoryImpl.kt | 168 +++-- .../core/data/repository/DiarySignIn.kt | 62 ++ .../core/data/repository/DiarySignInImpl.kt | 340 +++++++++++ .../data/repository/DiarySignInProblem.kt | 360 +++++++++++ .../core/data/repository/DiaryTarget.kt | 164 +++++ .../lessons/core/data/repository/Models.kt | 5 + .../data/repository/SessionRepositoryImpl.kt | 4 + .../lessons/core/data/repository/ShellMode.kt | 122 ++++ .../core/data/upstream/NetSchoolPassword.kt | 100 +++ .../data/upstream/NetSchoolSchoolSearch.kt | 141 +++++ .../core/data/upstream/NetSchoolSignIn.kt | 293 +++++++++ .../core/data/upstream/PetersburgSignIn.kt | 109 ++++ .../core/data/upstream/UpstreamDirectory.kt | 114 ++++ .../core/data/upstream/UpstreamFailure.kt | 79 +++ .../core/data/upstream/UpstreamHttp.kt | 206 +++++++ .../core/data/upstream/UpstreamJson.kt | 93 +++ .../core/data/upstream/UpstreamMarkers.kt | 34 ++ .../core/data/upstream/UpstreamSession.kt | 61 ++ .../core/data/catalog/RegionCatalogTest.kt | 74 +++ .../core/data/catalog/RegionSearchTest.kt | 130 ++++ .../core/data/catalog/SchoolDirectoryTest.kt | 194 ++++++ .../data/datastore/DiaryTargetStoreTest.kt | 138 +++++ .../core/data/datastore/MembershipsTest.kt | 41 ++ .../lessons/core/data/diary/DiaryCacheTest.kt | 246 ++++++++ .../core/data/diary/DiaryDaoPolicyTest.kt | 100 +++ .../core/data/diary/DiaryImportPlanTest.kt | 106 ++++ .../core/data/diary/DiaryImportTest.kt | 297 +++++++++ .../core/data/diary/DiaryTestSupport.kt | 335 ++++++++++ .../core/data/network/AuthInterceptorTest.kt | 63 ++ .../core/data/network/BearerTestSupport.kt | 50 ++ .../data/network/DiaryAuthInterceptorTest.kt | 84 +++ .../core/data/network/dto/DiaryJsonTest.kt | 65 +- .../core/data/network/dto/JoinJsonTest.kt | 71 +++ .../core/data/repository/DiaryFailureTest.kt | 51 ++ .../data/repository/DiaryRepositoryTest.kt | 133 +++- .../data/repository/DiarySignInProblemTest.kt | 162 +++++ .../core/data/repository/DiarySignInTest.kt | 575 ++++++++++++++++++ .../core/data/repository/ShellModeTest.kt | 117 ++++ .../core/data/sync/SyncWorkerSourceTest.kt | 69 +++ .../lessons/core/data/upstream/Cp1251Test.kt | 59 ++ .../data/upstream/DiaryProtocolVectorsTest.kt | 439 +++++++++++++ .../upstream/NetSchoolSchoolSearchTest.kt | 121 ++++ .../core/data/upstream/NetSchoolSignInTest.kt | 252 ++++++++ .../data/upstream/PetersburgSignInTest.kt | 117 ++++ .../data/upstream/UpstreamDirectoryTest.kt | 127 ++++ .../core/data/upstream/UpstreamHttpTest.kt | 213 +++++++ .../core/data/upstream/UpstreamTestSupport.kt | 165 +++++ android/gradle/libs.versions.toml | 5 + 82 files changed, 10761 insertions(+), 343 deletions(-) create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt create mode 100644 android/core/data/schemas/com.lumenpearson.lessons.core.data.diary.DiaryDatabase/1.json create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionLookup.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectory.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCache.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheImpl.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDao.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDatabase.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryEntities.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImport.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportImpl.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlan.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryWindows.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/SeedingDiarySignIn.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryBinding.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignIn.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ShellMode.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolPassword.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectory.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamFailure.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamMarkers.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamSession.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalogTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/DiaryTargetStoreTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDaoPolicyTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlanTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryTestSupport.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptorTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptorTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinJsonTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/Cp1251Test.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearchTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignInTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignInTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectoryTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamTestSupport.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt index 18f0e8f6..605d2adb 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt @@ -316,6 +316,14 @@ internal fun DiaryFailure.asText(): String = when (this) { DiaryFailure.BadRange -> correctedString(R.string.diary_error_range) DiaryFailure.Unreadable -> correctedString(R.string.diary_error_unreadable) DiaryFailure.Unavailable -> correctedString(R.string.diary_error_unavailable) + // Stand-ins until `DiaryProblemText` gives each its own sentence. «Try + // later» is right for a throttle and only half right for the other two — + // a diary switched off on the server, or one refusing its address, will + // not come back by waiting — so the screen half of #153 is not done here. + DiaryFailure.Disabled, + DiaryFailure.ServerAddressRefused, + is DiaryFailure.Throttled, + -> correctedString(R.string.diary_error_unavailable) // The server refusing a correction it could never apply. Its own message, // because "не получилось: 422" is not something to put in front of anybody. DiaryFailure.Rejected -> correctedString(R.string.diary_error_rejected) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index a05a2a99..0aba1442 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -11,7 +11,9 @@ import com.lumenpearson.lessons.core.data.repository.DiaryField import com.lumenpearson.lessons.core.data.repository.DiaryPeriod import com.lumenpearson.lessons.core.data.repository.DiaryRepository import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.LocalDate import kotlinx.coroutines.Job import kotlinx.coroutines.async @@ -19,6 +21,7 @@ import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -169,13 +172,23 @@ class DiaryViewModel( } } - /** Signs in, or answers the re-authentication prompt; both are the same call. */ + /** + * Signs in, or answers the re-authentication prompt; both are the same call. + * + * To the diary this phone already knows — the live session's, or the one a + * bare `401` left behind — so a re-authentication goes to the same + * provider, region and school with only the password typed. With none + * known this form can only mean Petersburg, the one diary it has ever + * offered; choosing another is the diary picker's, not this form's. + */ fun signIn(login: String, password: String) { if (state.value.signingIn) return viewModelScope.launch { state.update { it.copy(signingIn = true, signInError = null) } - val result = repository.signIn(login, password) - val failure = result.exceptionOrNull()?.let(DiaryFailure::of) + val known = state.value.session?.target ?: repository.target.first() + val target = known?.copy(login = login.trim()) ?: DiaryTarget.petersburg(login.trim()) + val result = repository.signIn(target, password) + val failure = result.exceptionOrNull()?.let(::signInFailure) state.update { it.copy( signingIn = false, @@ -546,3 +559,35 @@ class DiaryViewModel( } } } + +/** + * A sign-in's [DiarySignInProblem] in the words this screen already has. + * + * A bridge, and a lossy one: the sign-in now fails in more ways than the + * [DiaryFailure] this form was written against, and «слишком много попыток» + * or «дневник выключен на сервере» have no sentence here yet — they read as the + * nearest one. `DiaryProblemText` is where each problem gets its own; when this + * form switches to it, this function goes. + */ +internal fun signInFailure(failure: Throwable): DiaryFailure = when (failure) { + is DiarySignInProblem.WrongPassword, + DiarySignInProblem.LoginTooShort, + DiarySignInProblem.SignInRequired, + -> DiaryFailure.SignInRequired + DiarySignInProblem.ReauthRequired -> DiaryFailure.ReauthRequired + DiarySignInProblem.ServerDisabled -> DiaryFailure.Disabled + DiarySignInProblem.ServerAddressRefused -> DiaryFailure.ServerAddressRefused + is DiarySignInProblem.TooManyAttempts -> DiaryFailure.Throttled(failure.retryAfterSeconds) + is DiarySignInProblem.ProviderUnavailable, + is DiarySignInProblem.ProviderRefusesPhone, + is DiarySignInProblem.Timeout, + -> DiaryFailure.Unavailable + is DiarySignInProblem.ProviderUnreadable -> DiaryFailure.Unreadable + is DiarySignInProblem.ProviderOffline, + DiarySignInProblem.Offline, + DiarySignInProblem.RegisterUnreachable, + DiarySignInProblem.ServerMissing, + -> DiaryFailure.Offline(failure) + is DiarySignInProblem -> DiaryFailure.Unexpected(code = null, reason = failure) + else -> DiaryFailure.of(failure) +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCorrectionWritesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCorrectionWritesTest.kt index 0a45511d..608284aa 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCorrectionWritesTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCorrectionWritesTest.kt @@ -3,19 +3,11 @@ package com.lumenpearson.lessons.ui.diary import com.lumenpearson.lessons.core.data.repository.DiaryEdit import com.lumenpearson.lessons.core.data.repository.DiaryFailure import com.lumenpearson.lessons.core.data.repository.DiaryField -import com.lumenpearson.lessons.core.data.repository.DiaryHomework import com.lumenpearson.lessons.core.data.repository.DiaryLesson -import com.lumenpearson.lessons.core.data.repository.DiaryMark -import com.lumenpearson.lessons.core.data.repository.DiaryOverrideRecord -import com.lumenpearson.lessons.core.data.repository.DiaryPeriod -import com.lumenpearson.lessons.core.data.repository.DiaryRepository -import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiaryStudent import java.time.LocalDate import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -45,7 +37,7 @@ import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class DiaryCorrectionWritesTest { - private val repository = RecordingDiaryRepository() + private val repository = FakeDiaryRepository() @Before fun setUp() { @@ -263,105 +255,4 @@ class DiaryCorrectionWritesTest { private companion object { const val TARGET = "lesson:2026-09-07:n1:Алгебра" } - - private data class Written( - val target: String, - val field: DiaryField, - val value: String, - val original: String?, - ) - - /** Records what was asked of it, and can be told to stop answering. */ - private class RecordingDiaryRepository : DiaryRepository { - - var students: List = emptyList() - var failAfter: Int? = null - var failure: DiaryFailure = DiaryFailure.Unavailable - var reloads: Int = 0 - - val corrections = mutableListOf() - val resets = mutableListOf>() - - private val sessions = MutableStateFlow(null) - override val session: Flow = sessions - - private var writes = 0 - - private fun answer(value: T): Result { - val limit = failAfter - val outcome = if (limit != null && writes >= limit) { - Result.failure(failure) - } else { - Result.success(value) - } - writes += 1 - return outcome - } - - override suspend fun current(): DiarySession? = sessions.value - - override suspend fun signIn(login: String, password: String): Result { - val opened = DiarySession(login = login, token = "t") - sessions.value = opened - return Result.success(opened) - } - - override suspend fun signOut(): Result { - sessions.value = null - return Result.success(Unit) - } - - override suspend fun students(): Result> = Result.success(students) - - override suspend fun schedule( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> { - reloads += 1 - return Result.success(emptyList()) - } - - override suspend fun homework( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> = Result.success(emptyList()) - - override suspend fun grades( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> = Result.success(emptyList()) - - override suspend fun periods(studentId: Long): Result> = - Result.success(emptyList()) - - override suspend fun overrides(studentId: Long): Result> = - Result.success(emptyList()) - - override suspend fun correct( - studentId: Long, - target: String, - field: DiaryField, - value: String, - original: String?, - ): Result { - val outcome = answer(Unit) - if (outcome.isSuccess) corrections += Written(target, field, value, original) - return outcome - } - - override suspend fun reset( - studentId: Long, - target: String, - field: DiaryField, - ): Result { - val outcome = answer(Unit) - if (outcome.isSuccess) resets += target to field - return outcome - } - - override suspend fun resetAll(studentId: Long): Result = answer(Unit) - } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt index d11f2c7d..ed275647 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt @@ -1,20 +1,11 @@ package com.lumenpearson.lessons.ui.diary import com.lumenpearson.lessons.core.data.repository.DiaryFailure -import com.lumenpearson.lessons.core.data.repository.DiaryField -import com.lumenpearson.lessons.core.data.repository.DiaryOverrideRecord -import com.lumenpearson.lessons.core.data.repository.DiaryHomework -import com.lumenpearson.lessons.core.data.repository.DiaryLesson -import com.lumenpearson.lessons.core.data.repository.DiaryMark -import com.lumenpearson.lessons.core.data.repository.DiaryPeriod -import com.lumenpearson.lessons.core.data.repository.DiaryRepository import com.lumenpearson.lessons.core.data.repository.DiarySession -import com.lumenpearson.lessons.core.data.repository.DiaryStudent -import java.time.LocalDate +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -41,7 +32,12 @@ import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class DiarySignInOutcomeTest { - private val repository = FakeDiaryRepository() + // The reads all fail, on purpose: these tests are about the sign-in and + // nothing after it, and a students call that succeeded would pull the + // state holder into a load whose answers would have to be arranged too. + private val repository = FakeDiaryRepository().apply { + readFailure = DiaryFailure.Unavailable + } @Before fun setUp() { @@ -57,7 +53,7 @@ class DiarySignInOutcomeTest { @Test fun `a refused password is an outcome that names the reason`() { - repository.signInResult = Result.failure(DiaryFailure.SignInRequired) + repository.signInResult = Result.failure(DiarySignInProblem.WrongPassword(null)) val model = model() model.signIn("parent@example.com", "wrong") @@ -78,7 +74,7 @@ class DiarySignInOutcomeTest { // The whole point of carrying the failure rather than a boolean. These // two need different things from the person reading: one is a typo, the // other is waiting. - repository.signInResult = Result.failure(DiaryFailure.Unavailable) + repository.signInResult = Result.failure(DiarySignInProblem.ProviderUnavailable("dnevnik2.petersburgedu.ru")) val model = model() model.signIn("parent@example.com", "correct-horse") @@ -108,7 +104,7 @@ class DiarySignInOutcomeTest { @Test fun `the outcome is shown once and then gone`() { - repository.signInResult = Result.failure(DiaryFailure.SignInRequired) + repository.signInResult = Result.failure(DiarySignInProblem.WrongPassword(null)) val model = model() model.signIn("parent@example.com", "wrong") @@ -122,11 +118,11 @@ class DiarySignInOutcomeTest { @Test fun `a second attempt replaces the first outcome rather than queueing behind it`() { - repository.signInResult = Result.failure(DiaryFailure.Unavailable) + repository.signInResult = Result.failure(DiarySignInProblem.ProviderUnavailable(null)) val model = model() model.signIn("parent@example.com", "correct-horse") - repository.signInResult = Result.failure(DiaryFailure.SignInRequired) + repository.signInResult = Result.failure(DiarySignInProblem.WrongPassword(null)) model.signIn("parent@example.com", "wrong") assertEquals( @@ -134,75 +130,48 @@ class DiarySignInOutcomeTest { model.uiState.value.signInOutcome, ) } -} -/** - * A diary that answers `signIn` however the test says and nothing else. - * - * The reads all fail, on purpose: the tests here are about the sign-in and - * nothing after it, and a students call that succeeded would pull the state - * holder into a load whose answers would have to be arranged too. - */ -private class FakeDiaryRepository : DiaryRepository { + @Test + fun `with no diary known, the form signs in to Petersburg`() { + val model = model() - var signInResult: Result = Result.failure(DiaryFailure.Unavailable) + model.signIn(" parent@example.com ", "correct-horse") - private val sessions = MutableStateFlow(null) - override val session: Flow = sessions + assertEquals(listOf(DiaryTarget.petersburg("parent@example.com")), repository.signedInTo) + } - override suspend fun current(): DiarySession? = sessions.value + /** + * A bare `401` drops the bearer and keeps the target, so the form that + * follows must sign in to that diary — a «Сетевой город» family retyping + * their password must not be sent to Petersburg with it. + */ + @Test + fun `a sign-in after the session died goes to the diary that was kept`() { + val kept = DiaryTarget.netschool( + region = "samara", + schoolId = 1234, + schoolName = "Школа № 5", + login = "ivanova", + zone = "Europe/Samara", + ) + repository.targets.value = kept + val model = model() - override suspend fun signIn(login: String, password: String): Result = - signInResult.also { result -> result.getOrNull()?.let { sessions.value = it } } + model.signIn("ivanova", "correct-horse") - override suspend fun signOut(): Result { - sessions.value = null - return Result.success(Unit) + assertEquals(listOf(kept), repository.signedInTo) } - override suspend fun students(): Result> = - Result.failure(DiaryFailure.Unavailable) - - override suspend fun schedule( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> = Result.failure(DiaryFailure.Unavailable) - - override suspend fun homework( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> = Result.failure(DiaryFailure.Unavailable) - - // Corrections are not what this file is about — it pins how a sign-in - // reports itself — so these refuse like every other read here. - override suspend fun overrides(studentId: Long): Result> = - Result.failure(DiaryFailure.Unavailable) - - override suspend fun correct( - studentId: Long, - target: String, - field: DiaryField, - value: String, - original: String?, - ): Result = Result.failure(DiaryFailure.Unavailable) - - override suspend fun reset( - studentId: Long, - target: String, - field: DiaryField, - ): Result = Result.failure(DiaryFailure.Unavailable) - - override suspend fun resetAll(studentId: Long): Result = - Result.failure(DiaryFailure.Unavailable) - - override suspend fun grades( - studentId: Long, - from: LocalDate, - to: LocalDate, - ): Result> = Result.failure(DiaryFailure.Unavailable) - - override suspend fun periods(studentId: Long): Result> = - Result.failure(DiaryFailure.Unavailable) + @Test + fun `too many attempts is not reported as a wrong password`() { + repository.signInResult = Result.failure(DiarySignInProblem.TooManyAttempts(retryAfterSeconds = 60)) + val model = model() + + model.signIn("parent@example.com", "wrong") + + assertEquals( + DiarySignInOutcome.Failed(DiaryFailure.Throttled(retryAfterSeconds = 60)), + model.uiState.value.signInOutcome, + ) + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt new file mode 100644 index 00000000..cf8c2943 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt @@ -0,0 +1,156 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiaryField +import com.lumenpearson.lessons.core.data.repository.DiaryHomework +import com.lumenpearson.lessons.core.data.repository.DiaryLesson +import com.lumenpearson.lessons.core.data.repository.DiaryMark +import com.lumenpearson.lessons.core.data.repository.DiaryOverrideRecord +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryRepository +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow + +/** One correction as the fake was asked to store it. */ +internal data class Written( + val target: String, + val field: DiaryField, + val value: String, + val original: String?, +) + +/** + * The one fake diary every `:app` test uses. + * + * There were two, each private to its test file, and every change to + * [DiaryRepository]'s interface had to be made in both — the signature change + * this batch makes to how a sign-in reaches the server would have been two + * edits that could disagree. One file means one edit, and a new test picks the + * behaviour it needs from the knobs below rather than writing a third. + * + * @property readFailure when set, every read answers it: for tests about the + * sign-in and nothing after it, where a students call that succeeded would + * pull the state holder into a load whose answers would have to be arranged. + * @property failAfter the number of writes that succeed before [failure] is + * answered instead; `null` never fails a write. + */ +internal class FakeDiaryRepository : DiaryRepository { + + var students: List = emptyList() + var readFailure: DiaryFailure? = null + var failAfter: Int? = null + var failure: DiaryFailure = DiaryFailure.Unavailable + var reloads: Int = 0 + + /** What a sign-in answers; a success is also stored as the session. */ + var signInResult: Result? = null + + /** The diary each sign-in was asked for, in order. */ + val signedInTo = mutableListOf() + + /** What [target] reads while no session holds one — a bare `401`'s leftover. */ + val targets = MutableStateFlow(null) + + val corrections = mutableListOf() + val resets = mutableListOf>() + + val sessions = MutableStateFlow(null) + override val session: Flow = sessions + override val target: Flow = targets + + private var writes = 0 + + private fun read(value: T): Result = + readFailure?.let { Result.failure(it) } ?: Result.success(value) + + private fun answer(value: T): Result { + val limit = failAfter + val outcome = if (limit != null && writes >= limit) { + Result.failure(failure) + } else { + Result.success(value) + } + writes += 1 + return outcome + } + + override suspend fun current(): DiarySession? = sessions.value + + override suspend fun signIn(target: DiaryTarget, password: String): Result { + signedInTo += target + val result = signInResult + ?: Result.success(DiarySession(login = target.login, token = "t", target = target)) + result.getOrNull()?.let { + sessions.value = it + targets.value = it.target + } + return result + } + + override suspend fun signOut(): Result { + sessions.value = null + targets.value = null + return Result.success(Unit) + } + + override suspend fun students(): Result> = read(students) + + override suspend fun schedule( + studentId: Long, + from: LocalDate, + to: LocalDate, + ): Result> { + reloads += 1 + return read(emptyList()) + } + + override suspend fun homework( + studentId: Long, + from: LocalDate, + to: LocalDate, + ): Result> = read(emptyList()) + + override suspend fun grades( + studentId: Long, + from: LocalDate, + to: LocalDate, + ): Result> = read(emptyList()) + + override suspend fun periods(studentId: Long): Result> = read(emptyList()) + + override suspend fun overrides(studentId: Long): Result> = + read(emptyList()) + + override suspend fun correct( + studentId: Long, + target: String, + field: DiaryField, + value: String, + original: String?, + ): Result { + readFailure?.let { return Result.failure(it) } + val outcome = answer(Unit) + if (outcome.isSuccess) corrections += Written(target, field, value, original) + return outcome + } + + override suspend fun reset( + studentId: Long, + target: String, + field: DiaryField, + ): Result { + readFailure?.let { return Result.failure(it) } + val outcome = answer(Unit) + if (outcome.isSuccess) resets += target to field + return outcome + } + + override suspend fun resetAll(studentId: Long): Result { + readFailure?.let { return Result.failure(it) } + return answer(Unit) + } +} diff --git a/android/core/data/build.gradle.kts b/android/core/data/build.gradle.kts index b54de04a..49a74aae 100644 --- a/android/core/data/build.gradle.kts +++ b/android/core/data/build.gradle.kts @@ -53,6 +53,23 @@ android { // files from GitHub, and a bundled copy that had drifted from them // would show a reader a guide nobody wrote. getByName("main").assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/app")) + + // The region catalog, bundled as the server's generator wrote it — the + // same one file the server reads, never a copy, because the phone takes + // every host it will ever send a password to from this file and a + // second allow-list is a second answer to «may I talk to this host». + getByName("main").assets.srcDirs( + rootProject.layout.projectDirectory.dir("../server/app/catalog/data"), + ) + + // The known answers both sign-in implementations are held to, read in + // place from the server's tests so there is one file and not two that + // agree until somebody edits one. The catalog rides along so a JVM test + // can load it from the classpath the way the app loads it from assets. + getByName("test").resources.srcDirs( + rootProject.layout.projectDirectory.dir("../server/tests/vectors"), + rootProject.layout.projectDirectory.dir("../server/app/catalog/data"), + ) } } @@ -100,4 +117,8 @@ dependencies { testImplementation(libs.junit) testImplementation(libs.kotlinx.coroutines.test) + // A real socket for the provider sign-ins: the ports are held to what an + // HTTP exchange actually carries (form bodies, cookies, redirects not + // followed), which a scripted interceptor would only restate. + testImplementation(libs.okhttp.mockwebserver3) } diff --git a/android/core/data/schemas/com.lumenpearson.lessons.core.data.diary.DiaryDatabase/1.json b/android/core/data/schemas/com.lumenpearson.lessons.core.data.diary.DiaryDatabase/1.json new file mode 100644 index 00000000..ba11a8a8 --- /dev/null +++ b/android/core/data/schemas/com.lumenpearson.lessons.core.data.diary.DiaryDatabase/1.json @@ -0,0 +1,463 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "7948aaa70e120264b8b5ae0b83f92781", + "entities": [ + { + "tableName": "diary_student", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `first_name` TEXT NOT NULL, `last_name` TEXT NOT NULL, `middle_name` TEXT, `full_name` TEXT NOT NULL, `school` TEXT, `class_name` TEXT, `position` INTEGER NOT NULL, `synced_at` INTEGER NOT NULL, `periods_synced_at` INTEGER, `marks_from` INTEGER, `marks_to` INTEGER, `marks_synced_at` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "firstName", + "columnName": "first_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastName", + "columnName": "last_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "middleName", + "columnName": "middle_name", + "affinity": "TEXT" + }, + { + "fieldPath": "fullName", + "columnName": "full_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "school", + "columnName": "school", + "affinity": "TEXT" + }, + { + "fieldPath": "className", + "columnName": "class_name", + "affinity": "TEXT" + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncedAt", + "columnName": "synced_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "periodsSyncedAt", + "columnName": "periods_synced_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "marksFrom", + "columnName": "marks_from", + "affinity": "INTEGER" + }, + { + "fieldPath": "marksTo", + "columnName": "marks_to", + "affinity": "INTEGER" + }, + { + "fieldPath": "marksSyncedAt", + "columnName": "marks_synced_at", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "diary_week", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`student_id` INTEGER NOT NULL, `monday` INTEGER NOT NULL, `lessons_synced_at` INTEGER, `homework_synced_at` INTEGER, PRIMARY KEY(`student_id`, `monday`))", + "fields": [ + { + "fieldPath": "studentId", + "columnName": "student_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "monday", + "columnName": "monday", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lessonsSyncedAt", + "columnName": "lessons_synced_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "homeworkSyncedAt", + "columnName": "homework_synced_at", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "student_id", + "monday" + ] + } + }, + { + "tableName": "diary_period", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`student_id` INTEGER NOT NULL, `id` INTEGER NOT NULL, `name` TEXT NOT NULL, `starts_on` INTEGER, `ends_on` INTEGER, `is_current` INTEGER NOT NULL, `position` INTEGER NOT NULL, PRIMARY KEY(`student_id`, `id`))", + "fields": [ + { + "fieldPath": "studentId", + "columnName": "student_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "startsOn", + "columnName": "starts_on", + "affinity": "INTEGER" + }, + { + "fieldPath": "endsOn", + "columnName": "ends_on", + "affinity": "INTEGER" + }, + { + "fieldPath": "isCurrent", + "columnName": "is_current", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "student_id", + "id" + ] + } + }, + { + "tableName": "diary_lesson", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`row_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `student_id` INTEGER NOT NULL, `date` INTEGER NOT NULL, `number` INTEGER, `subject` TEXT NOT NULL, `starts_at` INTEGER, `ends_at` INTEGER, `room` TEXT, `teacher` TEXT, `homework` TEXT, `topic` TEXT, `target` TEXT NOT NULL, `edits` TEXT NOT NULL, `ambiguous` INTEGER NOT NULL, `position` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "rowId", + "columnName": "row_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "studentId", + "columnName": "student_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "number", + "columnName": "number", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "startsAt", + "columnName": "starts_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "endsAt", + "columnName": "ends_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "room", + "columnName": "room", + "affinity": "TEXT" + }, + { + "fieldPath": "teacher", + "columnName": "teacher", + "affinity": "TEXT" + }, + { + "fieldPath": "homework", + "columnName": "homework", + "affinity": "TEXT" + }, + { + "fieldPath": "topic", + "columnName": "topic", + "affinity": "TEXT" + }, + { + "fieldPath": "target", + "columnName": "target", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "edits", + "columnName": "edits", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ambiguous", + "columnName": "ambiguous", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "row_id" + ] + }, + "indices": [ + { + "name": "index_diary_lesson_student_id_date", + "unique": false, + "columnNames": [ + "student_id", + "date" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_diary_lesson_student_id_date` ON `${TABLE_NAME}` (`student_id`, `date`)" + } + ] + }, + { + "tableName": "diary_homework", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`row_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `student_id` INTEGER NOT NULL, `due_date` INTEGER NOT NULL, `upstream_id` INTEGER, `subject` TEXT NOT NULL, `text` TEXT NOT NULL, `teacher` TEXT, `target` TEXT NOT NULL, `edits` TEXT NOT NULL, `ambiguous` INTEGER NOT NULL, `position` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "rowId", + "columnName": "row_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "studentId", + "columnName": "student_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dueDate", + "columnName": "due_date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "upstreamId", + "columnName": "upstream_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "teacher", + "columnName": "teacher", + "affinity": "TEXT" + }, + { + "fieldPath": "target", + "columnName": "target", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "edits", + "columnName": "edits", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ambiguous", + "columnName": "ambiguous", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "row_id" + ] + }, + "indices": [ + { + "name": "index_diary_homework_student_id_due_date", + "unique": false, + "columnNames": [ + "student_id", + "due_date" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_diary_homework_student_id_due_date` ON `${TABLE_NAME}` (`student_id`, `due_date`)" + } + ] + }, + { + "tableName": "diary_mark", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`row_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `student_id` INTEGER NOT NULL, `upstream_id` INTEGER, `subject_id` INTEGER, `subject` TEXT NOT NULL, `date` INTEGER, `value` TEXT NOT NULL, `kind` TEXT NOT NULL, `reason` TEXT, `comment` TEXT, `position` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "rowId", + "columnName": "row_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "studentId", + "columnName": "student_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "upstreamId", + "columnName": "upstream_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "subjectId", + "columnName": "subject_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER" + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "reason", + "columnName": "reason", + "affinity": "TEXT" + }, + { + "fieldPath": "comment", + "columnName": "comment", + "affinity": "TEXT" + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "row_id" + ] + }, + "indices": [ + { + "name": "index_diary_mark_student_id", + "unique": false, + "columnNames": [ + "student_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_diary_mark_student_id` ON `${TABLE_NAME}` (`student_id`)" + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7948aaa70e120264b8b5ae0b83f92781')" + ] + } +} \ No newline at end of file diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt new file mode 100644 index 00000000..07812912 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt @@ -0,0 +1,186 @@ +package com.lumenpearson.lessons.core.data.catalog + +import android.content.Context +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * The region catalog the server's generator writes, as the phone reads it. + * + * `server/app/catalog/data/regions.json` is bundled as an asset exactly as it + * is committed (`core/data/build.gradle.kts`): generated from the survey by + * `server/scripts/region_catalog.py`, never copied and never edited by hand. It + * is the only place the phone learns which diaries exist, which region runs + * which, and — through [CatalogNetSchool.origin] and [CatalogPlatform.origin] — + * every host it will ever send a password to. `UpstreamDirectory` draws its + * allow-list from here and nowhere else. + * + * The model is a plain reading of the file, field for field, so that what reads + * it next (the region search, the provider picker) sees the generator's answers + * — `recommended`, `action`, `role` — rather than a second derivation of them. + * Unknown keys are ignored, so a newer generator does not break an older app. + * + * Region and platform names live here and not in string resources, in both + * languages ([CatalogRegion.nameRu], [CatalogRegion.nameEn]); the generator's + * test holds the English twin the way `ResourceTranslationTest` holds a + * resource's. + */ +@Serializable +data class RegionCatalog( + @SerialName("schema") val schema: Int = 0, + @SerialName("survey") val survey: CatalogSurvey = CatalogSurvey(), + @SerialName("regions") val regions: List = emptyList(), + @SerialName("platforms") val platforms: Map = emptyMap(), + @SerialName("search") val search: CatalogSearch = CatalogSearch(), +) { + + /** The region stored under [key], or `null` for one the catalog does not know. */ + fun region(key: String?): CatalogRegion? = key?.let { wanted -> regions.firstOrNull { it.key == wanted } } + + companion object { + /** The asset's name: the file sits at the asset root, beside the guide's. */ + const val ASSET = "regions.json" + + private val json = Json { + ignoreUnknownKeys = true + coerceInputValues = true + explicitNulls = false + } + + /** Reads a catalog from its JSON text. Throws on a file that is not one. */ + fun parse(text: String): RegionCatalog = json.decodeFromString(serializer(), text) + + /** + * Reads the bundled catalog. A few hundred kilobytes of JSON: call it off + * the main thread, once, and keep the answer. + */ + fun load(context: Context): RegionCatalog = + context.assets.open(ASSET).bufferedReader(Charsets.UTF_8).use { parse(it.readText()) } + } +} + +/** When the survey behind the catalog was taken, for a screen that says how fresh it is. */ +@Serializable +data class CatalogSurvey( + @SerialName("month") val month: String? = null, + @SerialName("school_year") val schoolYear: String? = null, +) + +/** + * One of the 89 regions. + * + * @property key the catalog key, which is also the server's allow-list key for a + * «Сетевой город» region and what the directory endpoint answers with. + * @property code the two-digit subject code. + * @property zone the region's administrative centre's zone. + * @property order the constitution's order (Art. 65), which is the list's. + */ +@Serializable +data class CatalogRegion( + @SerialName("key") val key: String, + @SerialName("code") val code: String = "", + @SerialName("iso") val iso: String? = null, + @SerialName("name_ru") val nameRu: String = "", + @SerialName("name_en") val nameEn: String = "", + @SerialName("aliases") val aliases: List = emptyList(), + @SerialName("cities") val cities: List = emptyList(), + @SerialName("dadata_names") val dadataNames: List = emptyList(), + @SerialName("zone") val zone: String = "", + @SerialName("order") val order: Int = 0, + @SerialName("mandatory") val mandatory: Boolean = false, + @SerialName("tor") val tor: String? = null, + @SerialName("recommended") val recommended: CatalogRecommendation? = null, + @SerialName("systems") val systems: List = emptyList(), +) + +/** + * The generator's recommendation for a region, read and never re-derived. + * + * @property system an index into [CatalogRegion.systems]. + * @property reason one of the generator's reason codes — `primary`, + * `tor_primary`, `front_end`, `moving_to`, `unreachable`, `unsupported`, + * `no_diary` — which the screens key their «почему» text by. + * @property modifiers `unverified`, `esia_only`. + */ +@Serializable +data class CatalogRecommendation( + @SerialName("platform") val platform: String? = null, + @SerialName("system") val system: Int? = null, + @SerialName("reason") val reason: String? = null, + @SerialName("modifiers") val modifiers: List = emptyList(), + @SerialName("confidence") val confidence: String? = null, +) + +/** + * One diary system a region runs. + * + * @property action `signin` (the app's own form can sign in here), `handoff` + * (open [handoffUrl] in the browser and nothing comes back) or `none`. + * @property role `primary`, `secondary`, `legacy`, `migrating_to`, `unclear`. + * @property netschool set only on a «Сетевой город» system this server's + * allow-list knows; the one source of such a host. + */ +@Serializable +data class CatalogSystem( + @SerialName("platform") val platform: String, + @SerialName("role") val role: String? = null, + @SerialName("action") val action: String = "none", + @SerialName("confidence") val confidence: String? = null, + @SerialName("front_end") val frontEnd: Boolean = false, + @SerialName("excluded") val excluded: String? = null, + @SerialName("hosts") val hosts: List = emptyList(), + @SerialName("web_url") val webUrl: String? = null, + @SerialName("handoff_url") val handoffUrl: String? = null, + @SerialName("netschool") val netschool: CatalogNetSchool? = null, +) + +/** + * A «Сетевой город» row of the server's allow-list, as the generator copied it + * from `providers/netschool/regions.py`. + * + * @property password `false` where the region lets people in through Госуслуги + * only; the phone sends such a region nothing. + */ +@Serializable +data class CatalogNetSchool( + @SerialName("region") val region: String, + @SerialName("origin") val origin: String, + @SerialName("password") val password: Boolean = false, + @SerialName("verified") val verified: Boolean = false, + @SerialName("zone") val zone: String = "", +) + +/** + * One diary platform, whichever regions run it. + * + * @property provider `petersburg` or `netschool` where this app can talk to the + * platform at all; `null` otherwise. + * @property origin set only where the platform is one server (Petersburg). + */ +@Serializable +data class CatalogPlatform( + @SerialName("name_ru") val nameRu: String = "", + @SerialName("name_en") val nameEn: String = "", + @SerialName("kind") val kind: String? = null, + @SerialName("origin") val origin: String? = null, + @SerialName("provider") val provider: String? = null, + @SerialName("signin") val signin: String? = null, + @SerialName("page") val page: String? = null, + @SerialName("handoff") val handoff: String? = null, +) + +/** + * The words the region search folds, drops and transliterates — carried in the + * catalog so the phone's search and the server's directory mean one thing by + * «too common to look up». + */ +@Serializable +data class CatalogSearch( + @SerialName("cyrillic_layout") val cyrillicLayout: String = "", + @SerialName("latin_layout") val latinLayout: String = "", + @SerialName("fold") val fold: Map = emptyMap(), + @SerialName("school_words") val schoolWords: List = emptyList(), + @SerialName("stop_words") val stopWords: List = emptyList(), + @SerialName("translit") val translit: List> = emptyList(), +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionLookup.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionLookup.kt new file mode 100644 index 00000000..a10d95f1 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionLookup.kt @@ -0,0 +1,76 @@ +package com.lumenpearson.lessons.core.data.catalog + +/** + * The region step's one question — «which region do you mean» — answered from + * both places that know: the bundled catalog, for a region's own name, alias, + * city or code, and the server's directory, for the name of a school. + * + * The directory is asked only when the query [RegionSearch.looksLikeSchool] and + * is not [generic][RegionSearch.isGenericSchool]: a region's name costs no + * request and a generic school name places nothing, and every directory call + * is counted against this phone and spent from an allowance the bot needs too. + * The screen debounces ([SchoolDirectory.DEBOUNCE_MILLIS]); this runs one + * lookup per call. + */ +class RegionLookup internal constructor( + private val search: suspend () -> RegionSearch, + private val directory: SchoolDirectory, +) { + + /** The bundled catalog, for the screens that list regions and their diaries. */ + suspend fun catalog(): RegionCatalog = search().catalog + + /** The catalog alone, with no request: for filtering the list as somebody types. */ + suspend fun byName(query: String): List = search().search(query) + + /** Both, combined; see [RegionLookupResult]. */ + suspend fun find(query: String): RegionLookupResult { + val search = search() + val byName = search.search(query) + val bySchool = when { + query.isBlank() || !search.looksLikeSchool(query) -> SchoolLookup.NotAsked + search.isGenericSchool(query) -> SchoolLookup.Generic + else -> directory.regionsForSchool(query).fold( + onSuccess = { hits -> if (hits.generic) SchoolLookup.Generic else SchoolLookup.Found(hits) }, + onFailure = { failure -> SchoolLookup.Failed(DirectoryProblem.of(failure)) }, + ) + } + return RegionLookupResult(query = query, byName = byName, bySchool = bySchool) + } +} + +/** What the directory said about a school name, if it was asked. */ +sealed interface SchoolLookup { + /** The query is a place, not a school; nothing was asked. */ + data object NotAsked : SchoolLookup + + /** Too common to place — «школа № 5» is in every region. «Выберите регион». */ + data object Generic : SchoolLookup + + data class Found(val hits: SchoolRegionHits) : SchoolLookup + + /** Every failure means «выберите регион из списка»; the problem says whether waiting helps. */ + data class Failed(val problem: DirectoryProblem) : SchoolLookup +} + +/** + * @property byName the catalog's own matches, best first. + * @property bySchool the directory's answer about a school of that name. + */ +data class RegionLookupResult( + val query: String, + val byName: List, + val bySchool: SchoolLookup, +) { + /** + * The regions to offer, once each: where the directory placed the school + * first, in its order, then the catalog's own matches. A region the + * directory named but the catalog cannot place is not here — it cannot be + * picked — and is in [bySchool] for the screen to mention. + */ + val suggested: List + get() { + val placed = (bySchool as? SchoolLookup.Found)?.hits?.hits.orEmpty().mapNotNull { it.region } + return (placed + byName.map { it.region }).distinctBy { it.key } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt new file mode 100644 index 00000000..bf71604c --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt @@ -0,0 +1,245 @@ +package com.lumenpearson.lessons.core.data.catalog + +import java.util.Locale + +/** + * Finding one of the 89 regions from what somebody types — «самара», + * «Samara», «cfvfhf» typed on the wrong layout, «moskva», «ХМАО», «Тольятти», + * «47» — without a request. + * + * Every word it treats specially comes from the catalog's `search` block + * ([CatalogSearch]): the fold map, the region type words it ignores, the two + * keyboard layouts, the transliteration table and the words a school's name is + * made of. The server's directory reads the same block (`catalog.school_words`), + * so «a name too common to look up» means one thing on both sides, and no + * Russian word is written into this file. + * + * Ranking, best first — ties go to the constitution's order, which is the + * list's: + * + * 0. the region's name, exactly; + * 1. every word typed is a whole word of the name; + * 2. every word typed starts a word of the name («моск»); + * 3. an alias («Питер», «ХМАО»), exactly or by its start; + * 4. a city in the region («Тольятти»), exactly or by its start; + * 5. the two-digit subject code («47», «78»); + * 6. anywhere inside a name, alias or city (three characters or more). + * + * An ambiguous query answers every region it fits: «Алтай» is both Altai + * regions, and choosing between them is the person's. + */ +class RegionSearch(val catalog: RegionCatalog) { + + private val lexicon = catalog.search + + private val fold: Map = lexicon.fold.entries + .filter { it.key.length == 1 } + .associate { it.key[0] to it.value } + + private val stopWords: Set = lexicon.stopWords.flatMap { normaliseTokens(it, drop = emptySet()) }.toSet() + + private val schoolWords: Set = lexicon.schoolWords.map { foldCase(it) }.toSet() + + private val latinToCyrillic: Map = layoutMap(lexicon.latinLayout, lexicon.cyrillicLayout) + private val cyrillicToLatin: Map = layoutMap(lexicon.cyrillicLayout, lexicon.latinLayout) + + /** Latin sequences, longest first, as the table lists them. */ + private val translit: List> = lexicon.translit + .filter { it.size == 2 && it[0].isNotEmpty() } + .map { it[0] to it[1] } + + private val index: List = catalog.regions.map { region -> + Entry( + region = region, + names = listOf(region.nameRu, region.nameEn).filter { it.isNotBlank() }.map { normalise(it) }, + aliases = region.aliases.map { normalise(it) }, + cities = region.cities.map { normalise(it) }, + code = region.code.toIntOrNull(), + ) + } + + private class Entry( + val region: CatalogRegion, + val names: List>, + val aliases: List>, + val cities: List>, + val code: Int?, + ) + + /** + * The regions [query] may mean, best first. A blank query is every region + * in the list's order, so a screen can show the whole list and narrow it + * as the person types. + */ + fun search(query: String): List { + if (query.isBlank()) { + return catalog.regions.sortedBy { it.order }.map { RegionMatch(it, MatchVia.LIST, "", LIST_SCORE) } + } + val candidates = candidates(query).map { normalise(it) }.filter { it.isNotEmpty() }.distinct() + val digits = query.trim().takeIf { it.length in 1..3 && it.all(Char::isDigit) }?.toIntOrNull() + return index.mapNotNull { entry -> + val scored = candidates.mapNotNull { score(entry, it) } + val byCode = if (digits != null && digits == entry.code) { + RegionMatch(entry.region, MatchVia.CODE, entry.region.code, CODE_SCORE) + } else { + null + } + (scored + listOfNotNull(byCode)).minByOrNull { it.score } + }.sortedWith(compareBy { it.score }.thenBy { it.region.order }) + } + + /** + * Whether [query] looks like a school's name rather than a place — the + * question of whether to ask the server's directory at all. It does when it + * carries a word schools are named with («лицей», «гимназия», «№»), or a + * number beside a word («1 казань»), or a number too long to be a subject + * code. + */ + fun looksLikeSchool(query: String): Boolean { + val tokens = schoolTokens(query) + if (tokens.any { it in schoolWords }) return true + val numbers = tokens.filter { token -> token.all(Char::isDigit) } + if (numbers.any { it.length > 3 }) return true + return numbers.isNotEmpty() && tokens.any { token -> token.none(Char::isDigit) } + } + + /** + * The server's `services/schools.is_generic`, token for token: with the + * words a school's name is made of taken away, is anything left that tells + * schools apart — a town, a name, a number of three digits or more? If not + * («школа № 5», «СОШ 12», «гимназия 3»), the name is in every region and + * asking the directory would spend a request to place nothing. + */ + fun isGenericSchool(query: String): Boolean = + schoolTokens(query) + .filterNot { it in schoolWords } + .all { token -> token.all(Char::isDigit) && token.length <= 2 } + + /** + * What else [query] could have been typed as: itself; the same keys on the + * other layout, both ways (a Russian word typed on an English keyboard); + * and a Latin query spelt out in Cyrillic («moskva»). + */ + internal fun candidates(query: String): List { + val lower = query.lowercase(Locale.ROOT) + val swappedToCyrillic = lower.map { latinToCyrillic[it] ?: it }.joinToString("") + val swappedToLatin = lower.map { cyrillicToLatin[it] ?: it }.joinToString("") + val latin = lower.any { it in 'a'..'z' } + return listOfNotNull( + lower, + swappedToCyrillic.takeIf { it != lower }, + swappedToLatin.takeIf { it != lower }, + transliterate(lower).takeIf { latin }, + ).distinct() + } + + /** + * The words of [text] as the search compares them: lower case, folded + * («ё» as «е», every dash a space), punctuation dropped, and the region + * type words («область», «край», «республика») left out — nobody picks + * a region by the word «область». + */ + internal fun normalise(text: String): List = normaliseTokens(text, stopWords) + + private fun normaliseTokens(text: String, drop: Set): List { + val folded = buildString { + for (char in text.lowercase(Locale.ROOT)) { + val mapped = fold[char] ?: char.toString() + for (c in mapped) append(if (c.isLetterOrDigit()) c else ' ') + } + } + return folded.split(' ').filter { it.isNotEmpty() && it !in drop } + } + + private fun score(entry: Entry, words: List): RegionMatch? { + val joined = words.joinToString(" ") + entry.names.forEach { name -> + if (name == words) return RegionMatch(entry.region, MatchVia.NAME, joined, 0) + } + entry.names.forEach { name -> + if (words.all { it in name }) return RegionMatch(entry.region, MatchVia.NAME, joined, 1) + } + entry.names.forEach { name -> + if (startsWords(name, words)) return RegionMatch(entry.region, MatchVia.NAME, joined, 2) + } + entry.aliases.forEach { alias -> + if (alias == words || startsWords(alias, words)) { + return RegionMatch(entry.region, MatchVia.ALIAS, alias.joinToString(" "), 3) + } + } + entry.cities.forEach { city -> + if (city == words || startsWords(city, words)) { + return RegionMatch(entry.region, MatchVia.CITY, city.joinToString(" "), 4) + } + } + if (joined.length >= SUBSTRING_MIN) { + val inside = (entry.names + entry.aliases + entry.cities) + .firstOrNull { joined in it.joinToString(" ") } + if (inside != null) return RegionMatch(entry.region, MatchVia.SUBSTRING, inside.joinToString(" "), 6) + } + return null + } + + /** Every word typed starts some word of [target]. */ + private fun startsWords(target: List, words: List): Boolean = + words.isNotEmpty() && words.all { word -> target.any { it.startsWith(word) } } + + private fun transliterate(text: String): String = buildString { + var at = 0 + while (at < text.length) { + val hit = translit.firstOrNull { (latin, _) -> text.startsWith(latin, at) } + if (hit == null) { + append(text[at]) + at += 1 + } else { + append(hit.second) + at += hit.first.length + } + } + } + + /** + * The server's tokens for a school's name (`services/schools._TOKENS`): the + * numero sign alone, a run of digits, or a run of letters, after folding + * case and «ё». + */ + private fun schoolTokens(query: String): List = + SCHOOL_TOKEN.findAll(foldCase(query)).map { it.value }.toList() + + /** Lower case and the letter folds only («ё» as «е»), as the server's `_fold`. */ + private fun foldCase(text: String): String = buildString { + for (char in text.lowercase(Locale.ROOT)) { + append(if (char.isLetter()) fold[char] ?: char.toString() else char.toString()) + } + } + + private fun layoutMap(from: String, to: String): Map = + if (from.length != to.length) emptyMap() else from.indices.associate { from[it] to to[it] } + + private companion object { + const val CODE_SCORE = 5 + const val LIST_SCORE = 7 + const val SUBSTRING_MIN = 3 + + /** `№|\d+|[^\W\d_]+`, in Java's spelling; the numero sign is U+2116. */ + val SCHOOL_TOKEN = Regex("№|\\p{Nd}+|[\\p{L}\\p{M}]+") + } +} + +/** How a region was found; see [RegionSearch]. */ +enum class MatchVia { NAME, ALIAS, CITY, CODE, SUBSTRING, LIST } + +/** + * One region a query may mean. + * + * @property matched the normalised words it was found by — a city's name when + * [via] is [MatchVia.CITY], so a screen can say «Тольятти — Самарская + * область». + * @property score lower is better; see [RegionSearch]. + */ +data class RegionMatch( + val region: CatalogRegion, + val via: MatchVia, + val matched: String, + val score: Int, +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectory.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectory.kt new file mode 100644 index 00000000..168c88fb --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectory.kt @@ -0,0 +1,218 @@ +package com.lumenpearson.lessons.core.data.catalog + +import com.lumenpearson.lessons.core.data.network.DirectoryApi +import com.lumenpearson.lessons.core.data.network.SchoolRegionsDto +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import java.io.IOException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import retrofit2.HttpException + +/** + * Finding a school, in the two places a school can be looked up. + * + * * [regionsForSchool] asks our server's directory which regions a school of + * that name is in — for somebody who knows their school and not what their + * region is called in a list. Anonymous; a convenience only, because + * picking the region from the list always works, and every failure says so. + * * [providerSchools] asks a «Сетевой город» region's own server for its + * schools, phone to region directly — [DiarySchoolSearch]. + */ +interface SchoolDirectory { + + /** + * The regions a school called [query] may be in, best first. + * + * Asks nothing when the query is under [MIN_QUERY_LENGTH] characters + * ([DirectoryProblem.TooShort]) or is a name too common to place + * ([SchoolRegionHits.generic] with no hits) — the second saves the + * server's allowance and the caller's own twenty searches a quarter-hour. + * Every failure is a [DirectoryProblem]. + */ + suspend fun regionsForSchool(query: String): Result + + /** A region's own school list; see [DiarySchoolSearch.search]. */ + suspend fun providerSchools(regionKey: String, query: String): Result> + + companion object { + /** The server's `MIN_QUERY`: below it the directory ranks on too little. */ + const val MIN_QUERY_LENGTH = 3 + + /** + * How long typing has to pause before the phone asks (r04 §2.2): every + * call is counted against the caller and spent from a shared allowance, + * so never per keystroke. + */ + const val DEBOUNCE_MILLIS = 600L + } +} + +/** + * What the directory answered. + * + * @property truncated the directory's twenty-row ceiling was reached, so these + * are the regions of the first twenty matches. + * @property generic the name is in too many regions to place; the screen says + * «выберите регион» rather than guessing. + */ +data class SchoolRegionHits( + val query: String, + val hits: List, + val truncated: Boolean, + val generic: Boolean, +) + +/** + * One region the directory placed schools in. + * + * @property region the bundled catalog's row, or `null` when neither the + * server's catalog nor this phone's could place it — then [label] is the + * directory's own name for it, and it cannot be picked (no diary can be + * offered for a region the catalog does not know). + */ +data class SchoolRegionHit( + val region: CatalogRegion?, + val code: String?, + val label: String?, + val schools: Int, + val cities: List, + val examples: List, +) + +/** + * Why the directory did not answer. Every case ends the same way on screen — + * «выберите регион из списка» — and differs only in whether waiting helps. + */ +sealed class DirectoryProblem(message: String, cause: Throwable? = null) : Exception(message, cause) { + + /** Under [SchoolDirectory.MIN_QUERY_LENGTH]; nothing was asked. */ + data object TooShort : DirectoryProblem("The query is too short to search with") + + /** `X-Directory-Unavailable: disabled`: this server has no directory key. */ + data object Disabled : DirectoryProblem("The school directory is not configured on this server") + + /** `spent`: today's anonymous allowance is gone; [retryAfterSeconds] is until it resets. */ + data class Spent(val retryAfterSeconds: Long?) : + DirectoryProblem("The school directory's daily allowance is spent") + + /** `upstream`, or a bare `503`: the directory itself failed. */ + data object Upstream : DirectoryProblem("The school directory is not answering") + + /** `429`: this caller's twenty searches a quarter-hour are used. */ + data class Throttled(val retryAfterSeconds: Long?) : DirectoryProblem("Too many school searches") + + /** `404`: a server from before the directory. */ + data object ServerTooOld : DirectoryProblem("The server has no school directory") + + /** No server address is set. */ + data object ServerMissing : DirectoryProblem("No server address is set") + + /** No answer at all. */ + data object Offline : DirectoryProblem("Could not reach the server") + + /** Anything else, kept with its cause for a bug report. */ + class Unexpected(val detail: String?, cause: Throwable? = null) : + DirectoryProblem("Unexpected directory failure: ${detail ?: "unknown"}", cause) + + companion object { + + /** Classifies whatever a directory call threw; never a cancellation. */ + fun of(failure: Throwable): DirectoryProblem = when (failure) { + is CancellationException -> throw failure + is DirectoryProblem -> failure + is HttpException -> ofHttp(failure) + is IOException -> + if (generateSequence(failure) { it.cause }.take(8).any { it is ServerAddressMissingException }) { + ServerMissing + } else { + Offline + } + else -> Unexpected(failure::class.simpleName, failure) + } + + private fun ofHttp(failure: HttpException): DirectoryProblem = when (failure.code()) { + 404 -> ServerTooOld + // The server's length rule, met here only by a phone whose own + // check disagreed with it. + 422 -> TooShort + 429 -> Throttled(DiaryFailure.retryAfterSeconds(failure)) + // The header, not the Russian `detail`, says which 503 this is. + 503 -> when ( + failure.response()?.headers()?.get(DirectoryApi.UNAVAILABLE_HEADER)?.trim()?.lowercase() + ) { + "disabled" -> Disabled + "spent" -> Spent(DiaryFailure.retryAfterSeconds(failure)) + else -> Upstream + } + // The platform's own ceiling; the directory was slow, not wrong. + 504 -> Upstream + else -> Unexpected("HTTP ${failure.code()}", failure) + } + } +} + +/** + * [SchoolDirectory] over our server's directory and the regions' own servers. + * + * @param search the search over the bundled catalog, built on first use off + * the main thread: its generic-name rule is the server's, from the same file. + */ +internal class ServerSchoolDirectory( + private val api: DirectoryApi, + private val search: suspend () -> RegionSearch, + private val schools: DiarySchoolSearch, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, +) : SchoolDirectory { + + override suspend fun regionsForSchool(query: String): Result = withContext(ioDispatcher) { + // As the server normalises: whitespace collapsed, then counted. + val asked = query.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString(" ") + if (asked.codePointCount(0, asked.length) < SchoolDirectory.MIN_QUERY_LENGTH) { + return@withContext Result.failure(DirectoryProblem.TooShort) + } + try { + val search = search() + if (search.isGenericSchool(asked)) { + return@withContext Result.success( + SchoolRegionHits(query = asked, hits = emptyList(), truncated = false, generic = true), + ) + } + Result.success(api.schoolRegions(asked).toHits(search.catalog)) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + Result.failure(DirectoryProblem.of(failure)) + } + } + + override suspend fun providerSchools(regionKey: String, query: String): Result> = + schools.search(regionKey, query) +} + +/** + * The server's answer, placed against the bundled catalog. A key this build's + * catalog does not know — a region the server's newer catalog added — is kept + * as unplaced, with the code as its label when the directory gave no other, + * rather than dropped: the person still learns where the school is. + */ +internal fun SchoolRegionsDto.toHits(catalog: RegionCatalog): SchoolRegionHits = SchoolRegionHits( + query = query, + hits = regions.map { row -> + val region = catalog.region(row.region) + SchoolRegionHit( + region = region, + code = row.code ?: region?.code, + label = if (region == null) row.label ?: row.region else null, + schools = row.schools, + cities = row.cities, + examples = row.examples, + ) + }, + truncated = truncated, + generic = generic, +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt index c1c8da8d..a309be39 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/LessonsPreferences.kt @@ -10,13 +10,22 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.floatPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.lumenpearson.lessons.core.data.repository.AppSettings import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiarySessionStore +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.DiaryTargetCodec import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.data.repository.SyncArming +import com.lumenpearson.lessons.core.data.repository.shellModeOf +import com.lumenpearson.lessons.core.data.repository.syncArmingFor import com.lumenpearson.lessons.core.model.AlertPreferences import com.lumenpearson.lessons.core.model.AppFont import com.lumenpearson.lessons.core.model.AppLanguage @@ -61,7 +70,7 @@ private val Context.lessonsDataStore: DataStore by preferencesDataS * screens, they are both tiny, and a single file means a single fsync and a * single flow to observe. */ -internal class LessonsPreferences(context: Context) : DiarySessionStore { +internal class LessonsPreferences(context: Context) : DiarySessionStore, ShellModeSource { private val dataStore = context.applicationContext.lessonsDataStore @@ -153,7 +162,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore { * * The diary keys are not in here on purpose. Leaving a class is not leaving * the diary: they are two accounts, and the one being signed out of is the - * one the user pressed a button about. [clearDiarySession] is the other + * one the user pressed a button about. [forgetDiary] is the other * half, and it is just as narrow. */ suspend fun clearSession() { @@ -196,18 +205,64 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore { preferences.first().toDiarySession() override suspend fun writeDiarySession(value: DiarySession) { + dataStore.edit { it.putDiarySession(value) } + } + + /** A bare `401`; see [dropDiaryToken]. */ + override suspend fun clearDiaryToken() { + dataStore.edit { it.dropDiaryToken() } + } + + /** Signing out: the diary and only the diary; [clearSession] is its counterpart. */ + override suspend fun forgetDiary() { + dataStore.edit { it.dropDiary() } + } + + override val diaryTarget: Flow = + preferences.map { it.toDiaryTarget() }.distinctUntilChanged() + + override suspend fun currentDiaryTarget(): DiaryTarget? = preferences.first().toDiaryTarget() + + override val selectedStudentId: Flow = + preferences.map { it[DiaryKeys.STUDENT_ID] }.distinctUntilChanged() + + override suspend fun selectStudent(id: Long?) { dataStore.edit { prefs -> - prefs[KEY_DIARY_TOKEN] = value.token - prefs[KEY_DIARY_LOGIN] = value.login + if (id == null) prefs.remove(DiaryKeys.STUDENT_ID) else prefs[DiaryKeys.STUDENT_ID] = id } } - /** Clears the diary and only the diary; [clearSession] is its counterpart. */ - override suspend fun clearDiarySession() { + // --------------------------------------------------------------------- + // Which home the app opens on + // --------------------------------------------------------------------- + // + // Every value below is read from one emission of the file: the class and + // the diary are both in it, so the mode never has to be assembled from two + // flows that can be caught between a write and its echo. + + override val state: Flow = preferences.map { it.shellState() }.distinctUntilChanged() + + override suspend fun current(): ShellState = preferences.first().shellState() + + override val syncArming: Flow = preferences + .map { prefs -> syncArmingFor(prefs.shellState().mode, prefs.toSettings().syncIntervalMinutes) } + .distinctUntilChanged() + + override suspend fun hold() { + dataStore.edit { it[ShellKeys.ONBOARDING_HELD] = true } + } + + override suspend fun release() { + dataStore.edit { it.remove(ShellKeys.ONBOARDING_HELD) } + } + + override suspend fun settleColdStart(): ShellState { + // Read and written in the one transaction, so a join landing between + // a separate read and write cannot have its hold taken away. dataStore.edit { prefs -> - prefs.remove(KEY_DIARY_TOKEN) - prefs.remove(KEY_DIARY_LOGIN) + if (prefs.shellState().mode == ShellMode.NONE) prefs.remove(ShellKeys.ONBOARDING_HELD) } + return current() } /** Read-modify-write inside DataStore's transaction, so concurrent edits merge. */ @@ -433,12 +488,6 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore { remove(KEY_SCHEDULE_FINGERPRINT) } - /** `null` unless a diary sign-in has actually stored a token. */ - private fun Preferences.toDiarySession(): DiarySession? { - val token = this[KEY_DIARY_TOKEN]?.takeIf { it.isNotBlank() } ?: return null - return DiarySession(login = this[KEY_DIARY_LOGIN].orEmpty(), token = token) - } - /** * Enums are stored by name rather than by ordinal, and unknown names fall * back to the default instead of throwing: reordering an enum must not be @@ -546,8 +595,7 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore { private companion object { // The membership keys live in `MembershipKeys`, beside the code that reads them. - val KEY_DIARY_TOKEN = stringPreferencesKey("diary_token") - val KEY_DIARY_LOGIN = stringPreferencesKey("diary_login") + // The diary's keys live in `DiaryKeys`, beside the reads that decode them. val KEY_CALENDAR_FILTERS = stringSetPreferencesKey("calendar_filters") val KEY_CALENDAR_ORDER = stringPreferencesKey("calendar_order") @@ -634,3 +682,104 @@ internal class LessonsPreferences(context: Context) : DiarySessionStore { val KEY_NOTIFY_UPDATES = booleanPreferencesKey("settings_notify_updates") } } + +/** + * The keys of the app shell's own state, which belongs to neither account. + * + * `onboarding_held` is kept until onboarding releases it, not cleared by a + * sign-out of either account: it describes the flow on screen, and only the + * flow — or a cold start that finds nothing to finish — may end it. + */ +internal object ShellKeys { + val ONBOARDING_HELD = booleanPreferencesKey("onboarding_held") +} + +/** [shellModeOf] and the hold, from one emission; see [ShellModeSource]. */ +internal fun Preferences.shellState(): ShellState = ShellState( + mode = shellModeOf(activeMembership(), toDiaryTarget()), + held = this[ShellKeys.ONBOARDING_HELD] ?: false, +) + +/** + * The diary's keys, apart from the class's and never written by the same + * method: leaving a class must not sign a parent out of the diary, and signing + * out of the diary must not unjoin the class. + * + * `diary_target` is one JSON value rather than six loose keys, so a write cut + * short can never leave a region beside another diary's school. + * `diary_student_id` is apart from it because it changes on its own — a + * different pupil picked — and is forgotten on its own, when the account + * changes. + */ +internal object DiaryKeys { + val TOKEN = stringPreferencesKey("diary_token") + val LOGIN = stringPreferencesKey("diary_login") + val TARGET = stringPreferencesKey("diary_target") + val STUDENT_ID = longPreferencesKey("diary_student_id") +} + +/** + * Which diary this phone signs in to, read from one emission — so whatever + * decides a mode from it and from the memberships reads both from the same + * moment rather than combining two flows that can disagree in between. + * + * A stored target that this build cannot read — a later version, a provider it + * does not know — is no target at all, rather than a guess: signing a third + * diary's account in to Petersburg would be worse than asking. An install from + * before targets, holding a token and a login, is Petersburg in Moscow time, + * which is the only diary it can have signed in to. + */ +internal fun Preferences.toDiaryTarget(): DiaryTarget? { + this[DiaryKeys.TARGET]?.let { stored -> return DiaryTargetCodec.decode(stored) } + this[DiaryKeys.TOKEN]?.takeIf { it.isNotBlank() } ?: return null + val login = this[DiaryKeys.LOGIN]?.takeIf { it.isNotBlank() } ?: return null + return DiaryTarget.petersburg(login) +} + +/** Our bearer, the login and the target, in one transaction. */ +internal fun MutablePreferences.putDiarySession(value: DiarySession) { + this[DiaryKeys.TOKEN] = value.token + this[DiaryKeys.LOGIN] = value.login + this[DiaryKeys.TARGET] = DiaryTargetCodec.encode(value.target) +} + +/** + * A bare `401`: our bearer is dead, the account is not. The login and the + * target stay, so the sign-in that follows is to the same diary. + * + * An install from before targets has only a token and a login, and its target + * is *derived* from the pair — so removing the token would remove the target + * with it. It is written down first, in the same transaction, as the Petersburg + * target it has always been read as. + */ +internal fun MutablePreferences.dropDiaryToken() { + if (DiaryKeys.TARGET !in this) { + toDiaryTarget()?.let { this[DiaryKeys.TARGET] = DiaryTargetCodec.encode(it) } + } + remove(DiaryKeys.TOKEN) +} + +/** Signing out: everything about the diary account, and nothing about the class. */ +internal fun MutablePreferences.dropDiary() { + remove(DiaryKeys.TOKEN) + remove(DiaryKeys.LOGIN) + remove(DiaryKeys.TARGET) + remove(DiaryKeys.STUDENT_ID) +} + +/** + * `null` unless a diary sign-in has actually stored a token — and `null` too + * when its target is one this build cannot read (see [toDiaryTarget]): a bearer + * sent for an account the app cannot name would be answered for somebody the + * screens cannot say. + */ +internal fun Preferences.toDiarySession(): DiarySession? { + val token = this[DiaryKeys.TOKEN]?.takeIf { it.isNotBlank() } ?: return null + val login = this[DiaryKeys.LOGIN].orEmpty() + val target = if (DiaryKeys.TARGET in this) { + toDiaryTarget() ?: return null + } else { + DiaryTarget.petersburg(login) + } + return DiarySession(login = login, token = token, target = target) +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt index 7e3ac0b7..dd6f99db 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/datastore/Memberships.kt @@ -4,9 +4,13 @@ import androidx.datastore.preferences.core.MutablePreferences import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.Session import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.jsonArray @@ -37,6 +41,39 @@ private data class StoredSession( val className: String = "", val school: String? = null, val token: String = "", + /** + * The class's diary binding, as a raw element decoded on its own + * ([storedBinding]): a binding this build cannot read must cost the + * binding, never the membership — and a typed field that failed would + * take the whole record with it. Absent on every record written before + * bindings, which read as unbound. + */ + val diary: JsonElement? = null, +) + +/** One class's diary binding as it is written down; see [StoredSession.diary]. */ +@Serializable +private data class StoredBinding( + val provider: String = "", + val region: String? = null, + val schoolId: Long? = null, + val schoolName: String? = null, +) + +private fun storedBinding(element: JsonElement?): DiaryBinding? { + if (element == null || element is JsonNull) return null + val stored = runCatching { membershipJson.decodeFromJsonElement(element) } + .getOrNull() + ?: return null + // A provider a later build added reads as no binding rather than as the + // wrong diary. + val provider = DiaryProviderKey.fromWire(stored.provider) ?: return null + return DiaryBinding(provider, stored.region, stored.schoolId, stored.schoolName) +} + +private fun DiaryBinding.stored(): JsonElement = membershipJson.encodeToJsonElement( + StoredBinding.serializer(), + StoredBinding(provider.wire, region, schoolId, schoolName), ) /** @@ -82,6 +119,7 @@ internal fun Preferences.memberships(): List { className = stored.className, school = stored.school, token = token, + diary = storedBinding(stored.diary), ) } } @@ -142,7 +180,7 @@ internal fun List.withMembership(joined: Session): List = */ internal fun MutablePreferences.writeMemberships(value: List) { this[MembershipKeys.SESSIONS] = membershipJson.encodeToString( - value.map { StoredSession(it.classId, it.className, it.school, it.token) }, + value.map { StoredSession(it.classId, it.className, it.school, it.token, it.diary?.stored()) }, ) remove(MembershipKeys.TOKEN) remove(MembershipKeys.CLASS_ID) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt index 9022d103..17c33b69 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/LessonsContainer.kt @@ -1,7 +1,18 @@ package com.lumenpearson.lessons.core.data.di import android.content.Context +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.catalog.RegionLookup +import com.lumenpearson.lessons.core.data.catalog.RegionSearch +import com.lumenpearson.lessons.core.data.catalog.SchoolDirectory +import com.lumenpearson.lessons.core.data.catalog.ServerSchoolDirectory import com.lumenpearson.lessons.core.data.database.LessonsDatabase +import com.lumenpearson.lessons.core.data.diary.DiaryCache +import com.lumenpearson.lessons.core.data.diary.DiaryCacheImpl +import com.lumenpearson.lessons.core.data.diary.DiaryDatabase +import com.lumenpearson.lessons.core.data.diary.DiaryImport +import com.lumenpearson.lessons.core.data.diary.DiaryImportImpl +import com.lumenpearson.lessons.core.data.diary.SeedingDiarySignIn import com.lumenpearson.lessons.core.data.datastore.LessonsPreferences import com.lumenpearson.lessons.core.data.network.LessonsApi import com.lumenpearson.lessons.core.data.notifications.SchoolAlerts @@ -20,17 +31,29 @@ import com.lumenpearson.lessons.core.data.repository.DeviceLinkRepositoryImpl import com.lumenpearson.lessons.core.data.repository.DiaryRepository import com.lumenpearson.lessons.core.data.repository.DocsRepository import com.lumenpearson.lessons.core.data.repository.DiaryRepositoryImpl +import com.lumenpearson.lessons.core.data.repository.DiarySessionStore +import com.lumenpearson.lessons.core.data.repository.DiarySignIn +import com.lumenpearson.lessons.core.data.repository.DiarySignInImpl import com.lumenpearson.lessons.core.data.repository.GithubRepository import com.lumenpearson.lessons.core.data.repository.ManageRepository import com.lumenpearson.lessons.core.data.repository.ManageRepositoryImpl +import com.lumenpearson.lessons.core.data.repository.ModeAnnouncingDiaryStore +import com.lumenpearson.lessons.core.data.repository.ShellModeSource import com.lumenpearson.lessons.core.data.repository.UpdateRepository import com.lumenpearson.lessons.core.data.sync.DataSyncBroadcast import com.lumenpearson.lessons.core.data.sync.SyncScheduler import com.lumenpearson.lessons.core.data.update.UpdateRepositoryImpl +import com.lumenpearson.lessons.core.data.upstream.CatalogUpstreamDirectory +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import com.lumenpearson.lessons.core.data.upstream.NetSchoolSchoolSearch +import com.lumenpearson.lessons.core.data.upstream.UpstreamDirectory +import com.lumenpearson.lessons.core.data.upstream.UpstreamHttp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient /** * Everything the rest of the app is allowed to reach for. @@ -54,11 +77,45 @@ interface LessonsContainer { val docsRepository: DocsRepository /** - * The Petersburg diary. Present whether or not anybody has signed in to - * one: it is the repository that knows, and the section asks it. + * The diary — Petersburg's or a «Сетевой город» region's. Present whether + * or not anybody has signed in to one: it is the repository that knows, + * and the section asks it. */ val diaryRepository: DiaryRepository + /** + * Getting into a diary step by step, for the screens that hold the + * diary's own session between the steps (onboarding's sign-in, which + * retries a registration without asking for the password again). + * [diaryRepository]'s `signIn` is the same thing in one call. + */ + val diarySignIn: DiarySignIn + + /** A «Сетевой город» region's schools, asked of the region's own server. */ + val diarySchoolSearch: DiarySchoolSearch + + /** + * Which home the app opens on — class, diary or neither — and whether + * onboarding holds the screen; also whether the periodic class sync should + * be armed. Read from the preferences alone, one emission at a time. + */ + val shellMode: ShellModeSource + + /** + * The diary as this phone last read it. Drawn by the app's diary screens + * only — never by the widget or a worker. + */ + val diaryCache: DiaryCache + + /** Filling [diaryCache] after a sign-in, and refreshing it while the app is open. */ + val diaryImport: DiaryImport + + /** The server's anonymous school directory, and a region's own school list. */ + val schoolDirectory: SchoolDirectory + + /** «Which region do you mean»: the bundled catalog and, for a school's name, the directory. */ + val regionLookup: RegionLookup + /** * Running the class. Present on every install, because whether this phone * may use it is the server's answer and not a fact the graph could hold: @@ -274,6 +331,78 @@ class DefaultLessonsContainer( DocsRepositoryImpl(appContext) } + /** + * The region catalog the server's generator wrote, bundled as an asset. + * Read on first use — which is always inside a sign-in or a search, on the + * IO dispatcher — and kept, because it does not change while the app runs. + */ + private val regionCatalog: RegionCatalog by lazy { RegionCatalog.load(appContext) } + + /** The only source of a host the phone sends a diary request to. */ + private val upstreamDirectory: UpstreamDirectory by lazy { CatalogUpstreamDirectory(regionCatalog) } + + /** + * The client for the diaries' own servers — its own, with none of [apis]' + * interceptors: those rewrite every host to our server and sign by path + * with our bearers, and a diary request through them would go to the + * wrong server or carry our token to somebody else's. + */ + private val upstreamClient: OkHttpClient by lazy { + UpstreamHttp.client { upstreamDirectory.allowedOrigins() } + } + + /** + * The catalog search, built once over the catalog, and only ever handed out + * from the IO dispatcher: the first use reads the asset. + */ + private val regionSearch: RegionSearch by lazy { RegionSearch(regionCatalog) } + + private suspend fun regionSearchOffMain(): RegionSearch = withContext(Dispatchers.IO) { regionSearch } + + /** + * `diary.db`, opened on first use: a phone that never signs in to a diary + * never creates the file. + */ + private val diaryDatabase: DiaryDatabase by lazy { DiaryDatabase.build(appContext) } + + /** + * The concrete cache, because two interfaces are drawn from it: the one the + * screens read and the write side only the repository holds. + */ + private val diaryCacheImpl: DiaryCacheImpl by lazy { + DiaryCacheImpl(dao = { diaryDatabase.diaryDao() }, selection = preferences) + } + + /** + * The diary's half of the preferences, announcing the writes that change + * the shell's mode to the widget — which redraws only when told, and whose + * sentence depends on the mode. Both diary writers share it. + */ + private val diaryStore: DiarySessionStore by lazy { + ModeAnnouncingDiaryStore(preferences) { DataSyncBroadcast.send(appContext) } + } + + override val diarySignIn: DiarySignIn by lazy { + SeedingDiarySignIn( + delegate = DiarySignInImpl( + api = apis.diary, + store = diaryStore, + directory = { upstreamDirectory }, + client = { upstreamClient }, + // Another account signing in empties what the last one left. + forgetLocal = diaryCacheImpl::clear, + ), + cache = diaryCacheImpl, + ) + } + + override val diarySchoolSearch: DiarySchoolSearch by lazy { + NetSchoolSchoolSearch( + client = { upstreamClient }, + directory = { upstreamDirectory }, + ) + } + override val diaryRepository: DiaryRepository by lazy { DiaryRepositoryImpl( api = apis.diary, @@ -281,10 +410,39 @@ class DefaultLessonsContainer( // process that may open the DataStore file, and the interface it // implements is narrow enough that this repository cannot reach // the class token through it. - store = preferences, + store = diaryStore, + diarySignIn = diarySignIn, + forgetLocal = diaryCacheImpl::clear, + cache = diaryCacheImpl, ) } + override val shellMode: ShellModeSource get() = preferences + + override val diaryCache: DiaryCache get() = diaryCacheImpl + + override val diaryImport: DiaryImport by lazy { + DiaryImportImpl( + // The repository, not the API: its reads are what fill the cache, + // so the import cannot write anything a screen would not have. + repository = diaryRepository, + store = diaryStore, + cache = diaryCacheImpl, + ) + } + + override val schoolDirectory: SchoolDirectory by lazy { + ServerSchoolDirectory( + api = apis.directory, + search = ::regionSearchOffMain, + schools = diarySchoolSearch, + ) + } + + override val regionLookup: RegionLookup by lazy { + RegionLookup(search = ::regionSearchOffMain, directory = schoolDirectory) + } + override val manageRepository: ManageRepository by lazy { ManageRepositoryImpl( api = apis.manage, diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCache.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCache.kt new file mode 100644 index 00000000..d07ea902 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCache.kt @@ -0,0 +1,321 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryEdit +import com.lumenpearson.lessons.core.data.repository.DiaryHomework +import com.lumenpearson.lessons.core.data.repository.DiaryLesson +import com.lumenpearson.lessons.core.data.repository.DiaryMark +import com.lumenpearson.lessons.core.data.repository.DiaryMarkKind +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import java.time.Instant +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow + +/** + * The diary as this phone last read it, for the screens to draw before — or + * instead of — the network. + * + * Read-only from here, but for which pupil is shown. The one writer of what + * the diary said is `DiaryRepositoryImpl`: every read it + * makes that succeeds is written through ([DiaryCacheWriter]), so the cache + * holds exactly what the screens were last answered and never a second + * derivation of it. The import fills it by reading through that same + * repository, which is why the ranges it asks for are the screen's. + * + * Everything carries when it was read, and `null` means never — which is not + * the same as empty: a week the diary has no lessons in is `lessonsLoadedAt` + * set and no rows, and the screen says «уроков нет» rather than «не + * загружено». + * + * Nothing in the widget, the sync worker or the alerts reads this + * (`SyncWorkerSourceTest`): the diary is read only while somebody is looking at + * it. + */ +interface DiaryCache { + + /** The account's pupils, in the server's order. */ + val students: Flow + + /** + * The pupil the diary shows, when the account has several — the choice the + * import made or the screen last stored. Kept with the session rather than + * in the cache, because it outlives a re-sign-in to the same account; it is + * here so a screen drawing the cache needs one object. + */ + val selectedStudentId: Flow + + /** Stores the pupil the diary shows; `null` forgets the choice. */ + suspend fun selectStudent(id: Long?) + + /** One Monday-to-Sunday week of one pupil; [monday] must be a Monday. */ + fun week(studentId: Long, monday: LocalDate): Flow + + /** One pupil's latest marks window. */ + fun marks(studentId: Long): Flow + + /** One pupil's terms. */ + fun periods(studentId: Long): Flow + + /** + * Forgets everything — signing out, or another account signing in. Also + * makes every read already in flight land nowhere: an answer that arrives + * after this was asked is for an account the phone has let go of. + */ + suspend fun clear() +} + +/** @see DiaryCache.students */ +data class DiaryCachedStudents( + val students: List, + val loadedAt: Instant?, +) + +/** @see DiaryCache.week */ +data class DiaryCachedWeek( + val monday: LocalDate, + val lessons: List, + val homework: List, + val lessonsLoadedAt: Instant?, + val homeworkLoadedAt: Instant?, +) + +/** + * @see DiaryCache.marks + * @property from the window [marks] covers, or `null` when none was read. The + * screen draws these only when it is the window it would ask for. + */ +data class DiaryCachedMarks( + val from: LocalDate?, + val to: LocalDate?, + val marks: List, + val loadedAt: Instant?, +) { + /** Whether these are the marks of exactly [window]. */ + fun covers(window: DiaryDateRange): Boolean = + loadedAt != null && from == window.from && to == window.to +} + +/** @see DiaryCache.periods */ +data class DiaryCachedPeriods( + val periods: List, + val loadedAt: Instant?, +) + +/** + * The write side of the cache, for `DiaryRepositoryImpl` alone. + * + * Every write carries the [generation] the read began under. [DiaryCache.clear] + * moves the generation on, so an answer that was in flight when somebody + * signed out — or when another account signed in — is dropped instead of + * being written into the cache of an account that no longer owns it. Without + * that, a sign-out during a slow week read left that week's marks and homework + * on the phone after the screen had said they were gone. + */ +internal interface DiaryCacheWriter { + + /** Taken before a read starts; see the class note. */ + fun generation(): Long + + suspend fun putStudents(generation: Long, students: List) + + /** [from] .. [to] must be whole weeks ([DiaryWindows.isWholeWeeks]). */ + suspend fun putLessons(generation: Long, studentId: Long, from: LocalDate, to: LocalDate, rows: List) + + /** @see putLessons */ + suspend fun putHomework(generation: Long, studentId: Long, from: LocalDate, to: LocalDate, rows: List) + + suspend fun putMarks(generation: Long, studentId: Long, from: LocalDate, to: LocalDate, rows: List) + + suspend fun putPeriods(generation: Long, studentId: Long, rows: List) + + /** For a repository built without a cache: every write goes nowhere. */ + object None : DiaryCacheWriter { + override fun generation(): Long = 0 + override suspend fun putStudents(generation: Long, students: List) = Unit + override suspend fun putLessons( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = Unit + + override suspend fun putHomework( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = Unit + + override suspend fun putMarks( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = Unit + + override suspend fun putPeriods(generation: Long, studentId: Long, rows: List) = Unit + } +} + +// ---- rows <-> domain --------------------------------------------------------- + +internal fun DiaryStudent.toEntity(position: Int, at: Long) = DiaryStudentEntity( + id = id, + firstName = firstName, + lastName = lastName, + middleName = middleName, + fullName = fullName, + school = school, + className = className, + position = position, + syncedAt = at, +) + +internal fun DiaryStudentEntity.toDomain() = DiaryStudent( + id = id, + firstName = firstName, + lastName = lastName, + middleName = middleName, + fullName = fullName, + school = school, + className = className, +) + +internal fun DiaryLesson.toEntity(studentId: Long, position: Int) = DiaryLessonEntity( + studentId = studentId, + date = date, + number = number, + subject = subject, + startsAt = startsAt, + endsAt = endsAt, + room = room, + teacher = teacher, + homework = homework, + topic = topic, + target = target, + edits = DiaryEditsCodec.encode(edits), + ambiguous = ambiguous, + position = position, +) + +internal fun DiaryLessonEntity.toDomain() = DiaryLesson( + date = date, + number = number, + subject = subject, + startsAt = startsAt, + endsAt = endsAt, + room = room, + teacher = teacher, + homework = homework, + topic = topic, + target = target, + edits = DiaryEditsCodec.decode(edits), + ambiguous = ambiguous, +) + +internal fun DiaryHomework.toEntity(studentId: Long, position: Int) = DiaryHomeworkEntity( + studentId = studentId, + dueDate = dueDate, + upstreamId = id, + subject = subject, + text = text, + teacher = teacher, + target = target, + edits = DiaryEditsCodec.encode(edits), + ambiguous = ambiguous, + position = position, +) + +internal fun DiaryHomeworkEntity.toDomain() = DiaryHomework( + id = upstreamId, + dueDate = dueDate, + subject = subject, + text = text, + teacher = teacher, + target = target, + edits = DiaryEditsCodec.decode(edits), + ambiguous = ambiguous, +) + +internal fun DiaryMark.toEntity(studentId: Long, position: Int) = DiaryMarkEntity( + studentId = studentId, + upstreamId = id, + subjectId = subjectId, + subject = subject, + date = date, + value = value, + kind = kind.name, + reason = reason, + comment = comment, + position = position, +) + +internal fun DiaryMarkEntity.toDomain() = DiaryMark( + id = upstreamId, + subjectId = subjectId, + subject = subject, + date = date, + value = value, + // By name, tolerantly: a kind a later build wrote reads as OTHER here + // rather than failing the whole marks tab. + kind = DiaryMarkKind.fromWire(kind), + reason = reason, + comment = comment, +) + +internal fun DiaryPeriod.toEntity(studentId: Long, position: Int) = DiaryPeriodEntity( + studentId = studentId, + id = id, + name = name, + startsOn = startsOn, + endsOn = endsOn, + isCurrent = isCurrent, + position = position, +) + +internal fun DiaryPeriodEntity.toDomain() = DiaryPeriod( + id = id, + name = name, + startsOn = startsOn, + endsOn = endsOn, + isCurrent = isCurrent, +) + +/** + * A row's corrections as they are kept in one column: JSON, decoded + * tolerantly, because they are only ever read back with their row and a + * damaged value must cost the «исправлено» marks and not the lesson. + */ +internal object DiaryEditsCodec { + + @kotlinx.serialization.Serializable + private data class Stored( + val field: String = "", + val value: String = "", + val original: String? = null, + val changedUpstream: Boolean = false, + ) + + private val json = kotlinx.serialization.json.Json { + ignoreUnknownKeys = true + coerceInputValues = true + } + + private val serializer = kotlinx.serialization.builtins.ListSerializer(Stored.serializer()) + + fun encode(edits: List): String = + if (edits.isEmpty()) "" else json.encodeToString( + serializer, + edits.map { Stored(it.field, it.value, it.original, it.changedUpstream) }, + ) + + fun decode(raw: String): List { + if (raw.isBlank()) return emptyList() + val stored = runCatching { json.decodeFromString(serializer, raw) }.getOrNull() ?: return emptyList() + return stored.filter { it.field.isNotBlank() } + .map { DiaryEdit(it.field, it.value, it.original, it.changedUpstream) } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheImpl.kt new file mode 100644 index 00000000..00faede1 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheImpl.kt @@ -0,0 +1,154 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryHomework +import com.lumenpearson.lessons.core.data.repository.DiaryLesson +import com.lumenpearson.lessons.core.data.repository.DiaryMark +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiarySessionStore +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import java.time.Clock +import java.time.Instant +import java.time.LocalDate +import java.util.concurrent.atomic.AtomicLong +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * [DiaryCache] and its write side over [DiaryDao]. + * + * @param dao resolved on first use, so building the container — which happens + * on every cold start, the widget's included — opens no database file. + * @param selection where the chosen pupil is kept: the session's store. + */ +internal class DiaryCacheImpl( + private val dao: () -> DiaryDao, + private val selection: DiarySessionStore, + private val clock: Clock = Clock.systemUTC(), +) : DiaryCache, DiaryCacheWriter { + + override val selectedStudentId: Flow get() = selection.selectedStudentId + + override suspend fun selectStudent(id: Long?) = selection.selectStudent(id) + + /** + * One lock for every write and for [clear], so a write cannot be checked + * against the generation, overtaken by a clear, and then land. + */ + private val writes = Mutex() + private val current = AtomicLong(0) + + /** + * Re-read on every change of any diary table, from a transactional + * snapshot. Room's observed query emits once on collection, so a screen + * gets what is there before anything is written. The database is opened on + * collection, not when the flow is built. + */ + private fun observe(read: suspend (DiaryDao) -> T): Flow = + flow { emitAll(dao().observeChanges()) } + .map { read(dao()) } + .distinctUntilChanged() + + override val students: Flow = observe { dao -> + val rows = dao.students() + DiaryCachedStudents( + students = rows.map { it.toDomain() }, + // Written together, so any row's stamp is the list's; the oldest is + // the honest one if a later build ever writes them apart. + loadedAt = rows.minOfOrNull { it.syncedAt }?.let(Instant::ofEpochMilli), + ) + } + + override fun week(studentId: Long, monday: LocalDate): Flow = observe { dao -> + val snapshot = dao.weekSnapshot(studentId, monday) + DiaryCachedWeek( + monday = monday, + lessons = snapshot.lessons.map { it.toDomain() }, + homework = snapshot.homework.map { it.toDomain() }, + lessonsLoadedAt = snapshot.week?.lessonsSyncedAt?.let(Instant::ofEpochMilli), + homeworkLoadedAt = snapshot.week?.homeworkSyncedAt?.let(Instant::ofEpochMilli), + ) + } + + override fun marks(studentId: Long): Flow = observe { dao -> + val snapshot = dao.marksSnapshot(studentId) + val student = snapshot.student + DiaryCachedMarks( + from = student?.marksFrom, + to = student?.marksTo, + marks = snapshot.marks.map { it.toDomain() }, + loadedAt = student?.marksSyncedAt?.let(Instant::ofEpochMilli), + ) + } + + override fun periods(studentId: Long): Flow = observe { dao -> + val snapshot = dao.periodsSnapshot(studentId) + DiaryCachedPeriods( + periods = snapshot.periods.map { it.toDomain() }, + loadedAt = snapshot.student?.periodsSyncedAt?.let(Instant::ofEpochMilli), + ) + } + + override suspend fun clear() { + writes.withLock { + current.incrementAndGet() + dao().clear() + } + } + + override fun generation(): Long = current.get() + + override suspend fun putStudents(generation: Long, students: List) = write(generation) { at -> + replaceStudents(students.mapIndexed { index, student -> student.toEntity(index, at) }) + } + + override suspend fun putLessons( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = write(generation) { at -> + if (!DiaryWindows.isWholeWeeks(from, to)) return@write + replaceLessons(studentId, from, to, rows.mapIndexed { index, row -> row.toEntity(studentId, index) }, at) + } + + override suspend fun putHomework( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = write(generation) { at -> + if (!DiaryWindows.isWholeWeeks(from, to)) return@write + replaceHomework(studentId, from, to, rows.mapIndexed { index, row -> row.toEntity(studentId, index) }, at) + } + + override suspend fun putMarks( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = write(generation) { at -> + replaceMarks(studentId, from, to, rows.mapIndexed { index, row -> row.toEntity(studentId, index) }, at) + } + + override suspend fun putPeriods(generation: Long, studentId: Long, rows: List) = + write(generation) { at -> + replacePeriods(studentId, rows.mapIndexed { index, row -> row.toEntity(studentId, index) }, at) + } + + private suspend fun write(generation: Long, block: suspend DiaryDao.(at: Long) -> Unit) { + writes.withLock { + // A clear happened since the read began: the answer is for an + // account this phone no longer holds. + if (generation != current.get()) return + dao().block(clock.millis()) + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDao.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDao.kt new file mode 100644 index 00000000..882c6766 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDao.kt @@ -0,0 +1,324 @@ +package com.lumenpearson.lessons.core.data.diary + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.Transaction +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow + +/** + * Every read and write of `diary.db`. + * + * An abstract class for the reason `TimetableDao` is one: the writes that must + * not be seen half-done are concrete `@Transaction` methods, and the tests + * drive exactly those bodies through `InMemoryDiaryDao`, which implements only + * the abstract statements. A fake that re-implemented the orchestration could + * agree with it while both were wrong. + * + * Two rules every statement below keeps, and `DiaryDaoPolicyTest` reads this + * file to hold them: + * + * * **every delete names its pupil** (or, in [clear], its whole table) — there + * are no foreign keys, so nothing is left to a cascade; + * * **no upsert syntax.** API 26–29 ship SQLite older than 3.24, which has no + * `ON CONFLICT … DO UPDATE`; a week is stamped with `INSERT OR IGNORE` and + * then an `UPDATE`, which every SQLite understands. + */ +@Dao +internal abstract class DiaryDao { + + // ---- reads ---------------------------------------------------------- + + /** + * Emits whenever any diary table changes, and carries nothing. + * + * Room re-runs an observed query when a table it names is written, so this + * one names all six and returns no rows. The caches below read their + * snapshot inside one transaction on each emission, rather than combining + * three observed queries that could each land on a different side of a + * write — a week's new lessons under its old «загружено в …». + */ + @Query( + "SELECT 1 FROM diary_student, diary_week, diary_period, diary_lesson, " + + "diary_homework, diary_mark LIMIT 0", + ) + abstract fun observeChanges(): Flow> + + @Query("SELECT * FROM diary_student ORDER BY position ASC") + abstract suspend fun students(): List + + @Query("SELECT * FROM diary_student WHERE id = :studentId") + abstract suspend fun student(studentId: Long): DiaryStudentEntity? + + @Query("SELECT * FROM diary_week WHERE student_id = :studentId AND monday = :monday") + abstract suspend fun week(studentId: Long, monday: LocalDate): DiaryWeekEntity? + + @Query( + "SELECT * FROM diary_lesson WHERE student_id = :studentId " + + "AND date BETWEEN :from AND :to ORDER BY date ASC, position ASC", + ) + abstract suspend fun lessons(studentId: Long, from: LocalDate, to: LocalDate): List + + @Query( + "SELECT * FROM diary_homework WHERE student_id = :studentId " + + "AND due_date BETWEEN :from AND :to ORDER BY due_date ASC, position ASC", + ) + abstract suspend fun homework(studentId: Long, from: LocalDate, to: LocalDate): List + + @Query("SELECT * FROM diary_mark WHERE student_id = :studentId ORDER BY position ASC") + abstract suspend fun marks(studentId: Long): List + + @Query("SELECT * FROM diary_period WHERE student_id = :studentId ORDER BY position ASC") + abstract suspend fun periods(studentId: Long): List + + /** One week of one pupil, read in one transaction; see [observeChanges]. */ + @Transaction + open suspend fun weekSnapshot(studentId: Long, monday: LocalDate): DiaryWeekSnapshot { + val sunday = monday.plusDays(6) + return DiaryWeekSnapshot( + week = week(studentId, monday), + lessons = lessons(studentId, monday, sunday), + homework = homework(studentId, monday, sunday), + ) + } + + /** One pupil's marks and the window they cover, read together. */ + @Transaction + open suspend fun marksSnapshot(studentId: Long): DiaryMarksSnapshot = + DiaryMarksSnapshot(student = student(studentId), marks = marks(studentId)) + + /** One pupil's terms and when they were read, together. */ + @Transaction + open suspend fun periodsSnapshot(studentId: Long): DiaryPeriodsSnapshot = + DiaryPeriodsSnapshot(student = student(studentId), periods = periods(studentId)) + + // ---- building blocks: call the transactions below instead ------------- + + /** `REPLACE` on the primary key, which SQLite has had for ever; not an upsert. */ + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract suspend fun insertStudents(rows: List) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + abstract suspend fun insertWeeksIfAbsent(rows: List) + + @Insert + abstract suspend fun insertLessons(rows: List) + + @Insert + abstract suspend fun insertHomework(rows: List) + + @Insert + abstract suspend fun insertMarks(rows: List) + + @Insert + abstract suspend fun insertPeriods(rows: List) + + @Query( + "UPDATE diary_week SET lessons_synced_at = :at " + + "WHERE student_id = :studentId AND monday IN (:mondays)", + ) + abstract suspend fun stampLessons(studentId: Long, mondays: List, at: Long) + + @Query( + "UPDATE diary_week SET homework_synced_at = :at " + + "WHERE student_id = :studentId AND monday IN (:mondays)", + ) + abstract suspend fun stampHomework(studentId: Long, mondays: List, at: Long) + + @Query( + "UPDATE diary_student SET marks_from = :from, marks_to = :to, marks_synced_at = :at " + + "WHERE id = :studentId", + ) + abstract suspend fun stampMarks(studentId: Long, from: LocalDate, to: LocalDate, at: Long) + + @Query("UPDATE diary_student SET periods_synced_at = :at WHERE id = :studentId") + abstract suspend fun stampPeriods(studentId: Long, at: Long) + + @Query("DELETE FROM diary_student WHERE id NOT IN (:keep)") + abstract suspend fun deleteStudentsOtherThan(keep: List) + + @Query("DELETE FROM diary_week WHERE student_id NOT IN (:keep)") + abstract suspend fun deleteWeeksOtherThan(keep: List) + + @Query("DELETE FROM diary_period WHERE student_id NOT IN (:keep)") + abstract suspend fun deletePeriodsOtherThan(keep: List) + + @Query("DELETE FROM diary_lesson WHERE student_id NOT IN (:keep)") + abstract suspend fun deleteLessonsOtherThan(keep: List) + + @Query("DELETE FROM diary_homework WHERE student_id NOT IN (:keep)") + abstract suspend fun deleteHomeworkOtherThan(keep: List) + + @Query("DELETE FROM diary_mark WHERE student_id NOT IN (:keep)") + abstract suspend fun deleteMarksOtherThan(keep: List) + + @Query("DELETE FROM diary_lesson WHERE student_id = :studentId AND date BETWEEN :from AND :to") + abstract suspend fun deleteLessons(studentId: Long, from: LocalDate, to: LocalDate) + + @Query( + "DELETE FROM diary_homework WHERE student_id = :studentId " + + "AND due_date BETWEEN :from AND :to", + ) + abstract suspend fun deleteHomework(studentId: Long, from: LocalDate, to: LocalDate) + + @Query("DELETE FROM diary_mark WHERE student_id = :studentId") + abstract suspend fun deleteMarks(studentId: Long) + + @Query("DELETE FROM diary_period WHERE student_id = :studentId") + abstract suspend fun deletePeriods(studentId: Long) + + @Query("DELETE FROM diary_student") + abstract suspend fun deleteAllStudents() + + @Query("DELETE FROM diary_week") + abstract suspend fun deleteAllWeeks() + + @Query("DELETE FROM diary_period") + abstract suspend fun deleteAllPeriods() + + @Query("DELETE FROM diary_lesson") + abstract suspend fun deleteAllLessons() + + @Query("DELETE FROM diary_homework") + abstract suspend fun deleteAllHomework() + + @Query("DELETE FROM diary_mark") + abstract suspend fun deleteAllMarks() + + // ---- the writes ------------------------------------------------------- + + /** + * The account's pupils, as the server just listed them. + * + * A pupil who is no longer listed takes every row of theirs along — + * explicitly, table by table — and a pupil still listed keeps the stamps of + * what was fetched for them: `REPLACE` would otherwise reset those to + * «never», and a marks tab read a minute ago would say «не загружено». + */ + @Transaction + open suspend fun replaceStudents(rows: List) { + if (rows.isEmpty()) { + clear() + return + } + val keep = rows.map { it.id } + deleteMarksOtherThan(keep) + deleteHomeworkOtherThan(keep) + deleteLessonsOtherThan(keep) + deletePeriodsOtherThan(keep) + deleteWeeksOtherThan(keep) + deleteStudentsOtherThan(keep) + val before = students().associateBy { it.id } + insertStudents( + rows.map { row -> + val old = before[row.id] ?: return@map row + row.copy( + periodsSyncedAt = old.periodsSyncedAt, + marksFrom = old.marksFrom, + marksTo = old.marksTo, + marksSyncedAt = old.marksSyncedAt, + ) + }, + ) + } + + /** + * One pupil's lessons for whole weeks [monday] .. [sunday], replacing what + * was there and stamping every week in the span as fetched — including the + * ones the answer had nothing for, which is what makes an empty week + * «пусто» rather than «не загружено». + * + * A row dated outside the span is dropped: it would sit in a week nobody + * stamped, and be drawn under «не загружено» as if it were the whole week. + */ + @Transaction + open suspend fun replaceLessons( + studentId: Long, + monday: LocalDate, + sunday: LocalDate, + rows: List, + at: Long, + ) { + deleteLessons(studentId, monday, sunday) + insertLessons(rows.filter { it.studentId == studentId && it.date in monday..sunday }) + val mondays = mondaysOf(monday, sunday) + insertWeeksIfAbsent(mondays.map { DiaryWeekEntity(studentId = studentId, monday = it) }) + stampLessons(studentId, mondays, at) + } + + /** @see replaceLessons */ + @Transaction + open suspend fun replaceHomework( + studentId: Long, + monday: LocalDate, + sunday: LocalDate, + rows: List, + at: Long, + ) { + deleteHomework(studentId, monday, sunday) + insertHomework(rows.filter { it.studentId == studentId && it.dueDate in monday..sunday }) + val mondays = mondaysOf(monday, sunday) + insertWeeksIfAbsent(mondays.map { DiaryWeekEntity(studentId = studentId, monday = it) }) + stampHomework(studentId, mondays, at) + } + + /** + * One pupil's marks for [from] .. [to]. One window per pupil, the latest: + * the marks tab asks for one window at a time, and keeping several would + * only be a question of which to draw. + */ + @Transaction + open suspend fun replaceMarks( + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + at: Long, + ) { + deleteMarks(studentId) + insertMarks(rows.filter { it.studentId == studentId }) + stampMarks(studentId, from, to, at) + } + + @Transaction + open suspend fun replacePeriods(studentId: Long, rows: List, at: Long) { + deletePeriods(studentId) + insertPeriods(rows.filter { it.studentId == studentId }) + stampPeriods(studentId, at) + } + + /** Everything, table by table. Signing out, or another account signing in. */ + @Transaction + open suspend fun clear() { + deleteAllMarks() + deleteAllHomework() + deleteAllLessons() + deleteAllPeriods() + deleteAllWeeks() + deleteAllStudents() + } + + private fun mondaysOf(monday: LocalDate, sunday: LocalDate): List = + generateSequence(monday) { it.plusWeeks(1) }.takeWhile { !it.isAfter(sunday) }.toList() +} + +/** What [DiaryDao.weekSnapshot] reads. */ +internal data class DiaryWeekSnapshot( + val week: DiaryWeekEntity?, + val lessons: List, + val homework: List, +) + +/** What [DiaryDao.marksSnapshot] reads. */ +internal data class DiaryMarksSnapshot( + val student: DiaryStudentEntity?, + val marks: List, +) + +/** What [DiaryDao.periodsSnapshot] reads. */ +internal data class DiaryPeriodsSnapshot( + val student: DiaryStudentEntity?, + val periods: List, +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDatabase.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDatabase.kt new file mode 100644 index 00000000..f84ac20e --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDatabase.kt @@ -0,0 +1,59 @@ +package com.lumenpearson.lessons.core.data.diary + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import com.lumenpearson.lessons.core.data.database.LessonsTypeConverters + +/** + * The diary as this phone last read it — a database of its own, apart from + * `lessons.db`, for three reasons: + * + * * a timetable schema bump is destructive (`LessonsDatabase.build`), and it + * must not wipe the offline diary of a family that has no class at all; + * * a diary schema bump must not wipe every class user's timetable either; + * * signing out of the diary is then «empty this file», with nothing of the + * class's standing next to it. + * + * Backups: the app's rules exclude the whole `database` domain + * (`backup_rules.xml`, `data_extraction_rules.xml`), so the marks and homework + * in here never leave the phone that way — which matters, because they are + * a child's. + * + * `exportSchema = true`, into the same `schemas/` folder as `lessons.db`, so a + * later version has a real v1 to be diffed against. + */ +@Database( + entities = [ + DiaryStudentEntity::class, + DiaryWeekEntity::class, + DiaryPeriodEntity::class, + DiaryLessonEntity::class, + DiaryHomeworkEntity::class, + DiaryMarkEntity::class, + ], + version = 1, + exportSchema = true, +) +@TypeConverters(LessonsTypeConverters::class) +internal abstract class DiaryDatabase : RoomDatabase() { + + abstract fun diaryDao(): DiaryDao + + companion object { + /** Also the file name; changing it silently orphans every existing cache. */ + const val NAME: String = "diary.db" + + /** + * Destructive on a version change, like `lessons.db` and for the same + * reason: every row is a copy of what our server answered, one import + * rebuilds it, and nothing typed on the phone lives here. + */ + fun build(context: Context): DiaryDatabase = + Room.databaseBuilder(context.applicationContext, DiaryDatabase::class.java, NAME) + .fallbackToDestructiveMigration(dropAllTables = true) + .build() + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryEntities.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryEntities.kt new file mode 100644 index 00000000..633627f0 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryEntities.kt @@ -0,0 +1,146 @@ +package com.lumenpearson.lessons.core.data.diary + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey +import java.time.LocalDate +import java.time.LocalTime + +/** + * What `diary.db` holds: the diary as this phone last read it, for one account. + * + * Every row is a copy of an answer our server gave, and nothing here is + * authored on the phone — corrections live on the server and arrive already + * laid over, with `edits` saying which fields. That is why the database may be + * dropped whole on a schema change or a sign-out. + * + * There are no foreign keys. Every delete in [DiaryDao] names the pupil it is + * about, so nothing depends on `PRAGMA foreign_keys` (the rule + * `DaoDeletePolicyTest` holds for the timetable, and `DiaryDaoPolicyTest` for + * this file). + * + * The timestamps are epoch milliseconds of the moment the answer arrived. A + * `null` stamp is «never fetched», which is a different thing from «fetched and + * empty» — the same distinction `synced_window` exists for in the timetable. + */ + +/** + * One pupil the account may see, and the stamps of what was fetched per pupil + * rather than per week. + * + * @property marksFrom the window the cached marks cover, inclusive; `null` + * until marks were fetched once. One window per pupil, the last one read. + */ +@Entity(tableName = "diary_student") +internal data class DiaryStudentEntity( + @PrimaryKey @ColumnInfo(name = "id") val id: Long, + @ColumnInfo(name = "first_name") val firstName: String, + @ColumnInfo(name = "last_name") val lastName: String, + @ColumnInfo(name = "middle_name") val middleName: String?, + @ColumnInfo(name = "full_name") val fullName: String, + @ColumnInfo(name = "school") val school: String?, + @ColumnInfo(name = "class_name") val className: String?, + /** The order the server listed the pupils in, which is the picker's. */ + @ColumnInfo(name = "position") val position: Int, + @ColumnInfo(name = "synced_at") val syncedAt: Long, + @ColumnInfo(name = "periods_synced_at") val periodsSyncedAt: Long? = null, + @ColumnInfo(name = "marks_from") val marksFrom: LocalDate? = null, + @ColumnInfo(name = "marks_to") val marksTo: LocalDate? = null, + @ColumnInfo(name = "marks_synced_at") val marksSyncedAt: Long? = null, +) + +/** + * One Monday-to-Sunday week of one pupil, and whether each half of it was + * fetched. A week with a stamp and no rows is a week the diary says is empty. + */ +@Entity( + tableName = "diary_week", + primaryKeys = ["student_id", "monday"], +) +internal data class DiaryWeekEntity( + @ColumnInfo(name = "student_id") val studentId: Long, + @ColumnInfo(name = "monday") val monday: LocalDate, + @ColumnInfo(name = "lessons_synced_at") val lessonsSyncedAt: Long? = null, + @ColumnInfo(name = "homework_synced_at") val homeworkSyncedAt: Long? = null, +) + +/** A term, so the marks window can be worked out offline the way the screen works it out. */ +@Entity( + tableName = "diary_period", + primaryKeys = ["student_id", "id"], +) +internal data class DiaryPeriodEntity( + @ColumnInfo(name = "student_id") val studentId: Long, + @ColumnInfo(name = "id") val id: Long, + @ColumnInfo(name = "name") val name: String, + @ColumnInfo(name = "starts_on") val startsOn: LocalDate?, + @ColumnInfo(name = "ends_on") val endsOn: LocalDate?, + @ColumnInfo(name = "is_current") val isCurrent: Boolean, + @ColumnInfo(name = "position") val position: Int, +) + +/** + * One lesson. [edits] is the corrections as JSON (`DiaryRowCodec`): they are + * only ever read back with their row, so a table of their own would buy a join + * for nothing. + */ +@Entity( + tableName = "diary_lesson", + indices = [Index(value = ["student_id", "date"])], +) +internal data class DiaryLessonEntity( + @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id") val rowId: Long = 0, + @ColumnInfo(name = "student_id") val studentId: Long, + @ColumnInfo(name = "date") val date: LocalDate, + @ColumnInfo(name = "number") val number: Int?, + @ColumnInfo(name = "subject") val subject: String, + @ColumnInfo(name = "starts_at") val startsAt: LocalTime?, + @ColumnInfo(name = "ends_at") val endsAt: LocalTime?, + @ColumnInfo(name = "room") val room: String?, + @ColumnInfo(name = "teacher") val teacher: String?, + @ColumnInfo(name = "homework") val homework: String?, + @ColumnInfo(name = "topic") val topic: String?, + @ColumnInfo(name = "target") val target: String, + @ColumnInfo(name = "edits") val edits: String, + @ColumnInfo(name = "ambiguous") val ambiguous: Boolean, + /** The order the server sent them in, which is the day's order. */ + @ColumnInfo(name = "position") val position: Int, +) + +@Entity( + tableName = "diary_homework", + indices = [Index(value = ["student_id", "due_date"])], +) +internal data class DiaryHomeworkEntity( + @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id") val rowId: Long = 0, + @ColumnInfo(name = "student_id") val studentId: Long, + @ColumnInfo(name = "due_date") val dueDate: LocalDate, + @ColumnInfo(name = "upstream_id") val upstreamId: Long?, + @ColumnInfo(name = "subject") val subject: String, + @ColumnInfo(name = "text") val text: String, + @ColumnInfo(name = "teacher") val teacher: String?, + @ColumnInfo(name = "target") val target: String, + @ColumnInfo(name = "edits") val edits: String, + @ColumnInfo(name = "ambiguous") val ambiguous: Boolean, + @ColumnInfo(name = "position") val position: Int, +) + +/** One register entry. [kind] is `DiaryMarkKind.name`, read back tolerantly. */ +@Entity( + tableName = "diary_mark", + indices = [Index(value = ["student_id"])], +) +internal data class DiaryMarkEntity( + @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id") val rowId: Long = 0, + @ColumnInfo(name = "student_id") val studentId: Long, + @ColumnInfo(name = "upstream_id") val upstreamId: Long?, + @ColumnInfo(name = "subject_id") val subjectId: Long?, + @ColumnInfo(name = "subject") val subject: String, + @ColumnInfo(name = "date") val date: LocalDate?, + @ColumnInfo(name = "value") val value: String, + @ColumnInfo(name = "kind") val kind: String, + @ColumnInfo(name = "reason") val reason: String?, + @ColumnInfo(name = "comment") val comment: String?, + @ColumnInfo(name = "position") val position: Int, +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImport.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImport.kt new file mode 100644 index 00000000..a69c747e --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImport.kt @@ -0,0 +1,121 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import kotlinx.coroutines.flow.Flow + +/** + * The steps of filling the phone with a diary account's first fortnight, in + * the order they run, each with its share of the progress bar. + * + * There is no registration step: the session is registered on the sign-in + * screen, whose failures need the form, and the import starts from the bearer + * that left behind. There is no «saving» step either — every step's answer is + * written as it arrives. + * + * @property weight the step's share of the bar; the weights sum to one. Rough + * costs, not measured ones: a week of «Сетевой город» is several upstream + * calls behind one of ours, and the list of pupils is one. + */ +enum class DiaryImportPhase(val weight: Float) { + STUDENTS(0.10f), + CHOOSE_STUDENT(0f), + PERIODS(0.10f), + SCHEDULE(0.30f), + HOMEWORK(0.25f), + MARKS(0.25f), +} + +/** + * What the import screen draws. + * + * Every state carries how much of the bar is done. [Running] also says where + * the step under way will leave it, so the bar can move toward [Running.target] + * while the request is out rather than sitting still and jumping. + */ +sealed interface DiaryImportProgress { + + /** The fraction of the bar that is done, `0..1`; it never goes backwards. */ + val completed: Float + + data class Running( + val phase: DiaryImportPhase, + override val completed: Float, + val target: Float, + ) : DiaryImportProgress + + /** The account sees several pupils and none was chosen before; the flow awaits `choose`. */ + data class ChoosingStudent( + val students: List, + override val completed: Float, + ) : DiaryImportProgress + + /** + * Finished. [skipped] names the steps that failed without stopping it — + * the terms, the homework, the marks — so the screen can say what is + * missing; their weeks stay «не загружено» in the cache rather than + * turning into an empty «нет заданий». + */ + data class Done( + val student: DiaryStudent, + val skipped: Set, + val lessons: Int, + val homework: Int, + val marks: Int, + ) : DiaryImportProgress { + override val completed: Float get() = 1f + } + + /** + * Stopped at [phase]. When [resumable], `run(resumeFrom = phase)` picks up + * there without repeating what already landed — after a re-sign-in, when + * [problem] is `ReauthRequired`. + */ + data class Failed( + val phase: DiaryImportPhase, + val problem: DiarySignInProblem, + val resumable: Boolean, + override val completed: Float, + ) : DiaryImportProgress +} + +/** + * Filling the cache from a registered diary session, and keeping the week in it + * current while the app is open. + * + * Both read through `DiaryRepository`, whose successful reads are the only + * thing that writes the cache — so what the import fetched and what the diary + * screen will ask for are the same requests, and the screen opens from the + * cache. Neither is called from the background: the sync worker and the widget + * never reach the diary (`SyncWorkerSourceTest`), because a read is what keeps + * the server's copy of the session alive and that has to mean somebody used the + * app. + */ +interface DiaryImport { + + /** + * The import, as a cold flow: nothing is asked until it is collected, one + * request is out at a time, and cancelling the collector cancels the + * request in flight. + * + * @param resumeFrom the step a [DiaryImportProgress.Failed] stopped at; the + * steps before it are not asked again. `null` starts from the beginning. + * @param choose asked only when the account sees several pupils and the + * stored choice is not one of them. + */ + fun run( + resumeFrom: DiaryImportPhase? = null, + choose: suspend (List) -> DiaryStudent, + ): Flow + + /** + * The foreground «activity»: when a session exists and the current week + * was last read more than [DiaryFreshFor] ago, reads this week and the next + * again (lessons and homework). `true` when it read anything. + * + * Answers `false` without asking while an import is running, so opening the + * app mid-import does not send every request twice. A failure is a + * [DiarySignInProblem]; the screen decides whether it is worth showing. + */ + suspend fun refreshIfStale(): Result +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportImpl.kt new file mode 100644 index 00000000..fdf33f89 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportImpl.kt @@ -0,0 +1,226 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.CHOOSE_STUDENT +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.HOMEWORK +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.MARKS +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.PERIODS +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.SCHEDULE +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.STUDENTS +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress.ChoosingStudent +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress.Done +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress.Failed +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress.Running +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryRepository +import com.lumenpearson.lessons.core.data.repository.DiarySessionStore +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import java.time.Clock +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.FlowCollector +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * [DiaryImport] over the repository, the stored session and the cache. + * + * It never writes the cache itself: every read goes through [repository], whose + * successful answers are written through. That is what keeps the import from + * being a second, subtly different client of the diary. + * + * What stops it and what does not: + * + * * the pupils and the lessons are the import — without them there is + * nothing to open — so their failure is [Failed]; + * * the terms, the homework and the marks are not: a failure there finishes + * with the step in `skipped`, and the screen asks again when it is opened; + * * but a dead session stops it wherever it happens, because every step after + * it would fail the same way, and each failure costs a request upstream. + */ +internal class DiaryImportImpl( + private val repository: DiaryRepository, + private val store: DiarySessionStore, + private val cache: DiaryCache, + private val clock: Clock = Clock.systemUTC(), +) : DiaryImport { + + /** Held for a whole import, so [refreshIfStale] can tell it would only repeat one. */ + private val running = Mutex() + + override fun run( + resumeFrom: DiaryImportPhase?, + choose: suspend (List) -> DiaryStudent, + ): Flow = flow { + running.withLock { import(resumeFrom, choose) } + } + + private suspend fun FlowCollector.import( + resumeFrom: DiaryImportPhase?, + choose: suspend (List) -> DiaryStudent, + ) { + var done = 0f + val skipped = linkedSetOf() + val start = resumeFrom ?: STUDENTS + + val session = store.currentDiarySession() + if (session == null) { + emit(Failed(start, DiarySignInProblem.SignInRequired, resumable = false, completed = done)) + return + } + val plan = DiaryImportPlan.of(DiaryWindows.today(session.target.zoneId(), clock)) + + // ---- STUDENTS: usually already here, from the registration's answer. + val cached = cache.students.first() + var students = cached.students + val ask = when { + students.isEmpty() -> true + start > STUDENTS -> false + resumeFrom == null -> !diaryIsFresh(cached.loadedAt, clock.instant()) + else -> true + } + if (ask) { + emit(Running(STUDENTS, done, done + STUDENTS.weight)) + students = repository.students().getOrElse { return fail(STUDENTS, it, done) } + } + done += STUDENTS.weight + if (students.isEmpty()) { + emit(Failed(STUDENTS, DiarySignInProblem.NoStudent, resumable = false, completed = done)) + return + } + + // ---- CHOOSE_STUDENT: the stored choice, the only pupil, or ask. + val stored = store.selectedStudentId.first() + val chosen = students.firstOrNull { it.id == stored } + ?: students.singleOrNull() + ?: run { + emit(ChoosingStudent(students, done)) + val picked = choose(students) + students.firstOrNull { it.id == picked.id } ?: picked + } + if (chosen.id != stored) { + try { + store.selectStudent(chosen.id) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + // A disk that refused the choice: not the network, and not + // worth reading as «нет сети». + val problem = DiarySignInProblem.Unexpected("the chosen pupil could not be stored", failure) + emit(Failed(CHOOSE_STUDENT, problem, resumable = true, completed = done)) + return + } + } + done += CHOOSE_STUDENT.weight + + // ---- PERIODS: only to cut the marks window the way the screen cuts it. + var current: DiaryPeriod? = null + if (start <= PERIODS) { + emit(Running(PERIODS, done, done + PERIODS.weight)) + repository.periods(chosen.id).fold( + onSuccess = { periods -> current = periods.firstOrNull { it.isCurrent } }, + onFailure = { failure -> + if (stops(failure)) return fail(PERIODS, failure, done) + skipped += PERIODS + }, + ) + } else { + current = cache.periods(chosen.id).first().periods.firstOrNull { it.isCurrent } + } + done += PERIODS.weight + + // ---- SCHEDULE: two whole weeks in one request. + var lessons = 0 + if (start <= SCHEDULE) { + emit(Running(SCHEDULE, done, done + SCHEDULE.weight)) + lessons = repository.schedule(chosen.id, plan.weeksFrom, plan.weeksTo) + .getOrElse { return fail(SCHEDULE, it, done) } + .size + } else { + lessons = plan.mondays.sumOf { cache.week(chosen.id, it).first().lessons.size } + } + done += SCHEDULE.weight + + // ---- HOMEWORK: the same two weeks; missing homework is not a failure. + var homework = 0 + if (start <= HOMEWORK) { + emit(Running(HOMEWORK, done, done + HOMEWORK.weight)) + repository.homework(chosen.id, plan.weeksFrom, plan.weeksTo).fold( + onSuccess = { homework = it.size }, + onFailure = { failure -> + if (stops(failure)) return fail(HOMEWORK, failure, done) + skipped += HOMEWORK + }, + ) + } else { + homework = plan.mondays.sumOf { cache.week(chosen.id, it).first().homework.size } + } + done += HOMEWORK.weight + + // ---- MARKS: the window the marks tab will ask for. + var marks = 0 + emit(Running(MARKS, done, done + MARKS.weight)) + val window = plan.marksWindow(current) + repository.grades(chosen.id, window.from, window.to).fold( + onSuccess = { marks = it.size }, + onFailure = { failure -> + if (stops(failure)) return fail(MARKS, failure, done) + skipped += MARKS + }, + ) + + emit(Done(chosen, skipped, lessons, homework, marks)) + } + + override suspend fun refreshIfStale(): Result { + if (!running.tryLock()) return Result.success(false) + try { + val session = store.currentDiarySession() ?: return Result.success(false) + val known = cache.students.first().students + val stored = store.selectedStudentId.first() + val studentId = known.firstOrNull { it.id == stored }?.id + ?: known.singleOrNull()?.id + // Nothing cached yet, but a choice was made: trust the choice. + ?: stored?.takeIf { known.isEmpty() } + ?: return Result.success(false) + val plan = DiaryImportPlan.of(DiaryWindows.today(session.target.zoneId(), clock)) + val week = cache.week(studentId, plan.weeksFrom).first() + if (diaryIsFresh(week.lessonsLoadedAt, clock.instant())) return Result.success(false) + + repository.schedule(studentId, plan.weeksFrom, plan.weeksTo).onFailure { + return Result.failure(DiarySignInProblem.of(it)) + } + repository.homework(studentId, plan.weeksFrom, plan.weeksTo).onFailure { + if (stops(it)) return Result.failure(DiarySignInProblem.of(it)) + } + return Result.success(true) + } finally { + running.unlock() + } + } + + private suspend fun FlowCollector.fail( + phase: DiaryImportPhase, + failure: Throwable, + done: Float, + ) { + val problem = DiarySignInProblem.of(failure) + emit(Failed(phase, problem, resumable = resumable(problem), completed = done)) + } + + /** A dead session ends the import wherever it is met; see the class note. */ + private fun stops(failure: Throwable): Boolean = when (DiarySignInProblem.of(failure)) { + DiarySignInProblem.ReauthRequired, DiarySignInProblem.SignInRequired -> true + else -> false + } + + /** + * Whether picking up at the failed step can work. Not after the bearer is + * gone — that is a new sign-in, and a new sign-in starts a new import — + * and not for an account with no pupil in it. + */ + private fun resumable(problem: DiarySignInProblem): Boolean = + problem != DiarySignInProblem.SignInRequired && problem != DiarySignInProblem.NoStudent +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlan.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlan.kt new file mode 100644 index 00000000..40664e31 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlan.kt @@ -0,0 +1,51 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import java.time.LocalDate + +/** + * Which days the import asks for, worked out from «today» and nothing else so + * it can be held by a test. + * + * **Weeks:** this week and the next, Monday to Sunday — two whole weeks, one + * request per resource, each a range the cache keeps + * ([DiaryWindows.isWholeWeeks]) and the week view asks for week by week. + * + * **Marks:** [DiaryWindows.gradeWindow] of the current term — the window the + * marks tab asks for, so it opens from the cache. That costs more upstream + * than four weeks would (about nine «Сетевой город» weeks for a long quarter), + * and it is the price of the tab not asking again the moment it is opened. + * + * Every span is inside `DiaryRepository.MAX_RANGE_DAYS`, so the repository's + * own range check never refuses what the import plans. + */ +data class DiaryImportPlan( + val today: LocalDate, + val weeksFrom: LocalDate, + val weeksTo: LocalDate, +) { + + /** The Mondays of the weeks the plan fetches. */ + val mondays: List + get() = generateSequence(weeksFrom) { it.plusWeeks(1) } + .takeWhile { !it.isAfter(weeksTo) } + .toList() + + /** The marks window once the current term is known — or not: `null` is «no term». */ + fun marksWindow(currentPeriod: DiaryPeriod?): DiaryDateRange = + DiaryWindows.gradeWindow(today, currentPeriod) + + companion object { + /** This week and the next. */ + const val WEEKS: Long = 2 + + fun of(today: LocalDate): DiaryImportPlan { + val monday = DiaryWindows.weekStart(today) + return DiaryImportPlan( + today = today, + weeksFrom = monday, + weeksTo = monday.plusWeeks(WEEKS).minusDays(1), + ) + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryWindows.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryWindows.kt new file mode 100644 index 00000000..af46f0c2 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryWindows.kt @@ -0,0 +1,88 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryRepository +import java.time.Clock +import java.time.DayOfWeek +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.temporal.TemporalAdjusters + +/** + * How long a read of the diary counts as current. + * + * One number for two decisions that have to agree: whether opening the app + * refreshes the week (`DiaryImport.refreshIfStale`, the only «activity» the + * phone performs — nothing reads the diary in the background), and whether the + * diary screen, seeded from the cache, asks again at all. Half an hour keeps an + * import that just finished from being repeated by the screen it lands on, and + * still means a family opening the app after lunch sees the afternoon's + * homework. + */ +val DiaryFreshFor: Duration = Duration.ofMinutes(30) + +/** Whether something read at [loadedAt] is still current at [now]; see [DiaryFreshFor]. */ +fun diaryIsFresh(loadedAt: Instant?, now: Instant): Boolean = + loadedAt != null && !loadedAt.isAfter(now) && Duration.between(loadedAt, now) < DiaryFreshFor + +/** A span of days, inclusive at both ends. */ +data class DiaryDateRange(val from: LocalDate, val to: LocalDate) + +/** + * The date arithmetic the diary screen and the import both ask, in one place. + * + * It has to be one place: the import fills the cache for the ranges the screen + * is about to ask for, and a range worked out twice is a range that will one + * day be worked out differently — a cache that is never hit, with nothing to + * say so. The screen's own helpers in `:app` delegate here. + */ +object DiaryWindows { + + /** + * The date it is where the diary is, not where the phone is. + * + * [zone] is the session's (`DiaryTarget.zoneId()`), which is the zone the + * server cuts the diary's days at, so a pupil in Tomsk and the server agree + * on which day is today. + */ + fun today(zone: ZoneId, clock: Clock = Clock.systemUTC()): LocalDate = + LocalDateTime.ofInstant(clock.instant(), zone).toLocalDate() + + /** Monday of the week [date] falls in; the week view's anchor and the cache's key. */ + fun weekStart(date: LocalDate): LocalDate = + date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) + + /** + * Whether [from] .. [to] is a run of whole Monday-to-Sunday weeks — the only + * ranges the cache keeps. A range cut anywhere else would stamp a week as + * fetched when only part of it was. + */ + fun isWholeWeeks(from: LocalDate, to: LocalDate): Boolean = + from.dayOfWeek == DayOfWeek.MONDAY && + to.dayOfWeek == DayOfWeek.SUNDAY && + !to.isBefore(from) + + /** + * The marks window: the current term, cut to what the server will answer. + * + * The server refuses anything wider than [DiaryRepository.MAX_RANGE_DAYS], + * and a quarter is routinely longer, so the rule is, in order: + * + * * end at today, or at the end of the term when it is already over — + * marks not yet given return nothing and say nothing; + * * start at the beginning of the term, when that fits; + * * otherwise start as far back as the limit allows, so what is shown is + * the latest part of the term rather than its first weeks. + */ + fun gradeWindow(today: LocalDate, period: DiaryPeriod? = null): DiaryDateRange { + val limit = DiaryRepository.MAX_RANGE_DAYS + val end = period?.endsOn?.takeIf { it.isBefore(today) } ?: today + val widest = end.minusDays(limit) + val start = period?.startsOn?.takeIf { it.isAfter(widest) } ?: widest + // A term whose start is somehow after its end cannot narrow anything. + return DiaryDateRange(from = minOf(start, end), to = end) + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/SeedingDiarySignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/SeedingDiarySignIn.kt new file mode 100644 index 00000000..018da0a5 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diary/SeedingDiarySignIn.kt @@ -0,0 +1,42 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryRegistration +import com.lumenpearson.lessons.core.data.repository.DiarySignIn +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession +import kotlinx.coroutines.CancellationException + +/** + * [DiarySignIn], with the pupils the registration answered written into the + * cache — which is what lets the import skip asking for them a second time + * seconds later (every pupil list is an upstream call behind ours). + * + * A decorator rather than a line inside the sign-in, so the sign-in keeps no + * idea that a cache exists: it already empties the cache through its + * `forgetLocal` hook when the account changes, and this runs after that, so + * the pupils land in a cache that belongs to the account that just signed in. + * The generation is taken after the registration returns for the same reason. + */ +internal class SeedingDiarySignIn( + private val delegate: DiarySignIn, + private val cache: DiaryCacheWriter, +) : DiarySignIn by delegate { + + override suspend fun register(upstream: UpstreamSession): Result = + delegate.register(upstream).also { seed(it) } + + override suspend fun signIn(target: DiaryTarget, password: String): Result = + delegate.signIn(target, password).also { seed(it) } + + private suspend fun seed(result: Result) { + val students = result.getOrNull()?.students?.takeIf { it.isNotEmpty() } ?: return + try { + cache.putStudents(cache.generation(), students) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // The sign-in succeeded; a cache that could not take the list only + // costs the import one request. + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt index 3764a5a5..bbdb294f 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptor.kt @@ -31,9 +31,17 @@ internal class AuthInterceptor( // [DiaryAuthInterceptor] is what signs those calls. The class token on // a diary request would be answered with a 401 that means nothing the // user could act on. + // + // The school directory is excluded for another reason: it is + // anonymous, asked on the first screen by a phone that may be in no + // class, and a phone that is in one has no business telling the server + // which class is searching for which school. Its paths are matched as a + // prefix, not by suffix like the three above, so that a second + // directory call cannot arrive signed because nobody listed it. val path = request.url.encodedPath val needsAuth = UNAUTHENTICATED_SUFFIXES.none { path.endsWith(it) } && - !path.contains(DiaryAuthInterceptor.DIARY_PATH_PREFIX) + !path.contains(DiaryAuthInterceptor.DIARY_PATH_PREFIX) && + !path.contains(DIRECTORY_PATH_PREFIX) if (!needsAuth || request.header(HEADER) != null) { return chain.proceed(request) } @@ -48,8 +56,11 @@ internal class AuthInterceptor( ) } - private companion object { + internal companion object { const val HEADER = "Authorization" + + /** `GET /api/v1/directory/school-regions` and whatever joins it; see above. */ + const val DIRECTORY_PATH_PREFIX = "/api/v1/directory/" // `/warmup` joins the two: it is the about page's server badge, and it // is asked before this device has joined anything at all. val UNAUTHENTICATED_SUFFIXES = listOf("/join", "/health", "/warmup") diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt index a81cdb3e..1795dd7a 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt @@ -3,13 +3,14 @@ package com.lumenpearson.lessons.core.data.network import com.lumenpearson.lessons.core.data.network.dto.DiaryAttendanceDto import com.lumenpearson.lessons.core.data.network.dto.DiaryHomeworkDto import com.lumenpearson.lessons.core.data.network.dto.DiaryLessonDto -import com.lumenpearson.lessons.core.data.network.dto.DiaryLoginRequestDto -import com.lumenpearson.lessons.core.data.network.dto.DiaryLoginResponseDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryCapabilitiesDto import com.lumenpearson.lessons.core.data.network.dto.DiaryMarkDto import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideDto import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideRequestDto import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto import com.lumenpearson.lessons.core.data.network.dto.DiaryResetRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionResponseDto import com.lumenpearson.lessons.core.data.network.dto.DiaryStudentDto import com.lumenpearson.lessons.core.data.network.dto.DiarySubjectDto import com.lumenpearson.lessons.core.data.network.dto.DiaryTeacherDto @@ -22,7 +23,8 @@ import retrofit2.http.Path import retrofit2.http.Query /** - * The Petersburg diary, as this server publishes it: `/api/v1/diary`. + * The diary, as this server publishes it: `/api/v1/diary`, for Petersburg and + * «Сетевой город» alike. * * Its own interface rather than more methods on [LessonsApi] because it is its * own thing — one family's account in a foreign service, not the class @@ -33,22 +35,41 @@ import retrofit2.http.Query * Paths are relative, as in [LessonsApi], so a base URL with a path prefix * behind a reverse proxy keeps working. * - * Every call but [login] answers `401` when the session is gone, and `401` - * carrying `X-Diary-Reauth: required` when it is the *upstream* session that - * died and the password has to be asked for again. Nothing here decides which: - * `DiaryFailure.of` reads the response and the screen reacts to the type. + * Every call but [capabilities] and [registerSession] answers `401` when the + * session is gone, and `401` carrying `X-Diary-Reauth: required` when it is the + * *upstream* session that died and the password has to be asked for again. + * Nothing here decides which: `DiaryFailure.of` reads the response and the + * screen reacts to the type. + * + * `POST /login`, which took the password itself, is deliberately absent. The + * endpoint is still served for older builds; this one signs in with the diary + * directly (`upstream/`) and hands over only the session it was given, so the + * password never reaches our server. Leaving the method out is what makes that + * a fact of the build rather than a promise about its callers. */ internal interface DiaryApi { /** - * Signs in to the diary. The password is used for this one call; neither - * this app nor the server stores it. + * What this server's diary can do: whether it runs at all, and which + * «Сетевой город» regions it keeps sessions for. Anonymous and cheap, + * asked before a password field is enabled. `404` from a server that + * predates registration. + */ + @GET("api/v1/diary/capabilities") + suspend fun capabilities(): DiaryCapabilitiesDto + + /** + * Hands over a session the phone opened with the diary, for one of ours. * - * `401` here means the credentials were refused — a different thing from a - * `401` on any other call, which means our own session is no longer good. + * Anonymous — see `DiaryAuthInterceptor`, which keeps a stale bearer off + * it — and throttled together with `/login`. `409` means the diary would + * not take the session from our server's address, which is not the + * password and not worth an automatic retry; `403` means the account has no + * pupil; `422` means the body was refused before anything was asked + * upstream, which only a bug in this app produces. */ - @POST("api/v1/diary/login") - suspend fun login(@Body body: DiaryLoginRequestDto): DiaryLoginResponseDto + @POST("api/v1/diary/session") + suspend fun registerSession(@Body body: DiarySessionRequestDto): DiarySessionResponseDto /** Forgets the session on the server; answers 204 with no body. */ @POST("api/v1/diary/logout") diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt index 29d10a03..2f1c994b 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptor.kt @@ -32,11 +32,14 @@ internal class DiaryAuthInterceptor( val request = chain.request() val path = request.url.encodedPath - // `/login` is the call that creates the token, so it cannot carry one; - // a stale bearer on it would be ignored by the server anyway, and not - // sending it keeps a dead session out of the one request that is - // supposed to replace it. - val mine = path.contains(DIARY_PATH_PREFIX) && !path.endsWith(LOGIN_SUFFIX) + // `/login` and `/session` are the calls that mint the token, so they + // cannot carry one: a stale bearer riding the request that is meant to + // replace it is a dead session sent along for nothing, and a family + // signing in to a second account would hand the server the first + // one's. `/capabilities` is asked before anybody is signed in and says + // the same thing to everyone. All three are anonymous on the server. + val mine = path.contains(DIARY_PATH_PREFIX) && + ANONYMOUS_SUFFIXES.none { path.endsWith(it) } if (!mine || request.header(HEADER) != null) { return chain.proceed(request) } @@ -61,6 +64,13 @@ internal class DiaryAuthInterceptor( */ const val DIARY_PATH_PREFIX = "/api/v1/diary" - const val LOGIN_SUFFIX = "/diary/login" + /** + * `/login` stays in the list although this build never calls it: the + * rule is about what the server treats as anonymous, and a list that + * matched the app's calls rather than the server's routes would be + * wrong again the day somebody calls it for a test. + */ + val ANONYMOUS_SUFFIXES: List = + listOf("/diary/login", "/diary/session", "/diary/capabilities") } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt new file mode 100644 index 00000000..900500cd --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DirectoryApi.kt @@ -0,0 +1,62 @@ +package com.lumenpearson.lessons.core.data.network + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import retrofit2.http.GET +import retrofit2.http.Query + +/** + * The school directory (`server/app/api/directory.py`): «which regions is a + * school of this name in», for a phone that is in no class and signed in to + * nothing. + * + * Anonymous, and kept so on purpose. `AuthInterceptor` skips every path under + * `/api/v1/directory/`, so a phone that *is* in a class does not tell the + * server which class is looking for which school, and `DiaryAuthInterceptor` + * signs only `/api/v1/diary`. The server counts every call against the caller + * and spends a shared daily allowance on it, so the phone asks on submit or + * after a pause in typing, never per keystroke — see `SchoolDirectory`. + */ +internal interface DirectoryApi { + + /** + * `200` with the regions, best-ranked first; `422` for a query under three + * characters; `429` + `Retry-After`; `503` with [UNAVAILABLE_HEADER]. + */ + @GET("api/v1/directory/school-regions") + suspend fun schoolRegions(@Query("q") query: String): SchoolRegionsDto + + companion object { + /** + * Every directory `503` carries it: `disabled` (no directory key on + * this server), `spent` (today's anonymous allowance is gone; comes with + * `Retry-After`) or `upstream` (the directory itself failed). + */ + const val UNAVAILABLE_HEADER = "X-Directory-Unavailable" + } +} + +/** `SchoolRegionsOut` in `server/app/schemas.py`. */ +@Serializable +internal data class SchoolRegionsDto( + @SerialName("query") val query: String = "", + @SerialName("regions") val regions: List = emptyList(), + @SerialName("truncated") val truncated: Boolean = false, + @SerialName("generic") val generic: Boolean = false, +) + +/** + * `SchoolRegionOut`: one region the search placed schools in. + * + * @property region the catalog's key, or `null` for a region the server's + * catalog could not place — then [label] is the directory's own name for it. + */ +@Serializable +internal data class SchoolRegionDto( + @SerialName("region") val region: String? = null, + @SerialName("code") val code: String? = null, + @SerialName("label") val label: String? = null, + @SerialName("schools") val schools: Int = 0, + @SerialName("cities") val cities: List = emptyList(), + @SerialName("examples") val examples: List = emptyList(), +) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt index 684430b1..b223053f 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/NetworkModule.kt @@ -13,7 +13,7 @@ import retrofit2.converter.kotlinx.serialization.asConverterFactory * There is no DI framework in this app (see `di.Graph` for why), so this object * is the factory: [DefaultLessonsContainer][com.lumenpearson.lessons.core.data.di.DefaultLessonsContainer] * calls [apis] once and everything else takes the resulting [LessonsApi], - * [DiaryApi] and [ManageApi]. + * [DiaryApi], [ManageApi] and [DirectoryApi]. */ internal object NetworkModule { @@ -91,10 +91,10 @@ internal object NetworkModule { .build() /** - * The stack every call site shares: one client, one Retrofit, three APIs. + * The stack every call site shares: one client, one Retrofit, four APIs. * - * Built as one object rather than through three factories because the - * client is the expensive part and all three interfaces want the same one — + * Built as one object rather than through four factories because the + * client is the expensive part and all four interfaces want the same one — * the same pool, the same timeouts and the same base-URL rewrite. */ fun apis( @@ -110,6 +110,7 @@ internal object NetworkModule { lessons = retrofit.create(LessonsApi::class.java), diary = retrofit.create(DiaryApi::class.java), manage = retrofit.create(ManageApi::class.java), + directory = retrofit.create(DirectoryApi::class.java), ) } @@ -118,8 +119,15 @@ internal object NetworkModule { * `/api/v1/manage` is signed by the ordinary class token like the rest of * [LessonsApi], and the role behind that token is looked up per request on * the server. + * @property directory the anonymous school directory. The same client, and + * no bearer: [AuthInterceptor] skips its paths by prefix. * * @see apis */ - data class Apis(val lessons: LessonsApi, val diary: DiaryApi, val manage: ManageApi) + data class Apis( + val lessons: LessonsApi, + val diary: DiaryApi, + val manage: ManageApi, + val directory: DirectoryApi, + ) } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt index 1aecf253..5d4764c5 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryDto.kt @@ -2,6 +2,7 @@ package com.lumenpearson.lessons.core.data.network.dto import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject /** * The wire shapes of `/api/v1/diary`, mirroring every `Diary*` model in @@ -18,24 +19,114 @@ import kotlinx.serialization.Serializable * register entry must not stop an older build from showing the other five. */ -/** `POST /login` — used once and never stored; see [DiaryLoginResponseDto]. */ +/** + * `POST /session`: a session the phone opened with the diary itself, handed + * over so our server can keep reading with it. Mirrors `DiarySessionBody`. + * + * There is no password field, and there is nowhere to put one: the server + * refuses any key it does not know with a `422` (`extra="forbid"`), so a + * password could not be sent here even by mistake. The app stopped calling + * `POST /login`, which is the only endpoint that ever took one. + * + * [credential] is the provider's own shape — [PetersburgCredentialDto] or + * [NetSchoolCredentialDto] as JSON — because the server tells the two bodies + * apart by [provider] and validates each half separately. [region] and + * [schoolId] are left out of the JSON when `null` (the app's `Json` drops + * nulls): Petersburg's half of the union has no such fields, and a `null` + * there would be a key the server forbids. + * + * A plain class with a redacted [toString], not a data class: a data class + * prints every field, and one of these is a live session. + */ @Serializable -internal data class DiaryLoginRequestDto( +internal class DiarySessionRequestDto( + @SerialName("provider") val provider: String, @SerialName("login") val login: String, - @SerialName("password") val password: String, + @SerialName("region") val region: String? = null, + @SerialName("school_id") val schoolId: Long? = null, + @SerialName("credential") val credential: JsonObject, +) { + override fun toString(): String = "DiarySessionRequestDto($provider, $region, )" +} + +/** Petersburg's half of [DiarySessionRequestDto.credential]: its `X-JWT-Token`. */ +@Serializable +internal class PetersburgCredentialDto( + @SerialName("token") val token: String, ) /** - * Mirrors `DiaryLoginOut`. + * «Сетевой город»'s half: the `at` bearer, the two session cookies, and the + * two fields the server's own sign-in keeps beside them. `null`s are dropped on + * the way out, which is what the server's `exclude_none` stores anyway. + */ +@Serializable +internal class NetSchoolCredentialDto( + @SerialName("at") val at: String, + @SerialName("cookies") val cookies: NetSchoolCookiesDto, + @SerialName("ver") val ver: String? = null, + @SerialName("time_out") val timeOut: Long? = null, +) + +/** + * The only two cookie names the server takes; any other is a `422`, because + * it would be sent upstream on every read. + */ +@Serializable +internal class NetSchoolCookiesDto( + @SerialName("NSSESSIONID") val session: String, + @SerialName("ESRNSec") val security: String? = null, +) + +/** + * Mirrors `DiarySessionOut`: our bearer for the registered session, and what + * the phone needs to keep reading it — never the upstream credential, which + * stays sealed on the server. * - * The password is deliberately absent from the answer: the server keeps only - * the session it opened upstream, which is the whole reason a dead session - * comes back as `401` + `X-Diary-Reauth: required` rather than being refreshed. + * [zone] is the zone the server cuts this diary's days at, so the phone's + * «today» is the server's. [students] saves the import one round trip: the + * validating read already fetched them. */ @Serializable -internal data class DiaryLoginResponseDto( +internal data class DiarySessionResponseDto( @SerialName("token") val token: String, @SerialName("login") val login: String = "", + @SerialName("provider") val provider: String = "", + @SerialName("region") val region: String? = null, + @SerialName("school_id") val schoolId: Long? = null, + @SerialName("school_name") val schoolName: String? = null, + @SerialName("zone") val zone: String? = null, + @SerialName("students") val students: List = emptyList(), +) { + override fun toString(): String = "DiarySessionResponseDto($provider, $region, )" +} + +/** + * Mirrors `DiaryCapabilitiesOut`: asked before a password is taken, so a + * server that cannot keep the session is found out before anything is sent to + * a diary. A server from before registration answers `404` instead. + */ +@Serializable +internal data class DiaryCapabilitiesDto( + @SerialName("enabled") val enabled: Boolean = false, + @SerialName("registration") val registration: Boolean = false, + @SerialName("providers") val providers: DiaryProvidersDto = DiaryProvidersDto(), +) + +/** + * Mirrors `DiaryProvidersOut`. [petersburg] is an empty object today; its + * presence is what says the server serves Petersburg at all. + */ +@Serializable +internal data class DiaryProvidersDto( + @SerialName("petersburg") val petersburg: JsonObject? = null, + @SerialName("netschool") val netschool: NetSchoolCapabilitiesDto? = null, +) + +/** Mirrors `NetSchoolCapabilitiesOut`: the allow-list keys this server signs in to. */ +@Serializable +internal data class NetSchoolCapabilitiesDto( + @SerialName("regions") val regions: List = emptyList(), ) /** Mirrors `DiaryStudentOut`: one child this account may see. */ diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt index 71ed6e45..2d0e7c63 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinDto.kt @@ -1,5 +1,7 @@ package com.lumenpearson.lessons.core.data.network.dto +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -28,8 +30,36 @@ internal data class JoinResponseDto( @SerialName("class_id") val classId: Long, @SerialName("class_name") val className: String, @SerialName("school") val school: String? = null, + /** `DiaryBindingOut`; absent from a server older than bindings, and for a class with none. */ + @SerialName("diary") val diary: DiaryBindingDto? = null, ) +/** + * `DiaryBindingOut` in `server/app/schemas.py`: which diary the class reads. + * + * Every field defaults, so a binding a newer server shapes differently costs + * the binding and never the join — [toDomain] turns anything it cannot stand + * behind into no binding. + */ +@Serializable +internal data class DiaryBindingDto( + @SerialName("provider") val provider: String = "", + @SerialName("region") val region: String? = null, + @SerialName("school_id") val schoolId: Long? = null, + @SerialName("school_name") val schoolName: String? = null, +) { + /** `null` for a provider this build does not know, never a guess. */ + fun toDomain(): DiaryBinding? { + val key = DiaryProviderKey.fromWire(provider) ?: return null + return DiaryBinding( + provider = key, + region = region?.trim()?.ifBlank { null }, + schoolId = schoolId, + schoolName = schoolName?.trim()?.ifBlank { null }, + ) + } +} + /** * Response of `GET /api/v1/health`. * diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryBinding.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryBinding.kt new file mode 100644 index 00000000..811fa30b --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryBinding.kt @@ -0,0 +1,49 @@ +package com.lumenpearson.lessons.core.data.repository + +/** + * Which diary a class reads, as the join told this phone — so a family that + * joined by code can sign in to their diary without searching for their + * school. + * + * It rides the join's answer and nothing else (`JoinResponse.diary`): the + * server built it through its own allow-list, so a class bound to a region the + * server cannot reach, one that takes no password, or a «Сетевой город» + * binding without a school arrives as no binding at all. A phone that joined + * before bindings existed holds none until it joins again, which costs it the + * prefill and nothing else. + * + * @property region the catalog's key; `null` for Petersburg. + * @property schoolId the upstream's own school id; `null` for Petersburg. + */ +data class DiaryBinding( + val provider: DiaryProviderKey, + val region: String?, + val schoolId: Long?, + val schoolName: String?, +) { + + /** + * The sign-in target for [login] at this binding, or `null` when a + * «Сетевой город» binding is missing the region or the school it cannot + * sign in without. The zone is a placeholder until registration answers + * with the server's own, which is what gets stored. + */ + fun targetFor(login: String): DiaryTarget? = when (provider) { + DiaryProviderKey.PETERSBURG -> DiaryTarget.petersburg(login) + DiaryProviderKey.NETSCHOOL -> { + val region = region?.takeIf { it.isNotBlank() } + val school = schoolId + if (region == null || school == null) { + null + } else { + DiaryTarget( + provider = provider, + region = region, + schoolId = school, + schoolName = schoolName, + login = login, + ) + } + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryModels.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryModels.kt index 1be936f7..1bf8b829 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryModels.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryModels.kt @@ -19,15 +19,38 @@ import retrofit2.HttpException * * [token] is this server's own bearer, not the upstream's, and it is separate * from the class device token in [Session] — a phone may hold either, both or - * neither. [login] is kept only so the re-authentication prompt can say whose + * neither. [login] is kept so the re-authentication prompt can say whose * password it is asking for; the password itself is stored nowhere, here or on * the server. + * + * [target] says which diary, region and school the session is in, so that + * re-authentication signs in to the same one rather than to whatever the form + * defaults to. A session stored before there was a second diary has none on + * disk and reads as Petersburg, which is the only place it can have been. */ data class DiarySession( val login: String, val token: String, + val target: DiaryTarget = DiaryTarget.petersburg(login), ) +/** + * What a registration hands back: the session now stored, and the pupils the + * server's validating read already fetched — so the import that follows does + * not ask for them again straight away. + */ +data class DiaryRegistration( + val session: DiarySession, + val students: List, +) + +/** + * How long a session nobody uses survives on the server before the cron purges + * it (`cron.DIARY_SESSION_TTL`). The screens say it out loud; the shared + * vectors (`session.idle_days`) hold this number and the server's to one value. + */ +const val DiarySessionIdleDays: Long = 30 + /** * One pupil the account may see. * @@ -321,9 +344,33 @@ sealed class DiaryFailure(message: String, cause: Throwable? = null) : /** `502`: the diary answered something the server could not read. */ data object Unreadable : DiaryFailure("The diary answered in an unreadable way") - /** `503`: the diary is down. Worth retrying, and only that. */ + /** + * `503` with `X-Diary-Unavailable: upstream`, a bare `503`, or a `504` — + * the diary is down, or the platform gave up waiting for it. Worth + * retrying, and only that. + */ data object Unavailable : DiaryFailure("The diary is not answering") + /** + * `503` with `X-Diary-Unavailable: disabled`: the server has no + * `DIARY_SECRET`, so its diary is off. Nothing anybody types will help; + * whoever runs the server has to switch it on. + */ + data object Disabled : DiaryFailure("The diary is switched off on this server") + + /** + * `503` with `X-Diary-Unavailable: address-refused`: the diary will not talk + * to our server's address. Not the password and not worth retrying. + */ + data object ServerAddressRefused : DiaryFailure("The diary refuses the server's address") + + /** + * `429`: too many sign-in attempts from here. [retryAfterSeconds] is the + * server's `Retry-After`, when it sent one a number could be read from. + */ + data class Throttled(val retryAfterSeconds: Long?) : + DiaryFailure("Too many diary sign-in attempts") + /** No answer at all: no network, wrong address, a timeout. */ data class Offline(val reason: Throwable) : DiaryFailure("Could not reach the server", reason) @@ -337,6 +384,13 @@ sealed class DiaryFailure(message: String, cause: Throwable? = null) : /** The header that separates "sign in" from "type your password again". */ const val REAUTH_HEADER = "X-Diary-Reauth" + /** + * The header that says which of three things a diary `503` is — + * `disabled`, `address-refused` or `upstream` — so the app can tell + * them apart without reading the Russian in `detail`. + */ + const val UNAVAILABLE_HEADER = "X-Diary-Unavailable" + /** * Classifies whatever a call threw. * @@ -379,9 +433,33 @@ sealed class DiaryFailure(message: String, cause: Throwable? = null) : 404 -> UnknownStudent 422 -> unprocessable + // «Слишком много попыток», not «Не получилось: 429»: the server + // said exactly what was wrong and how long to wait (#153). + 429 -> Throttled(retryAfterSeconds(failure)) 502 -> Unreadable - 503 -> Unavailable + // The header, not the Russian: «выключен на сервере» and «дневник + // не отвечает» are both 503s and ask for different things (#153). + 503 -> when (unavailableReason(failure)) { + "disabled" -> Disabled + "address-refused" -> ServerAddressRefused + else -> Unavailable + } + // The platform's own ceiling (Vercel answers 504 at 30 s): the diary + // was slow, not wrong, so it is worth another try (#153). + 504 -> Unavailable else -> Unexpected(code = failure.code(), reason = failure) } + + private fun unavailableReason(failure: HttpException): String? = + failure.response()?.headers()?.get(UNAVAILABLE_HEADER)?.trim()?.lowercase() + + /** + * `Retry-After` in seconds, or `null`. Only the delta-seconds form: the + * server sends nothing else, and an HTTP date would need a clock this + * function does not have. + */ + internal fun retryAfterSeconds(failure: HttpException): Long? = + failure.response()?.headers()?.get("Retry-After")?.trim()?.toLongOrNull() + ?.takeIf { it >= 0 } } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt index a8ca34bf..785461fa 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt @@ -4,7 +4,7 @@ import java.time.LocalDate import kotlinx.coroutines.flow.Flow /** - * The family's account in the Petersburg diary. + * The family's account in a diary — Petersburg's or a «Сетевой город» region's. * * Deliberately not part of [SessionRepository]. The two sessions are * independent in both directions — a phone can be in a class without a diary @@ -13,8 +13,9 @@ import kotlinx.coroutines.flow.Flow * does not touch the other. Two repositories is how that stays true when * somebody later adds a sign-out to either. * - * Every call returns [Result] like [SessionRepository.join] does, but the - * failure inside it is always a [DiaryFailure]: the screens have a different + * Every call returns [Result] like [SessionRepository.join] does, and the + * failure inside it is a [DiaryFailure] — [signIn]'s alone is a + * [DiarySignInProblem], see there. The screens have a different * thing to do about each answer, and * [ReauthRequired][DiaryFailure.ReauthRequired] in particular has to be * recognisable without reading a message. @@ -24,24 +25,32 @@ interface DiaryRepository { /** `null` means "not signed in to the diary"; the section switches on it. */ val session: Flow + /** + * Which diary this phone signs in to, whether or not the session is alive: + * it outlives a bare `401`, so the sign-in that follows one is to the same + * diary, region and school rather than to a blank form. + */ + val target: Flow + /** One-shot read, for a screen that needs the login before its first frame. */ suspend fun current(): DiarySession? /** - * Exchanges credentials for a session and stores it. - * - * The password is passed straight through to the one call that needs it and - * is never written anywhere — not by this app, and not by the server, which - * is why an expired upstream session ends in - * [DiaryFailure.ReauthRequired] rather than in a silent refresh. + * Signs in to [target]'s diary on the phone, registers the session with the + * server and stores our bearer — [DiarySignIn.signIn], for the screens that + * hold nothing between the steps: Settings → Дневник and re-authentication, + * which passes the stored session's target so only the password is typed. * - * A refused password comes back as [DiaryFailure.SignInRequired]: on this - * call, and only on this call, that means "wrong login or password". + * The password goes to the diary's own server and nowhere else: not to + * ours, not to disk. The failure inside the [Result] is a + * [DiarySignInProblem], not a [DiaryFailure] — a sign-in has more ways to + * fail than a read, and the screens say one sentence per way. */ - suspend fun signIn(login: String, password: String): Result + suspend fun signIn(target: DiaryTarget, password: String): Result /** - * Forgets the diary session, here and on the server. + * Forgets the diary session, here and on the server — the bearer, the + * target, the chosen pupil and whatever was kept offline for the account. * * The local half happens even when the server cannot be reached: a user who * asked to be signed out must not stay signed in because the network was diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryImpl.kt index ba920c6d..0aa00156 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryImpl.kt @@ -1,7 +1,7 @@ package com.lumenpearson.lessons.core.data.repository +import com.lumenpearson.lessons.core.data.diary.DiaryCacheWriter import com.lumenpearson.lessons.core.data.network.DiaryApi -import com.lumenpearson.lessons.core.data.network.dto.DiaryLoginRequestDto import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideRequestDto import com.lumenpearson.lessons.core.data.network.dto.DiaryResetRequestDto import java.time.LocalDate @@ -16,15 +16,39 @@ import kotlinx.coroutines.withContext * * An interface with one production implementation — `LessonsPreferences` — so * that the repository can be exercised without DataStore, and so that the only - * thing this repository is allowed to do to storage is written down in four - * methods. It cannot reach the class token from here, which is the mechanical - * half of "signing out of one does not touch the other". + * thing this repository is allowed to do to storage is written down here. It + * cannot reach the class token from here, which is the mechanical half of + * "signing out of one does not touch the other". + * + * Two ways to let go, because a session and the account it belongs to die at + * different times: [clearDiaryToken] is a bare `401` — our bearer is dead, but + * which diary, region, school and login this phone uses is not, so the next + * screen asks for the same account's password instead of starting over — + * and [forgetDiary] is signing out, which forgets all of it. */ internal interface DiarySessionStore { val diarySession: Flow suspend fun currentDiarySession(): DiarySession? + + /** Our bearer, the login and the target, written together. */ suspend fun writeDiarySession(value: DiarySession) - suspend fun clearDiarySession() + + /** The bearer only; the target and the login stay. */ + suspend fun clearDiaryToken() + + /** The bearer, the login, the target and the chosen pupil. */ + suspend fun forgetDiary() + + /** + * Which diary this phone signs in to, with or without a live bearer: it + * outlives a bare `401` and ends only at [forgetDiary]. + */ + val diaryTarget: Flow + suspend fun currentDiaryTarget(): DiaryTarget? + + /** The pupil the diary shows, when the account has several. */ + val selectedStudentId: Flow + suspend fun selectStudent(id: Long?) } /** @@ -33,48 +57,58 @@ internal interface DiarySessionStore { * * Two behaviours are worth knowing about: * - * * a `401` that is *not* a re-auth request clears the stored session. The + * * a `401` that is *not* a re-auth request clears the stored bearer. The * token is demonstrably dead — the server has just refused it — and leaving * it in place would leave the app on a screen it cannot load, with a sign-in - * button the user has no reason to press; + * button the user has no reason to press. The [DiaryTarget] stays, so the + * sign-in that follows is to the same diary and the same account; * * a `401` that *is* a re-auth request leaves it alone. The session is still * ours, only the upstream half expired, and the login in it is what the * password prompt is about to ask for. + * + * Signing in is [DiarySignIn]'s: this class only hands it the target and the + * password and reports the session it stored. + * + * And it is the one writer of the offline diary: every read that succeeds is + * written through to [cache] — the pupils, the terms, the marks window asked + * for, and lessons and homework when the range is whole Monday-to-Sunday weeks + * (any other range passes through uncached, because stamping a week fetched + * when only part of it was would draw its missing days as empty). The import + * reads through here too, so the cache only ever holds what a screen asking + * the same question would have been answered. */ internal class DiaryRepositoryImpl( private val api: DiaryApi, private val store: DiarySessionStore, + private val diarySignIn: DiarySignIn, + private val forgetLocal: suspend () -> Unit = {}, + private val cache: DiaryCacheWriter = DiaryCacheWriter.None, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ) : DiaryRepository { override val session: Flow = store.diarySession + override val target: Flow = store.diaryTarget + override suspend fun current(): DiarySession? = withContext(ioDispatcher) { store.currentDiarySession() } - override suspend fun signIn(login: String, password: String): Result = - call(clearOnSignInRequired = false) { - val response = api.login( - DiaryLoginRequestDto(login = login.trim(), password = password), - ) - val opened = DiarySession( - // The server echoes the login it accepted; falling back to what - // was typed keeps the prompt honest if it ever stops. - login = response.login.trim().ifBlank { login.trim() }, - token = response.token, - ) - store.writeDiarySession(opened) - opened - } + override suspend fun signIn(target: DiaryTarget, password: String): Result = + diarySignIn.signIn(target, password).map { it.session } override suspend fun signOut(): Result = withContext(ioDispatcher) { // Best effort, and deliberately ignored: the server forgetting its row - // is good hygiene, but the user asked to be signed out of this phone - // and a dead network is not a reason to refuse. + // (and saying goodbye upstream, for «Сетевой город») is good hygiene, + // but the user asked to be signed out of this phone and a dead network + // is not a reason to refuse. runCatching { api.logout() } try { - store.clearDiarySession() + store.forgetDiary() + // After the store, so a disk that refuses the first write is the + // failure reported, and nothing is emptied under a session that + // is still there. + forgetLocal() Result.success(Unit) } catch (cancellation: CancellationException) { throw cancellation @@ -83,44 +117,61 @@ internal class DiaryRepositoryImpl( } } - override suspend fun students(): Result> = call { - api.students().map { it.toDomain() } - } + override suspend fun students(): Result> = remembered( + read = { call { api.students().map { it.toDomain() } } }, + write = { generation, rows -> cache.putStudents(generation, rows) }, + ) override suspend fun schedule( studentId: Long, from: LocalDate, to: LocalDate, - ): Result> = ranged(from, to) { - api.schedule(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } - } + ): Result> = remembered( + read = { + ranged(from, to) { + api.schedule(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } + } + }, + write = { generation, rows -> cache.putLessons(generation, studentId, from, to, rows) }, + ) override suspend fun homework( studentId: Long, from: LocalDate, to: LocalDate, - ): Result> = ranged(from, to) { - api.homework(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } - } + ): Result> = remembered( + read = { + ranged(from, to) { + api.homework(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } + } + }, + write = { generation, rows -> cache.putHomework(generation, studentId, from, to, rows) }, + ) override suspend fun grades( studentId: Long, from: LocalDate, to: LocalDate, - ): Result> = ranged(from, to) { - api.grades(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } - } + ): Result> = remembered( + read = { + ranged(from, to) { + api.grades(studentId, from.toString(), to.toString()).mapNotNull { it.toDomain() } + } + }, + write = { generation, rows -> cache.putMarks(generation, studentId, from, to, rows) }, + ) - override suspend fun periods(studentId: Long): Result> = call { - api.periods(studentId).map { it.toDomain() } - } + override suspend fun periods(studentId: Long): Result> = remembered( + read = { call { api.periods(studentId).map { it.toDomain() } } }, + write = { generation, rows -> cache.putPeriods(generation, studentId, rows) }, + ) override suspend fun overrides(studentId: Long): Result> = call { api.overrides(studentId).mapNotNull { it.toDomain() } } - // The three writes below leave `clearOnSignInRequired` at true, like every - // read, and that is a decision rather than the default going unexamined. + // The three writes below drop the token on a bare `401`, like every read, + // and that is a decision rather than the rule going unexamined. // // A `401` without the re-auth header means the server has just refused this // token: it is dead for writing and for reading alike, and the correction @@ -179,6 +230,33 @@ internal class DiaryRepositoryImpl( api.resetOverrides(studentId) } + /** + * [read], and on success its answer written through to the cache. + * + * The generation is taken **before** the request, so an answer that lands + * after a sign-out — or after another account signed in — is dropped by + * the cache rather than written under the wrong account. The write is + * guarded: a disk that will not take it costs the offline copy, never the + * answer the screen asked for. + */ + private suspend fun remembered( + read: suspend () -> Result, + write: suspend (generation: Long, value: T) -> Unit, + ): Result { + val generation = cache.generation() + val result = read() + result.onSuccess { value -> + try { + write(generation, value) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // See above: the read stands, the copy is lost. + } + } + return result + } + /** [call], with the server's own range rule applied before the round trip. */ private suspend fun ranged( from: LocalDate, @@ -199,7 +277,6 @@ internal class DiaryRepositoryImpl( * field the server will not file, and nothing but the endpoint says so. */ private suspend fun call( - clearOnSignInRequired: Boolean = true, unprocessable: DiaryFailure = DiaryFailure.BadRange, block: suspend () -> T, ): Result = withContext(ioDispatcher) { @@ -209,7 +286,7 @@ internal class DiaryRepositoryImpl( throw cancellation } catch (failure: Exception) { val classified = DiaryFailure.of(failure, unprocessable) - if (clearOnSignInRequired && classified is DiaryFailure.SignInRequired) { + if (classified is DiaryFailure.SignInRequired) { // Guarded, because it writes: the store is DataStore, whose // write side rethrows `IOException`, and this runs inside the // `catch` that is turning a refusal into a `Result`. A full @@ -219,7 +296,10 @@ internal class DiaryRepositoryImpl( // was the app disappearing while the screen was open. The // token stays until the next failure tries again; see // `signOut`, which has always guarded its own clear. - runCatching { store.clearDiarySession() } + // + // The token only: which diary this phone uses outlives it, so + // the next screen asks for the same account (see the store). + runCatching { store.clearDiaryToken() } } Result.failure(classified) } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignIn.kt new file mode 100644 index 00000000..40fc110f --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignIn.kt @@ -0,0 +1,62 @@ +package com.lumenpearson.lessons.core.data.repository + +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession + +/** + * Getting into a diary from this phone, in the order it has to happen. + * + * 1. [preflight] — before the password field is even enabled: is a server set, + * can it keep a session opened here, does it serve this region, and does the + * region take a password at all. Nothing is sent to a diary. + * 2. [openUpstream] — the phone signs in to the diary's own server with the + * password. The password goes there and nowhere else: not to our server, + * not to a log, not to disk. + * 3. [register] — the session the diary handed over goes to our server, which + * reads with it once from its own address (that read is the check), seals + * it, and answers with a bearer of ours. The phone then forgets the diary's + * session; the bearer and the [DiaryTarget] are all it keeps. + * 4. [discard] — for a session our server refused, or one a screen backs out + * of: says goodbye upstream («Сетевой город»; Petersburg has no such call), + * so it does not linger on the diary's side for its whole idle window. + * + * The steps are separate because the screens need them to be: a registration + * that failed for want of a network is retried with the session still in hand, + * without asking for the password again — see + * [DiarySignInProblem.retryKeepsSession]. [signIn] runs all of them for a + * screen that holds nothing between steps. + * + * Every failure is a [DiarySignInProblem]. + */ +interface DiarySignIn { + + /** Everything that can be checked before a password is taken. */ + suspend fun preflight(target: DiaryTarget): Result + + /** + * Signs in to the diary itself. The [UpstreamSession] that comes back lives + * in memory only — never in saved state, DataStore, Room or a log — until + * [register] or [discard] is done with it. + */ + suspend fun openUpstream(target: DiaryTarget, password: String): Result + + /** + * Hands [upstream] to our server and stores what it answers — our bearer + * and the target — in place of whatever diary this phone held before. A + * different account empties what was kept for the previous one first, so a + * new account never sits over the old one's rows. + * + * On a failure whose [DiarySignInProblem.retryKeepsSession] is `false`, the + * session has already been discarded here; on one where it is `true`, the + * caller may register the same session again. + */ + suspend fun register(upstream: UpstreamSession): Result + + /** Ends [upstream] with the diary, best effort. Nothing once our server holds it. */ + suspend fun discard(upstream: UpstreamSession) + + /** + * [preflight], [openUpstream] and [register] in one, discarding the session + * on any failure after it exists: there is nobody holding it to retry. + */ + suspend fun signIn(target: DiaryTarget, password: String): Result +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt new file mode 100644 index 00000000..5ec5e438 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt @@ -0,0 +1,340 @@ +package com.lumenpearson.lessons.core.data.repository + +import com.lumenpearson.lessons.core.data.network.DiaryApi +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionResponseDto +import com.lumenpearson.lessons.core.data.network.dto.NetSchoolCookiesDto +import com.lumenpearson.lessons.core.data.network.dto.NetSchoolCredentialDto +import com.lumenpearson.lessons.core.data.network.dto.PetersburgCredentialDto +import com.lumenpearson.lessons.core.data.upstream.NetSchoolRegion +import com.lumenpearson.lessons.core.data.upstream.NetSchoolSignIn +import com.lumenpearson.lessons.core.data.upstream.PetersburgSignIn +import com.lumenpearson.lessons.core.data.upstream.UpstreamDirectory +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession +import com.lumenpearson.lessons.core.data.upstream.UpstreamValues +import java.time.Clock +import java.time.Duration +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.jsonObject +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import retrofit2.HttpException + +/** + * [DiarySignIn] over the diaries' own servers and ours. + * + * @param directory the bundled catalog's allow-list, the only source of a host + * the phone signs in to. A function because building it reads a few hundred + * kilobytes of JSON, which happens on first use, on the IO dispatcher, rather + * than on the main thread in the container's constructor. + * @param client the provider client (`UpstreamHttp.client`), which carries + * none of our server's interceptors; built on first use for the same reason. + * @param forgetLocal empties whatever this phone keeps about a diary account + * beyond the store — the offline diary, once there is one. Called when a + * different account signs in, before its session is written. + */ +internal class DiarySignInImpl( + private val api: DiaryApi, + private val store: DiarySessionStore, + private val directory: () -> UpstreamDirectory, + private val client: () -> OkHttpClient, + private val forgetLocal: suspend () -> Unit = {}, + private val clock: Clock = Clock.systemUTC(), + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, +) : DiarySignIn { + + /** Where a target's sign-in goes, resolved from the catalog and nothing else. */ + private sealed interface Endpoint { + val origin: HttpUrl + + class Petersburg(override val origin: HttpUrl) : Endpoint + + class NetSchool(val region: NetSchoolRegion) : Endpoint { + override val origin: HttpUrl get() = region.origin + } + } + + override suspend fun preflight(target: DiaryTarget): Result = attempt { + // The phone's own catalog first: it costs no request, and a region the + // phone would refuse to talk to is not worth asking the server about. + endpoint(target) + val capabilities = try { + api.capabilities() + } catch (failure: HttpException) { + // A server from before registration has no such route. It could + // not keep a session opened here, so it is found out now — before + // a password is typed, never after one was sent to the diary. + if (failure.code() == 404) throw DiarySignInProblem.ServerTooOld + throw failure + } + if (!capabilities.registration) throw DiarySignInProblem.ServerTooOld + if (!capabilities.enabled) throw DiarySignInProblem.ServerDisabled + val served = when (target.provider) { + DiaryProviderKey.PETERSBURG -> capabilities.providers.petersburg != null + DiaryProviderKey.NETSCHOOL -> + target.region in capabilities.providers.netschool?.regions.orEmpty() + } + if (!served) throw DiarySignInProblem.RegionNotServed + } + + override suspend fun openUpstream( + target: DiaryTarget, + password: String, + ): Result = withContext(ioDispatcher) { + val endpoint = try { + endpoint(target) + } catch (problem: DiarySignInProblem) { + return@withContext Result.failure(problem) + } + val host = endpoint.origin.host + try { + // The server's own rule for a login, checked before anything is + // sent, so a typo costs a sentence rather than an attempt. + val login = target.login.trim() + if (login.codePointCount(0, login.length) < MIN_LOGIN_LENGTH) { + throw DiarySignInProblem.LoginTooShort + } + if (password.isEmpty()) throw DiarySignInProblem.WrongPassword(upstreamMessage = null) + val session = when (endpoint) { + is Endpoint.Petersburg -> + PetersburgSignIn(client(), endpoint.origin, clock).signIn(target, password) + is Endpoint.NetSchool -> + NetSchoolSignIn(client(), clock).signIn(endpoint.region, target, password) + } + Result.success(session) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + val problem = DiarySignInProblem.of(failure, host = host) + // `logindata` saying «Госуслуги only» names no site; the catalog does. + Result.failure( + if (problem is DiarySignInProblem.GosuslugiOnly && endpoint is Endpoint.NetSchool) { + DiarySignInProblem.GosuslugiOnly(endpoint.region.handoffUrl) + } else { + problem + }, + ) + } + } + + override suspend fun register(upstream: UpstreamSession): Result = + withContext(ioDispatcher) { + if (upstream.spent) { + // Registered or discarded already: a second row, or a session + // somebody said goodbye to, is not something to send. + return@withContext Result.failure( + DiarySignInProblem.Unexpected("the diary session was already used"), + ) + } + val response = try { + if (Duration.between(upstream.openedAt, clock.instant()) > maxAge(upstream)) { + throw DiarySignInProblem.SessionAgedOut + } + val body = requestFor(upstream) + ?: throw DiarySignInProblem.ProviderUnreadable(hostOf(upstream)) + api.registerSession(body) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + val problem = DiarySignInProblem.of(failure, host = null, registering = true) + if (!problem.retryKeepsSession) discard(upstream) + return@withContext Result.failure(problem) + } + + // From here the session is the server's: nothing on the phone may + // end it or send it again, whatever happens to the write below. + upstream.spent = true + val session = sessionFrom(response, upstream.target) + try { + val previous = store.currentDiaryTarget() + if (previous == null || previous.accountKey() != session.target.accountKey()) { + // In this order, so there is never a moment where a new + // account's bearer sits over the old account's rows. + forgetLocal() + store.selectStudent(null) + } + store.writeDiarySession(session) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + // A full disk. The server holds a session nobody here can + // reach; it is purged after its idle window. Not a network + // failure, whatever the exception's type says, so not retried. + return@withContext Result.failure( + DiarySignInProblem.Unexpected("the session could not be stored", failure), + ) + } + Result.success(DiaryRegistration(session, response.students.map { it.toDomain() })) + } + + override suspend fun discard(upstream: UpstreamSession) { + if (upstream.spent) return + upstream.spent = true + when (upstream) { + is UpstreamSession.Petersburg -> Unit // Petersburg has no logout without a browser. + is UpstreamSession.NetSchool -> withContext(ioDispatcher) { + val region = runCatching { directory().netschool(upstream.target.region) }.getOrNull() + ?: return@withContext + NetSchoolSignIn(client(), clock).logout(upstream, region) + } + } + } + + override suspend fun signIn(target: DiaryTarget, password: String): Result { + preflight(target).onFailure { return Result.failure(it) } + val upstream = openUpstream(target, password).getOrElse { return Result.failure(it) } + return register(upstream).onFailure { discard(upstream) } + } + + // ---- plumbing ----------------------------------------------------------- + + private suspend fun attempt(block: suspend () -> T): Result = withContext(ioDispatcher) { + try { + Result.success(block()) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + Result.failure(DiarySignInProblem.of(failure)) + } + } + + /** The catalog's answer to «where does this target sign in», or the problem that stops it. */ + private fun endpoint(target: DiaryTarget): Endpoint { + val catalog = directory() + return when (target.provider) { + DiaryProviderKey.PETERSBURG -> Endpoint.Petersburg( + catalog.petersburg + ?: throw DiarySignInProblem.Unexpected("the catalog carries no Petersburg origin"), + ) + DiaryProviderKey.NETSCHOOL -> { + val region = catalog.netschool(target.region) ?: throw DiarySignInProblem.RegionNotServed + // Refused here, with nothing sent anywhere: the region lets + // people in through Госуслуги only, which this app never signs + // in to. The browser is the way in. + if (!region.password) throw DiarySignInProblem.GosuslugiOnly(region.handoffUrl) + val school = target.schoolId + if (school == null || school < 1) { + throw DiarySignInProblem.Unexpected("a NetSchool target without a school") + } + Endpoint.NetSchool(region) + } + } + } + + private fun hostOf(upstream: UpstreamSession): String? = + runCatching { endpoint(upstream.target).origin.host }.getOrNull() + + /** + * How long a session may wait between the diary handing it over and our + * server taking it. Registering a dead one costs an attempt against the + * throttle and says «the diary refused the session», which would be a lie. + * + * «Сетевой город» says how long its sessions idle for, in milliseconds; + * a figure under a minute is read as some other unit and ignored. + * Petersburg says nothing, so ten minutes — far longer than the seconds a + * registration takes, far shorter than any lifetime seen. + */ + private fun maxAge(upstream: UpstreamSession): Duration { + val declared = (upstream as? UpstreamSession.NetSchool)?.timeOut + ?.takeIf { it >= MIN_DECLARED_TIMEOUT_MILLIS } + ?.let(Duration::ofMillis) + return declared ?: DEFAULT_MAX_AGE + } + + /** + * The registration body, or `null` when the session holds a value the + * server would refuse — checked here by the server's own rules, so a + * session the diary shaped oddly is «the diary answered strangely», not a + * `422` that looks like a bug in the app. + */ + private fun requestFor(upstream: UpstreamSession): DiarySessionRequestDto? { + val target = upstream.target + val login = target.login.trim() + return when (upstream) { + is UpstreamSession.Petersburg -> { + val token = upstream.token + if (token.length < MIN_JWT_LENGTH || !JWT.matches(token) || !UpstreamValues.cookieValueOk(token)) { + return null + } + DiarySessionRequestDto( + provider = DiaryProviderKey.PETERSBURG.wire, + login = login, + credential = credentialJson.encodeToJsonElement(PetersburgCredentialDto(token)).jsonObject, + ) + } + is UpstreamSession.NetSchool -> { + val at = upstream.at + if (at.length !in AT_LENGTH || !UpstreamValues.headerValueOk(at)) return null + val session = upstream.cookies[NSSESSIONID] + ?.takeIf { it.length <= NSSESSIONID_MAX && UpstreamValues.cookieValueOk(it) } + ?: return null + val security = upstream.cookies[ESRNSEC] + ?.takeIf { it.length <= ESRNSEC_MAX && UpstreamValues.cookieValueOk(it) } + val credential = NetSchoolCredentialDto( + at = at, + cookies = NetSchoolCookiesDto(session = session, security = security), + // Left out rather than refused when it is not a version the + // server takes: it only acknowledges a warning page and says + // goodbye, and a session is worth more than either. + ver = upstream.ver?.takeIf { it.length <= VER_MAX && VER.matches(it) }, + timeOut = upstream.timeOut?.takeIf { it in 0..Int.MAX_VALUE.toLong() }, + ) + DiarySessionRequestDto( + provider = DiaryProviderKey.NETSCHOOL.wire, + login = login, + region = target.region, + schoolId = target.schoolId, + credential = credentialJson.encodeToJsonElement(credential).jsonObject, + ) + } + } + } + + /** + * What the phone keeps: our bearer, and the target as the server now names + * it — its zone above all, so the phone's «today» is the server's. + */ + private fun sessionFrom(response: DiarySessionResponseDto, sent: DiaryTarget): DiarySession { + // The login as the server stored it, which keys the corrections; what + // was typed, trimmed, if it ever stops echoing one. + val login = response.login.trim().ifBlank { sent.login.trim() } + val target = sent.copy( + region = response.region ?: sent.region, + schoolId = response.schoolId ?: sent.schoolId, + schoolName = response.schoolName?.takeIf { it.isNotBlank() } ?: sent.schoolName, + login = login, + zone = response.zone?.takeIf { it.isNotBlank() } ?: sent.zone, + ) + return DiarySession(login = login, token = response.token, target = target) + } + + private companion object { + /** `_clean_login_value` in `server/app/schemas.py`. */ + const val MIN_LOGIN_LENGTH = 3 + + val DEFAULT_MAX_AGE: Duration = Duration.ofMinutes(10) + const val MIN_DECLARED_TIMEOUT_MILLIS = 60_000L + + /** `PetersburgCredentialIn` in `server/app/schemas.py`: a JWT that can be one cookie. */ + val JWT = Regex("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*") + const val MIN_JWT_LENGTH = 16 + + /** `NetSchoolCredentialIn` and `NetSchoolCookiesIn`, bound for bound. */ + val AT_LENGTH = 8..512 + const val NSSESSIONID = "NSSESSIONID" + const val NSSESSIONID_MAX = 128 + const val ESRNSEC = "ESRNSec" + const val ESRNSEC_MAX = 2048 + val VER = Regex("[A-Za-z0-9._-]+") + const val VER_MAX = 32 + + /** Nulls left out: `ver` and `ESRNSec` are absent, not `null`, when there are none. */ + val credentialJson = Json { explicitNulls = false } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt new file mode 100644 index 00000000..570b19df --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt @@ -0,0 +1,360 @@ +package com.lumenpearson.lessons.core.data.repository + +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.upstream.UpstreamFailure +import com.lumenpearson.lessons.core.data.upstream.UpstreamNotAllowed +import com.lumenpearson.lessons.core.data.upstream.isTimeout +import java.io.IOException +import kotlinx.coroutines.CancellationException +import retrofit2.HttpException + +/** + * Everything that can stop a family getting into their diary on this phone, as + * one type the screens switch on. + * + * A sign-in now has two counterparts — the diary's own server, which the phone + * talks to directly, and ours, which it registers the session with — and each + * fails in its own vocabulary: [UpstreamFailure] for the first, HTTP statuses + * and [DiaryFailure] for the second. The sign-in form, the school search, the + * import and Settings → Дневник all have to say one sentence about whichever it + * was, so they switch on this and nothing else; `DiaryProblemText` in `:app` is + * the one place that turns a case into words. Two mappings would be two + * answers to «what does a 429 say», which is how the diary came to show «Не + * получилось: 429» where the server had said «слишком много попыток» (#153). + * + * The cases that concern the diary's server carry its host, because «не + * отвечает» about a named server is a sentence somebody can do something with + * and «не отвечает» alone is not. The cases that concern ours carry nothing: + * the screen already knows which server it is set to. + * + * No case carries the password or any part of it. [WrongPassword] carries only + * what the diary said. + */ +sealed class DiarySignInProblem(message: String, cause: Throwable? = null) : + Exception(message, cause) { + + /** What the screen offers next. */ + enum class Action { + /** Try the same thing again; nothing typed has to change. */ + RETRY, + + /** Type the password (or the login) again. */ + RETYPE, + + /** + * Open the diary's own site in the browser — the region lets people in + * through Госуслуги only, which this app never signs in to. + */ + HANDOFF, + + /** Set or change our server's address. */ + SET_SERVER, + + /** Wait before trying again; see [TooManyAttempts]. */ + WAIT, + + /** Nothing on this screen will help. */ + NONE, + } + + abstract val action: Action + + /** + * Whether an upstream session that was being registered when this happened + * is still worth holding for a retry. The ones that are: our server could + * not be reached or was busy, so nothing judged the session and the same + * one may be registered again without the password. Everything else has + * already said no to that session, and `DiarySignIn.register` has + * discarded it. + */ + open val retryKeepsSession: Boolean get() = false + + // ---- the diary's own server -------------------------------------------- + + /** The diary refused the login and password. */ + data class WrongPassword(val upstreamMessage: String?) : + DiarySignInProblem("The diary refused the credentials") { + override val action get() = Action.RETYPE + } + + /** + * The region lets people in through Госуслуги only — the catalog said so + * before anything was sent, or the diary's `logindata` did before a + * password was. [handoffUrl] is where to send somebody instead: the + * catalog system's `handoff_url`, which for a «Сетевой город» region is its + * own site rather than Госуслуги's. + */ + data class GosuslugiOnly(val handoffUrl: String?) : + DiarySignInProblem("The diary takes no password sign-in") { + override val action get() = Action.HANDOFF + } + + /** The diary's server did not answer, or answered `5xx`/`429`. */ + data class ProviderUnavailable(val host: String?) : + DiarySignInProblem("The diary is not answering") { + override val action get() = Action.RETRY + override val retryKeepsSession get() = true + } + + /** + * A `403` or a firewall page from the diary: it will not talk to this + * phone's address. A VPN is the usual reason, so it is worth a retry once + * that is off. + */ + data class ProviderRefusesPhone(val host: String?) : + DiarySignInProblem("The diary refuses this phone's address") { + override val action get() = Action.RETRY + } + + /** + * The diary's certificate chains to a root the phone does not trust — the + * Russian Trusted Root, typically. Nothing is relaxed to get past it. + */ + data class ProviderUntrusted(val host: String?) : + DiarySignInProblem("The phone does not trust the diary's certificate") { + override val action get() = Action.NONE + } + + /** + * An answer nobody could read: the diary's to the phone (a captcha, a + * changed sign-in page), or its answer to our server (`502`), in which case + * [host] is `null`. An app update fixes this, not another password. + */ + data class ProviderUnreadable(val host: String?) : + DiarySignInProblem("The diary answered in an unreadable way") { + override val action get() = Action.RETRY + } + + /** The phone could not resolve or reach the diary's server at all. */ + data class ProviderOffline(val host: String?) : + DiarySignInProblem("The diary's server cannot be reached") { + override val action get() = Action.RETRY + } + + // ---- either side ------------------------------------------------------- + + /** + * Nobody answered in time: the diary's server, when [host] is set, or ours + * — a socket timeout, or a `504` from the platform's own ceiling. + */ + data class Timeout(val host: String?) : + DiarySignInProblem("Nobody answered in time") { + override val action get() = Action.RETRY + override val retryKeepsSession get() = true + } + + // ---- our server ---------------------------------------------------------- + + /** Our server could not be reached, before any session existed. */ + data object Offline : DiarySignInProblem("Could not reach the server") { + override val action get() = Action.RETRY + } + + /** + * The diary let the family in, and then our server could not be reached to + * keep the session. The session is still held: a retry registers it again, + * without the password. + */ + data object RegisterUnreachable : + DiarySignInProblem("The diary let you in, but the server could not be reached") { + override val action get() = Action.RETRY + override val retryKeepsSession get() = true + } + + /** No server address is set yet; nothing was sent anywhere. */ + data object ServerMissing : DiarySignInProblem("No server address is set") { + override val action get() = Action.SET_SERVER + } + + /** + * The server predates sessions opened on the phone (`404` on + * `/capabilities`), so it could not keep one. Found out before a password + * was taken. + */ + data object ServerTooOld : DiarySignInProblem("The server cannot keep a session opened here") { + override val action get() = Action.SET_SERVER + } + + /** The server's diary is switched off (no `DIARY_SECRET`). */ + data object ServerDisabled : DiarySignInProblem("The diary is switched off on this server") { + override val action get() = Action.NONE + } + + /** + * The server does not keep sessions for this region, or the phone's own + * catalog does not list it. Found out before a password was taken. + */ + data object RegionNotServed : DiarySignInProblem("The server does not serve this region") { + override val action get() = Action.NONE + } + + /** + * `409`: the diary let the family in on the phone, and then refused the + * same session from our server's address. Retyping the password would loop + * — it was right seconds ago — so nothing is retried automatically, and a + * class code is the way in that still works. + */ + data object ServerRefusedSession : + DiarySignInProblem("The diary refused the session from the server") { + override val action get() = Action.NONE + } + + /** + * `503` with `X-Diary-Unavailable: address-refused`: the diary will not + * talk to our server at all. Not the password. + */ + data object ServerAddressRefused : + DiarySignInProblem("The diary refuses the server's address") { + override val action get() = Action.NONE + } + + /** `403` on registration: the account has no pupil the diary will show. */ + data object NoStudent : DiarySignInProblem("The diary account has no pupil") { + override val action get() = Action.NONE + } + + /** + * `429`: too many attempts from here. [retryAfterSeconds] is the server's + * `Retry-After`, or `null` when it gave none that could be read. + */ + data class TooManyAttempts(val retryAfterSeconds: Long?) : + DiarySignInProblem("Too many sign-in attempts") { + override val action get() = Action.WAIT + override val retryKeepsSession get() = true + } + + /** + * The diary handed over a session and it grew too old to register before + * it was — the screen sat open, or the phone slept. It was discarded + * rather than sent to die on the server, where it would cost an attempt. + */ + data object SessionAgedOut : DiarySignInProblem("The diary session grew too old to keep") { + override val action get() = Action.RETYPE + } + + /** + * The login is shorter than three characters once trimmed — what the + * server refuses too. Caught before anything was sent. + */ + data object LoginTooShort : DiarySignInProblem("The login is too short") { + override val action get() = Action.RETYPE + } + + /** Our session is fine, the diary's expired: the password, for the same account. */ + data object ReauthRequired : DiarySignInProblem("Diary session expired upstream") { + override val action get() = Action.RETYPE + } + + /** Our own session is gone: sign in again. */ + data object SignInRequired : DiarySignInProblem("Diary sign-in required") { + override val action get() = Action.RETYPE + } + + /** + * Anything else — a `422` from registration included, which only a bug in + * this app produces — kept with its cause so a bug report can carry it. + */ + class Unexpected(val detail: String?, cause: Throwable? = null) : + DiarySignInProblem("Unexpected diary sign-in failure" + (detail?.let { ": $it" } ?: ""), cause) { + override val action get() = Action.RETRY + } + + companion object { + + /** + * Classifies whatever a sign-in, a registration, a school search or an + * import step threw. Already a problem stays itself. + * + * @param host the diary server the failing call went to, for the cases + * that name it; `null` when the call was to our server. + * @param registering whether the call was the registration, where a + * network failure means «the diary let you in and the session is + * still held», not «no network before anything happened». + */ + fun of( + failure: Throwable, + host: String? = null, + registering: Boolean = false, + ): DiarySignInProblem = when (failure) { + // Never classified: a cancelled screen is not a failure to show. + is CancellationException -> throw failure + is DiarySignInProblem -> failure + is UpstreamFailure -> ofUpstream(failure, host) + // A request to a host outside the allow-list. Every URL is built + // from the catalog, so this is a bug here, never «нет сети». + is UpstreamNotAllowed -> Unexpected("not an allow-listed origin", failure) + is HttpException -> ofServer(failure.code(), failure, registering) + is DiaryFailure -> ofDiaryFailure(failure, registering) + is IOException -> ofTransport(failure, registering) + else -> Unexpected(failure::class.simpleName, failure) + } + + private fun ofUpstream(failure: UpstreamFailure, host: String?): DiarySignInProblem = + when (failure) { + is UpstreamFailure.BadCredentials -> WrongPassword(failure.upstreamMessage) + is UpstreamFailure.SignInUnsupported -> GosuslugiOnly(handoffUrl = null) + is UpstreamFailure.Unavailable -> + if (failure.timedOut) Timeout(host) else ProviderUnavailable(host) + is UpstreamFailure.Offline -> ProviderOffline(host) + is UpstreamFailure.AddressRefused -> ProviderRefusesPhone(host) + is UpstreamFailure.Untrusted -> ProviderUntrusted(host) + is UpstreamFailure.Unexpected -> ProviderUnreadable(host) + } + + /** One of our server's statuses, on the registration or any diary call. */ + private fun ofServer(code: Int, failure: HttpException, registering: Boolean): DiarySignInProblem = + when (code) { + 401 -> { + val reauth = failure.response()?.headers()?.get(DiaryFailure.REAUTH_HEADER) + ?.trim()?.equals("required", ignoreCase = true) == true + if (reauth) ReauthRequired else SignInRequired + } + // On registration, the account has no pupil; elsewhere a 403 + // is nothing this client should ever be answered. + 403 -> if (registering) NoStudent else Unexpected("HTTP 403", failure) + // Registration's own status for «the diary refused the session + // from our address», which is not a wrong password (K10). + 409 -> ServerRefusedSession + // A body the server refused before asking anybody: ours to fix. + 422 -> Unexpected("HTTP 422", failure) + 429 -> TooManyAttempts(DiaryFailure.retryAfterSeconds(failure)) + 502 -> ProviderUnreadable(host = null) + 503 -> when ( + failure.response()?.headers()?.get(DiaryFailure.UNAVAILABLE_HEADER) + ?.trim()?.lowercase() + ) { + "disabled" -> ServerDisabled + "address-refused" -> ServerAddressRefused + else -> ProviderUnavailable(host = null) + } + 504 -> Timeout(host = null) + else -> Unexpected("HTTP $code", failure) + } + + private fun ofDiaryFailure(failure: DiaryFailure, registering: Boolean): DiarySignInProblem = + when (failure) { + DiaryFailure.SignInRequired -> SignInRequired + DiaryFailure.ReauthRequired -> ReauthRequired + DiaryFailure.Disabled -> ServerDisabled + DiaryFailure.ServerAddressRefused -> ServerAddressRefused + is DiaryFailure.Throttled -> TooManyAttempts(failure.retryAfterSeconds) + DiaryFailure.Unavailable -> ProviderUnavailable(host = null) + DiaryFailure.Unreadable -> ProviderUnreadable(host = null) + is DiaryFailure.Offline -> ofTransport(failure.reason, registering) + DiaryFailure.UnknownStudent, + DiaryFailure.BadRange, + DiaryFailure.Rejected, + is DiaryFailure.Unexpected, + -> Unexpected(failure.message, failure) + } + + /** No answer from our server at all. */ + private fun ofTransport(failure: Throwable, registering: Boolean): DiarySignInProblem = when { + generateSequence(failure) { it.cause }.take(8).any { it is ServerAddressMissingException } -> + ServerMissing + failure.isTimeout() -> Timeout(host = null) + registering -> RegisterUnreachable + else -> Offline + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt new file mode 100644 index 00000000..5c981e69 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt @@ -0,0 +1,164 @@ +package com.lumenpearson.lessons.core.data.repository + +import java.time.DateTimeException +import java.time.ZoneId +import java.util.Locale +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * Which diary a phone signs in to. The server's `provider` wire names. + * + * Named «key» because `DiaryProvider` is the server's word for the class that + * *talks* to a diary, and a phone that only picks one should not borrow it. + */ +enum class DiaryProviderKey(val wire: String) { + PETERSBURG("petersburg"), + NETSCHOOL("netschool"), + ; + + companion object { + /** `null` for a name this build does not know, so it reads as no diary at all. */ + fun fromWire(raw: String?): DiaryProviderKey? = entries.firstOrNull { it.wire == raw } + } +} + +/** + * Where this phone signs in to a diary — everything but the secret. + * + * Kept apart from our bearer because the two die at different times: a bare + * `401` drops the bearer, and without this the app would forget which diary, + * which region and which school it had been in, and a family that had only + * ever used the diary would be dropped back at the start instead of being asked + * for the password of the same account. It is cleared by signing out and by + * nothing else. + * + * @property region the catalog's key for a «Сетевой город» region; `null` for + * Petersburg, which is one city's server. + * @property schoolId the upstream's own school id («scid»); `null` for Petersburg. + * @property zone the zone the diary cuts its days at, as the server told us at + * registration (`services/diary.zone_for`), so the phone's «today» and the + * server's are one rule rather than two tables. + */ +data class DiaryTarget( + val provider: DiaryProviderKey, + val region: String?, + val schoolId: Long?, + val schoolName: String?, + val login: String, + val zone: String = PETERSBURG_ZONE, +) { + + /** + * [zone] as a [ZoneId], falling back to Moscow the way the server's + * `timezones.resolve` does. An older phone's tzdata may not know + * `Asia/Tomsk` or `Europe/Ulyanovsk`, and a diary that cannot open because + * of a zone name is worse than one whose midnight is an hour off. + */ + fun zoneId(): ZoneId = try { + ZoneId.of(zone) + } catch (_: DateTimeException) { + ZoneId.of(PETERSBURG_ZONE) + } + + /** + * Whether two targets are the same account, for deciding whether what is + * cached on the phone still belongs to whoever just signed in. Local only: + * it is not the server's `owner_key` and never leaves the device. + */ + fun accountKey(): String = + "${provider.wire}|${region.orEmpty()}|${login.trim().lowercase(Locale.ROOT)}" + + companion object { + /** Petersburg's diary is one city's, and that city keeps Moscow time. */ + const val PETERSBURG_ZONE: String = "Europe/Moscow" + + fun petersburg(login: String): DiaryTarget = DiaryTarget( + provider = DiaryProviderKey.PETERSBURG, + region = null, + schoolId = null, + schoolName = null, + login = login, + ) + + fun netschool( + region: String, + schoolId: Long, + schoolName: String?, + login: String, + zone: String, + ): DiaryTarget = DiaryTarget( + provider = DiaryProviderKey.NETSCHOOL, + region = region, + schoolId = schoolId, + schoolName = schoolName, + login = login, + zone = zone, + ) + } +} + +/** + * The stored shape of a [DiaryTarget]: one JSON value under one key, with a + * version, rather than six loose keys that a half-finished write could leave + * disagreeing with each other. + */ +internal object DiaryTargetCodec { + + private const val VERSION = 1 + + private val json = Json { + ignoreUnknownKeys = true + explicitNulls = false + // The version and the zone are written even when they are the + // defaults: a stored value that says what it is outlives a change to + // what the default means. + encodeDefaults = true + } + + @Serializable + private data class Stored( + @SerialName("v") val version: Int = VERSION, + @SerialName("provider") val provider: String, + @SerialName("region") val region: String? = null, + @SerialName("school_id") val schoolId: Long? = null, + @SerialName("school") val school: String? = null, + @SerialName("login") val login: String, + @SerialName("zone") val zone: String = DiaryTarget.PETERSBURG_ZONE, + ) + + fun encode(target: DiaryTarget): String = json.encodeToString( + Stored.serializer(), + Stored( + provider = target.provider.wire, + region = target.region, + schoolId = target.schoolId, + school = target.schoolName, + login = target.login, + zone = target.zone, + ), + ) + + /** + * `null` for anything this build cannot stand behind: an unreadable value, + * a later version, or a provider it does not know — which is what a + * downgrade after a third diary arrives would look like, and signing that + * account in to Petersburg instead would be worse than asking. + */ + fun decode(raw: String?): DiaryTarget? { + if (raw.isNullOrBlank()) return null + val stored = runCatching { json.decodeFromString(Stored.serializer(), raw) }.getOrNull() + ?: return null + if (stored.version != VERSION) return null + val provider = DiaryProviderKey.fromWire(stored.provider) ?: return null + return DiaryTarget( + provider = provider, + region = stored.region, + schoolId = stored.schoolId, + schoolName = stored.school, + login = stored.login, + zone = stored.zone, + ) + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt index 17e063d6..ed413a0b 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/Models.kt @@ -27,12 +27,17 @@ import com.lumenpearson.lessons.core.model.WeekStart * The [token] is long-lived and read-only; there is no refresh and no password, * so its presence is the whole of "signed in" and its absence sends the user * back to the join screen. + * + * [diary] is the class's diary binding as the join answered it, or `null` — + * see [DiaryBinding]. Last and defaulted, so every place that builds a session + * without one still means «no binding». */ data class Session( val classId: Long, val className: String, val school: String?, val token: String, + val diary: DiaryBinding? = null, ) /** diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt index 5ce989b3..dc007eb9 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/SessionRepositoryImpl.kt @@ -117,6 +117,10 @@ internal class SessionRepositoryImpl( className = response.className, school = response.school?.trim()?.ifBlank { null }, token = response.token, + // The join is the only answer that carries it (the bundle + // does not), so it is kept with the membership it came + // with — and replaced, like the token, by a re-join. + diary = response.diary?.toDomain(), ) // Before the membership is stored, so the new token can never // show rows that predate it. Only this class's rows: the other diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ShellMode.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ShellMode.kt new file mode 100644 index 00000000..72046e2b --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/ShellMode.kt @@ -0,0 +1,122 @@ +package com.lumenpearson.lessons.core.data.repository + +import kotlinx.coroutines.flow.Flow + +/** + * Which home the app opens on — decided from what is stored, by one rule. + * + * * [CLASS]: the phone is in a class. Today, Week, the widget and the alerts + * are the class's, and the diary lives in Settings → «Дневник». + * * [DIARY]: no class, but a diary this phone signs in to. The diary is the + * home. Nothing else is fed: no timetable, no widget content, no alerts, + * and no background sync (see [syncArmingFor]). + * * [NONE]: neither. The way in. + */ +enum class ShellMode { NONE, CLASS, DIARY } + +/** + * The mode, and whether onboarding holds the screen. + * + * [held] exists because a way in writes its credential **before** it is + * finished: the class-code step joins, the sign-in step registers, and either + * write flips [mode] away from [ShellMode.NONE] while the flow still has an + * import or a summary to show. The flag is persisted rather than remembered + * by the screen, so a process death between the write and the summary brings + * the flow back rather than dropping the family into a half-filled home. + */ +data class ShellState(val mode: ShellMode, val held: Boolean) + +/** + * A class outranks a diary: a phone in a class is in the app the class runs, + * and its diary stays in settings. A diary *target* — not a live session — is + * what makes [ShellMode.DIARY], because a bare `401` drops the bearer and + * keeps the target, and a family whose session lapsed belongs on their diary's + * sign-in form, not back at the start. + * + * This is also the answer to leaving the last class while signed in to a + * diary: the phone lands on the diary home, where the diary and its sign-out + * are, rather than on a join screen that reaches neither (#151). + */ +fun shellModeOf(classSession: Session?, diaryTarget: DiaryTarget?): ShellMode = when { + classSession != null -> ShellMode.CLASS + diaryTarget != null -> ShellMode.DIARY + else -> ShellMode.NONE +} + +/** Whether the periodic class sync should be installed, and at what interval. */ +sealed interface SyncArming { + data class Armed(val intervalMinutes: Int) : SyncArming + data object Disarmed : SyncArming +} + +/** + * The periodic `SyncWorker` refreshes a class timetable, so it runs in a class + * and nowhere else. + * + * This was a cold-start bug before it was a rule: the application armed the + * worker on every launch whatever was stored, so a phone that had left its + * last class — whose sign-out had just cancelled the worker — was woken every + * fifteen minutes again from its next launch on, for a run that found no class + * and returned (#152). A diary-only phone would have been woken the same way + * for ever, and the diary is never read in the background anyway. + */ +fun syncArmingFor(mode: ShellMode, intervalMinutes: Int): SyncArming = when (mode) { + ShellMode.CLASS -> SyncArming.Armed(intervalMinutes) + ShellMode.DIARY, ShellMode.NONE -> SyncArming.Disarmed +} + +/** + * The stored mode, for the app shell, the widget and the application. + * + * Every value here is computed from **one** read of the preferences file, never + * by combining a class flow with a diary flow: two flows can disagree for an + * emission in between — a join half-seen — and a gate that flickered to the + * wrong home for a frame would reset the state of the one it left. + */ +interface ShellModeSource { + + val state: Flow + + suspend fun current(): ShellState + + /** [syncArmingFor] of the stored mode and interval, one emission per change. */ + val syncArming: Flow + + /** Onboarding keeps the screen from here on; set on entering the class-code or sign-in step. */ + suspend fun hold() + + /** Onboarding is finished with the screen. */ + suspend fun release() + + /** + * For a cold start: a hold left over in [ShellMode.NONE] is dropped — the + * credential it was waiting for never landed, so there is nothing for the + * flow to finish and it starts from its beginning. Returns the state after. + */ + suspend fun settleColdStart(): ShellState +} + +/** + * The diary store, announcing the two writes that change the mode — a + * registration landing and a sign-out — so the widget, which draws a different + * sentence per mode and redraws only when told, does not keep saying «введите + * код класса» to a phone that just signed in to its diary. + * + * Only those two. A bare `401` keeps the target and so the mode, and the + * diary's own rows are drawn by nothing outside the app. + */ +internal class ModeAnnouncingDiaryStore( + private val delegate: DiarySessionStore, + private val announce: () -> Unit, +) : DiarySessionStore by delegate { + + override suspend fun writeDiarySession(value: DiarySession) { + delegate.writeDiarySession(value) + announce() + } + + override suspend fun forgetDiary() { + delegate.forgetDiary() + announce() + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolPassword.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolPassword.kt new file mode 100644 index 00000000..3c097ba1 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolPassword.kt @@ -0,0 +1,100 @@ +package com.lumenpearson.lessons.core.data.upstream + +import java.security.MessageDigest + +/** + * windows-1251, carried as a table rather than asked of the platform. + * + * «Сетевой город» hashes the password's windows-1251 bytes, so a character that + * encodes differently here than on the server is a password that is right on + * one side and wrong on the other. The JVM's charset and CPython's `cp1251` + * agree on every BMP code point (`Cp1251Test` holds the table to the JVM's); + * Android's charsets come from ICU, which nothing here has checked, so the + * table is this app's own and the device's converter is never asked. + * + * ASCII is itself; the high half is the 128 entries below, and `0x98` maps to + * nothing, as in both references. + */ +internal object Cp1251 { + + private val HIGH: IntArray = intArrayOf( + 0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021, // 0x80 + 0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F, // 0x88 + 0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, // 0x90 + -1, 0x2122, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F, // 0x98 + 0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7, // 0xA0 + 0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407, // 0xA8 + 0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7, // 0xB0 + 0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457, // 0xB8 + 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, // 0xC0 + 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, // 0xC8 + 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, // 0xD0 + 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, // 0xD8 + 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, // 0xE0 + 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, // 0xE8 + 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, // 0xF0 + 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, // 0xF8 + ) + + private val REVERSE: Map = buildMap { + HIGH.forEachIndexed { index, codePoint -> + if (codePoint >= 0) put(codePoint.toChar(), (0x80 + index).toByte()) + } + } + + /** + * The bytes of [text], or `null` when any character has none — never a + * question mark in its place, which would hash a different password. + * A surrogate half is refused like any other unmapped character, so a + * text this accepts has exactly one character per code point. + */ + fun encode(text: String): ByteArray? { + val out = ByteArray(text.length) + for ((index, char) in text.withIndex()) { + out[index] = when { + char.code < 0x80 -> char.code.toByte() + else -> REVERSE[char] ?: return null + } + } + return out + } +} + +/** + * The password pair «Сетевой город» asks for, computed on the phone so the + * password itself goes nowhere: `pw2 = md5hex(salt + md5hex(cp1251(password)))` + * and `pw` is its first `len(password)` characters — the scheme of every + * windows-1251 client, and the server's `_hash_password` byte for byte, held + * there by the shared vectors. + */ +internal object NetSchoolPassword { + + /** + * `(pw, pw2)`, or `null` when windows-1251 cannot encode a character of + * [password] — which the caller reports as a wrong password without the + * character, since a message holding it would hold part of the password. + * + * [salt] must be ASCII; the caller checks, because a salt that is not is + * the server's failure and not the password's. + */ + fun hash(salt: String, password: String): Pair? { + val raw = Cp1251.encode(password) ?: return null + val inner = md5Hex(raw) + val pw2 = md5Hex((salt + inner).toByteArray(Charsets.US_ASCII)) + // `Cp1251.encode` accepted only BMP characters, so `length` counts what + // Python's `len` counts. + return pw2.take(password.length) to pw2 + } + + // By hand rather than `"%02x".format`, which formats in the default locale + // and would hash an Arabic-locale phone's password with Arabic digits. + private fun md5Hex(bytes: ByteArray): String = buildString(32) { + for (byte in MessageDigest.getInstance("MD5").digest(bytes)) { + val value = byte.toInt() and 0xFF + append(HEX[value ushr 4]) + append(HEX[value and 0x0F]) + } + } + + private const val HEX = "0123456789abcdef" +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt new file mode 100644 index 00000000..f33e9135 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt @@ -0,0 +1,141 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import okhttp3.OkHttpClient +import okhttp3.Request + +/** One school a «Сетевой город» region lists. [address] is what tells apart its many «Школа № 5». */ +data class DiarySchool(val id: Long, val name: String, val address: String?) + +/** + * The schools of one «Сетевой город» region, asked of the region's own server. + * + * Straight from the phone, not through ours: the phone is about to sign in to + * exactly that server, so a search that cannot reach it is the honest early + * warning that the sign-in could not either; nothing new is opened on our + * server for anybody to spend; and we learn nothing about which school a family + * looked for. + * + * A failure is a [DiarySignInProblem], the same type the sign-in fails with, + * so the screen says one sentence about a region that refuses the phone, + * whichever step found it out. + */ +interface DiarySchoolSearch { + + /** + * Schools whose name matches [query] in the region under [regionKey], + * as the region's server ranks them, at most [MAX_ROWS]. + * + * A query shorter than [MIN_QUERY_LENGTH] once trimmed is answered with an + * empty list and no request. + */ + suspend fun search(regionKey: String, query: String): Result> + + companion object { + /** The bot's minimum too; one letter matches half a region. */ + const val MIN_QUERY_LENGTH: Int = 2 + + /** + * How long the screen waits after the last keystroke before asking. + * One constant for every screen that searches schools, so the upstream + * sees one person typing, not one request per letter. + */ + const val DEBOUNCE_MILLIS: Long = 500 + + /** More than a screen can usefully show; past it the query needs another word. */ + const val MAX_ROWS: Int = 50 + } +} + +/** + * [DiarySchoolSearch] over `GET {origin}/webapi/schools/search?name=…`. + * + * The Kotlin twin of the server's `NetSchoolClient.schools_search`, held to it + * by the `schools_search` cases of the shared vectors: the same query cut, the + * same refusal rule, and the same row rule — a row counts only with an `id` + * that is a JSON integer (not a string of digits, not `true`, not `6.0`) and a + * name that is non-blank text. + * + * No session rides a search: the region answers it to its own login page, and + * there is no session yet anyway. The query is a query *parameter* — the only + * user input that ever reaches a diary's URL — and never part of the host. + */ +internal class NetSchoolSchoolSearch( + private val client: () -> OkHttpClient, + private val directory: () -> UpstreamDirectory, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, +) : DiarySchoolSearch { + + override suspend fun search(regionKey: String, query: String): Result> = + withContext(ioDispatcher) { + val region = directory().netschool(regionKey) + ?: return@withContext Result.failure(DiarySignInProblem.RegionNotServed) + // A region that takes Госуслуги only is sent nothing: there is no + // school to pick for a sign-in this app cannot make. + if (!region.password) { + return@withContext Result.failure(DiarySignInProblem.GosuslugiOnly(region.handoffUrl)) + } + val wanted = query.trim() + if (wanted.codePointCount(0, wanted.length) < DiarySchoolSearch.MIN_QUERY_LENGTH) { + return@withContext Result.success(emptyList()) + } + try { + Result.success(fetch(region, wanted)) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (failure: Exception) { + Result.failure(DiarySignInProblem.of(failure, host = region.origin.host)) + } + } + + private suspend fun fetch(region: NetSchoolRegion, query: String): List { + val url = region.origin.newBuilder() + .encodedPath(PATH) + .addQueryParameter(QUERY_PARAMETER, cut(query)) + .build() + val request = Request.Builder() + .url(url) + .header("Accept", NetSchoolSignIn.ACCEPT) + .header("X-Requested-With", "XMLHttpRequest") + .get() + .build() + val answer = UpstreamHttp.fetch(client(), request) + if (NetSchoolSignIn.looksRefused(answer)) throw UpstreamFailure.AddressRefused() + return rows(NetSchoolSignIn.decode(answer) as? JsonArray ?: throw UpstreamFailure.Unexpected()) + .take(DiarySchoolSearch.MAX_ROWS) + } + + internal companion object { + const val PATH = "/webapi/schools/search" + const val QUERY_PARAMETER = "name" + + /** The server's `query[:60]`: whole code points, never half a surrogate pair. */ + const val QUERY_CUT_CODE_POINTS = 60 + + fun cut(query: String): String = + if (query.codePointCount(0, query.length) <= QUERY_CUT_CODE_POINTS) { + query + } else { + query.substring(0, query.offsetByCodePoints(0, QUERY_CUT_CODE_POINTS)) + } + + /** The rows worth showing, by the server's rule; see the class comment. */ + fun rows(body: JsonArray): List = body.mapNotNull { element -> + val row = element as? JsonObject ?: return@mapNotNull null + val id = UpstreamJson.integer(row["id"]) + ?.takeIf { it.bitLength() < 64 } + ?.toLong() + ?: return@mapNotNull null + val name = UpstreamJson.string(row["name"])?.trim()?.takeIf { it.isNotEmpty() } + ?: return@mapNotNull null + val address = UpstreamJson.string(row["addressString"])?.trim()?.takeIf { it.isNotEmpty() } + DiarySchool(id = id, name = name, address = address) + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt new file mode 100644 index 00000000..b7ebe5f0 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt @@ -0,0 +1,293 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Clock +import kotlinx.coroutines.CancellationException +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody + +/** + * «Сетевой город»'s password sign-in, on the phone: the password is hashed here + * and the pair goes to the region's own server, never to ours. + * + * A port of the server's `NetSchoolClient.login` (`netschool/client.py`) — + * `logindata`, then `getdata` for a one-shot salt, then the hashed `login`, + * rerun once with a fresh salt when the account is asked which role it is + * signing in as — held to it by the shared vectors, case for case. It ends at + * the accepted login: the phone runs no bootstrap and makes no read with the + * session. It hands it to our server, which does both from its own address, + * and then forgets it. + * + * **One deliberate difference from the server.** The server reads a transport + * failure whose text says `reset`, `refused` or `denied` as the region refusing + * its address, a rule written for a datacentre dropped at a regional firewall. + * On a phone, a refused connection is far more often the phone's own network or + * a captive portal, so here it is [UpstreamFailure.Unavailable]. The HTTP-level + * refusal rule — a `403`, or a firewall page — is kept exactly, and the vectors + * pin it. + * + * Nothing secret ever goes into a URL: `at`, the cookies, `pw` and `pw2` travel + * in headers and form bodies only. + */ +internal class NetSchoolSignIn( + private val client: OkHttpClient, + private val clock: Clock = Clock.systemUTC(), +) { + + /** The session being assembled: what `_absorb_cookies` and `self.session` are on the server. */ + private class Draft(val origin: HttpUrl) { + val cookies = LinkedHashMap() + var ver: String? = null + } + + /** + * @throws UpstreamFailure for every answer that is not a session; see the + * class comment for which is which. + */ + suspend fun signIn(region: NetSchoolRegion, target: DiaryTarget, password: String): UpstreamSession.NetSchool { + // Before any request: a region that takes Госуслуги only is sent nothing. + if (!region.password) throw UpstreamFailure.SignInUnsupported() + val schoolId = target.schoolId ?: throw UpstreamFailure.Unexpected("no school") + val login = target.login.trim() + val draft = Draft(region.origin) + + loginAllowed(draft) + val login1 = passwordLogin(draft, login, password, schoolId, rolegroup = null) + val accepted = when (login1) { + is Outcome.Accepted -> login1 + is Outcome.NeedsRole -> { + // The server wants a role chosen and names none this code can + // read: asking again without one would ask the same question. + val role = login1.rolegroup ?: throw UpstreamFailure.Unexpected("role") + when (val login2 = passwordLogin(draft, login, password, schoolId, rolegroup = role)) { + is Outcome.Accepted -> login2 + // `tried_role` makes a second role question a refusal in + // `consumeLogin`, so this branch cannot be reached; it is + // here so the `when` needs no cast. + is Outcome.NeedsRole -> throw UpstreamFailure.BadCredentials(null) + } + } + } + return UpstreamSession.NetSchool( + target = target.copy(login = login), + at = accepted.at, + cookies = draft.cookies.toMap(), + ver = draft.ver, + timeOut = accepted.timeOut, + openedAt = clock.instant(), + ) + } + + /** + * Says goodbye upstream, best effort — for a session our server refused, + * so it does not linger on the diary's side for its whole idle window. + * Never after a successful registration: that would end the session our + * server now holds. + */ + suspend fun logout(session: UpstreamSession.NetSchool, region: NetSchoolRegion) { + try { + val form = FormBody.Builder() + .add("at", session.at) + .add("ver", session.ver.orEmpty()) + .build() + UpstreamHttp.fetch( + client, + authed(Request.Builder(), session.at, session.cookies) + .url(region.origin.newBuilder().encodedPath(LOGOUT_PATH).build()) + .post(form) + .build(), + ) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (_: Exception) { + // We are leaving anyway. + } + } + + // ---- the steps -------------------------------------------------------- + + private suspend fun loginAllowed(draft: Draft) { + val answer = send(draft, LOGINDATA_PATH, body = null, auth = false) + val data = decode(answer) as? JsonObject ?: throw UpstreamFailure.Unexpected() + absorb(draft, answer) + // Absent means allowed, as the server's `data.get("schoolLogin", True)`. + if ("schoolLogin" in data && !UpstreamJson.truthy(data["schoolLogin"])) { + throw UpstreamFailure.SignInUnsupported() + } + // Kept only when the server gave one, never as the word "null". + UpstreamJson.scalarText(data["cacheVer"]).takeIf { it.isNotEmpty() }?.let { ver -> + if (draft.ver == null) draft.ver = ver + } + } + + internal sealed interface Outcome { + class Accepted(val at: String, val timeOut: Long?) : Outcome + class NeedsRole(val rolegroup: String?) : Outcome + } + + private suspend fun passwordLogin( + draft: Draft, + login: String, + password: String, + schoolId: Long, + rolegroup: String?, + ): Outcome { + // An empty body with no media type, as httpx sends `data={}`; the salt + // is one-shot and tied to the cookie `logindata` set, so every attempt + // — the role retry included — asks for a fresh one. + val getdata = send(draft, GETDATA_PATH, body = ByteArray(0).toRequestBody(null), auth = true) + absorb(draft, getdata) + val payload = decode(getdata) as? JsonObject ?: JsonObject(emptyMap()) + val salt = UpstreamJson.scalarText(payload["salt"]) + val lt = UpstreamJson.scalarText(payload["lt"]) + val ver = UpstreamJson.scalarText(payload["ver"]) + // Nothing has judged the password yet: this is the diary's failure. + if (salt.isEmpty() || lt.isEmpty()) throw UpstreamFailure.Unavailable() + if (!salt.all { it.code < 0x80 }) throw UpstreamFailure.Unavailable() + val (pw, pw2) = NetSchoolPassword.hash(salt, password) + ?: throw UpstreamFailure.BadCredentials(null) + + val form = FormBody.Builder() + .add("loginType", "1") + .add("scid", schoolId.toString()) + .add("un", login) + .add("pw", pw) + .add("pw2", pw2) + .add("lt", lt) + .add("ver", ver) + .apply { if (rolegroup != null) add("rolegroup", rolegroup) } + .build() + val answer = send(draft, LOGIN_PATH, body = form, auth = true) + absorb(draft, answer) + return consumeLogin(answer, triedRole = rolegroup != null) + } + + // ---- plumbing --------------------------------------------------------- + + private suspend fun send(draft: Draft, path: String, body: RequestBody?, auth: Boolean): UpstreamAnswer { + val builder = Request.Builder().url(draft.origin.newBuilder().encodedPath(path).build()) + if (auth) authed(builder, at = null, cookies = draft.cookies) + builder.header("Accept", ACCEPT).header("X-Requested-With", "XMLHttpRequest") + if (body == null) builder.get() else builder.post(body) + val answer = UpstreamHttp.fetch(client, builder.build()) + if (looksRefused(answer)) throw UpstreamFailure.AddressRefused() + return answer + } + + private fun authed(builder: Request.Builder, at: String?, cookies: Map): Request.Builder { + builder.header("Accept", ACCEPT).header("X-Requested-With", "XMLHttpRequest") + if (!at.isNullOrEmpty()) builder.header("at", at) + if (cookies.isNotEmpty()) { + builder.header("Cookie", cookies.entries.joinToString("; ") { "${it.key}=${it.value}" }) + } + return builder + } + + private fun absorb(draft: Draft, answer: UpstreamAnswer) { + val now = clock.millis() + for (name in SESSION_COOKIES) { + val value = UpstreamHttp.sessionCookie(answer.url, answer.headers, name, now) ?: continue + // Only a value that can be sent back as one cookie; anything else + // would smuggle a second one onto every later call. + if (UpstreamValues.cookieValueOk(value)) draft.cookies[name] = value + } + } + + internal companion object { + const val LOGINDATA_PATH = "/webapi/logindata" + const val GETDATA_PATH = "/webapi/auth/getdata" + const val LOGIN_PATH = "/webapi/login" + const val LOGOUT_PATH = "/webapi/auth/logout" + + /** The session's cookies worth carrying: the session, and the ESRN security module's. */ + val SESSION_COOKIES: List = listOf("NSSESSIONID", "ESRNSec") + + const val ACCEPT = "application/json, text/plain, */*" + private const val ROLE_QUESTION = "choose-session-role" + private const val MESSAGE_LIMIT = 200 + + /** + * The server's `_looks_refused`: a `403`, or a page that is not JSON and + * carries a firewall's words in its first 2000 characters. + */ + fun looksRefused(answer: UpstreamAnswer): Boolean { + if (answer.code == 403) return true + val type = answer.contentType + if ("html" in type || "json" !in type) { + val head = answer.body.take(2000) + return UpstreamMarkers.WAF.any { it in head } + } + return false + } + + /** The server's `_decode`: a JSON body, or the failure its absence means. */ + fun decode(answer: UpstreamAnswer): JsonElement { + if (answer.code >= 500 || answer.code == 429) throw UpstreamFailure.Unavailable() + return UpstreamJson.parse(answer.body) ?: throw UpstreamFailure.Unexpected() + } + + /** The server's `_consume_login`, answer for answer. */ + fun consumeLogin(answer: UpstreamAnswer, triedRole: Boolean): Outcome { + val status = answer.code + if (status == 409) throw UpstreamFailure.BadCredentials(loginMessage(UpstreamJson.parse(answer.body))) + if (status == 429 || status >= 500) throw UpstreamFailure.Unavailable() + val body = UpstreamJson.parse(answer.body) as? JsonObject ?: throw UpstreamFailure.Unexpected() + val entry = UpstreamJson.string(body["entryPoint"]) + if (entry != null && ROLE_QUESTION in entry && !triedRole) { + return Outcome.NeedsRole(pickParentRole(body)) + } + val at = UpstreamJson.string(body["at"]) + if (at.isNullOrEmpty()) throw UpstreamFailure.BadCredentials(loginMessage(body)) + // Accepted, but not a value that can go in a header whole: a shape + // this code does not know, not a wrong password. + if (!UpstreamValues.headerValueOk(at)) throw UpstreamFailure.Unexpected() + val timeOut = UpstreamJson.integer(body["timeOut"]) + ?.takeIf { it.signum() != 0 && it.bitLength() < 63 } + ?.toLong() + return Outcome.Accepted(at, timeOut) + } + + /** `message`, else `errorMessage`, if either is non-blank text; cut to 200 characters. */ + fun loginMessage(source: JsonElement?): String? { + val body = source as? JsonObject ?: return null + val picked = body["message"]?.takeIf(UpstreamJson::truthy) ?: body["errorMessage"] + val text = UpstreamJson.string(picked)?.trim()?.takeIf { it.isNotEmpty() } ?: return null + return text.cutCodePoints(MESSAGE_LIMIT) + } + + /** + * The role to sign in as: the first parent's, else the first role's — + * the server's `_pick_parent_role`. A role is `entry.role` or the entry + * itself, and counts only with an id that is a JSON string or integer. + */ + fun pickParentRole(body: JsonObject): String? { + val info = body["accountInfo"] + var roles: JsonElement? = (info as? JsonObject)?.get("userRoles") + if (!UpstreamJson.truthy(roles)) roles = body["userRoles"] + val list = roles as? JsonArray ?: return null + val usable = list.mapNotNull { entry -> + val holder = entry as? JsonObject ?: return@mapNotNull null + val role = (if ("role" in holder) holder["role"] else holder) as? JsonObject + ?: return@mapNotNull null + val id = UpstreamJson.scalarText(role["id"]).takeIf { it.isNotEmpty() } + ?: return@mapNotNull null + id to UpstreamJson.string(role["name"]).orEmpty() + } + return usable.firstOrNull { (_, name) -> UpstreamMarkers.PARENT_ROLE in name }?.first + ?: usable.firstOrNull()?.first + } + + /** Python's `text[:limit]`: whole code points, never half a surrogate pair. */ + private fun String.cutCodePoints(limit: Int): String { + if (codePointCount(0, length) <= limit) return this + return substring(0, offsetByCodePoints(0, limit)) + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt new file mode 100644 index 00000000..c5e49f03 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt @@ -0,0 +1,109 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Clock +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import okhttp3.HttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody + +/** + * Petersburg's sign-in, on the phone: the password goes to + * `dnevnik2.petersburgedu.ru` and nowhere else. + * + * A port of the server's `PetersburgClient.login` (`petersburg/client.py`), + * including its order of questions — `5xx` before `400/401/403`, the cookie + * before the body — and held to it by the `petersburg.login_cases` of the + * shared vectors. One reading differs from the server's other calls on + * purpose, as it does on the server: a `200` that is not JSON is an unreadable + * answer, never «your session ended». Nobody is signed in yet, and reading it + * as a session problem sent the person back to the form they were already + * looking at, in a loop with no way out. + */ +internal class PetersburgSignIn( + private val client: OkHttpClient, + private val origin: HttpUrl, + private val clock: Clock = Clock.systemUTC(), +) { + + suspend fun signIn(target: DiaryTarget, password: String): UpstreamSession.Petersburg { + val login = target.login.trim() + val request = Request.Builder() + .url(origin.newBuilder().encodedPath(LOGIN_PATH).build()) + .header("Accept", "application/json") + .header("Accept-Charset", "UTF-8") + .post(body(login, password).toString().toRequestBody(JSON)) + .build() + val answer = UpstreamHttp.fetch(client, request) + val token = read(answer, clock.millis()) + return UpstreamSession.Petersburg( + target = target.copy(login = login), + token = token, + openedAt = clock.instant(), + ) + } + + internal companion object { + const val LOGIN_PATH = "/api/user/auth/login" + const val SESSION_COOKIE = "X-JWT-Token" + + private val JSON = "application/json".toMediaType() + + /** + * Their field names, including the two that look like leftovers: + * sending fewer gets a 400. `activation_code` is an explicit `null`, + * which the app's usual `Json` (nulls dropped) would not write. + */ + fun body(login: String, password: String): JsonObject = buildJsonObject { + put("type", "email") + put("login", login) + put("activation_code", JsonNull) + put("password", password) + put("_isEmpty", false) + } + + /** The session this answer issued, or the failure it means. */ + fun read(answer: UpstreamAnswer, nowMillis: Long): String { + if (answer.code >= 500) throw UpstreamFailure.Unavailable() + if (answer.code == 400 || answer.code == 401 || answer.code == 403) { + throw UpstreamFailure.BadCredentials(null) + } + val body = UpstreamJson.parse(answer.body) as? JsonObject + // Not JSON at any status, including a 200 of HTML and a 3xx that + // was not followed; or JSON that is not an object. + ?: throw UpstreamFailure.Unexpected() + val data = body["data"] + val fields: JsonObject? = when (data) { + is JsonObject -> data + null, JsonNull -> { + // Some errors answer 200 with only a message. + val message = UpstreamJson.string(body["message"])?.trim()?.takeIf { it.isNotEmpty() } + ?: firstError(body) + throw UpstreamFailure.Unexpected(message) + } + // A list or a scalar: nothing to read a token from, but the + // cookie may still carry one, as on the server. + else -> null + } + // The cookie first: the two have been seen to differ, and the + // cookie is the one later calls accept. + val token = UpstreamHttp.sessionCookie(answer.url, answer.headers, SESSION_COOKIE, nowMillis) + ?: fields?.let { UpstreamJson.string(it["token"])?.trim()?.takeIf(String::isNotEmpty) } + return token ?: throw UpstreamFailure.Unexpected() + } + + private fun firstError(body: JsonObject): String? { + val errors = body["errors"] as? kotlinx.serialization.json.JsonArray ?: return null + val first = errors.firstOrNull() ?: return null + return when (first) { + is JsonObject -> UpstreamJson.string(first["message"])?.trim()?.takeIf { it.isNotEmpty() } + else -> UpstreamJson.string(first) + } + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectory.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectory.kt new file mode 100644 index 00000000..d6a32539 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectory.kt @@ -0,0 +1,114 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +/** + * A «Сетевой город» region the phone may talk to. + * + * @property origin scheme, host and port only — Sakhalin's `:11111` included. + * @property password whether a login and password get in at all; `false` where + * the region takes Госуслуги only, and then nothing is sent. + * @property handoffUrl where to send somebody the app cannot sign in for: the + * catalog's `handoff_url`, or the system's own site when it has none. + */ +data class NetSchoolRegion( + val key: String, + val origin: HttpUrl, + val password: Boolean, + val zone: String, + val handoffUrl: String?, +) + +/** + * The only source of a host the phone sends a diary request to. + * + * Nothing typed and nothing received ever becomes a host: a region is picked by + * its catalog key, the key finds a row here, and the row's origin is where the + * request goes. The one piece of user input that reaches a diary at all — a + * school search — travels as a query parameter. + */ +interface UpstreamDirectory { + + /** Petersburg's one server, or `null` if the catalog does not carry it. */ + val petersburg: HttpUrl? + + /** The region under [regionKey], or `null` when it is not allow-listed. */ + fun netschool(regionKey: String?): NetSchoolRegion? + + /** Every origin above, for the client's guard. */ + fun allowedOrigins(): Set +} + +/** + * [UpstreamDirectory] over the bundled catalog. + * + * An origin that is not `https`, or that carries a path, a query, a fragment or + * credentials, is dropped rather than used: an `http` origin would send the + * salted password and the session in clear text, and anything after the + * authority would be a way to point a request somewhere the origin does not + * say. The generator refuses the same things; this is the second lock. + */ +class CatalogUpstreamDirectory(catalog: RegionCatalog) : UpstreamDirectory { + + override val petersburg: HttpUrl? = catalog.platforms + .values + .firstOrNull { it.provider == PETERSBURG_PROVIDER } + ?.origin + ?.let(::originOrNull) + + private val regions: Map = buildMap { + for (region in catalog.regions) { + for (system in region.systems) { + val row = system.netschool ?: continue + val origin = originOrNull(row.origin) ?: continue + if (row.region in this) continue + put( + row.region, + NetSchoolRegion( + key = row.region, + origin = origin, + password = row.password, + zone = row.zone.ifBlank { region.zone }, + // Opened in the browser, never requested by the app, + // so a path is fine; plain http is not. + handoffUrl = (system.handoffUrl ?: system.webUrl) + ?.takeIf { it.toHttpUrlOrNull()?.scheme == "https" }, + ), + ) + } + } + } + + private val origins: Set = buildSet { + petersburg?.let { add(UpstreamOrigin.of(it)) } + regions.values.forEach { add(UpstreamOrigin.of(it.origin)) } + } + + override fun netschool(regionKey: String?): NetSchoolRegion? = regionKey?.let(regions::get) + + override fun allowedOrigins(): Set = origins + + companion object { + private const val PETERSBURG_PROVIDER = "petersburg" + + /** + * [raw] as a bare `https` origin, or `null`. Public to this module's + * tests because the rule is the allow-list's whole defence. + */ + internal fun originOrNull(raw: String): HttpUrl? { + val url = raw.toHttpUrlOrNull() ?: return null + val bare = url.scheme == "https" && + url.username.isEmpty() && + url.password.isEmpty() && + url.encodedPath == "/" && + url.query == null && + url.fragment == null && + // `toHttpUrl` normalises a trailing slash in, so the raw text is + // what says whether anything followed the authority. + !raw.removePrefix("https://").contains('/') + return url.takeIf { bare } + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamFailure.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamFailure.kt new file mode 100644 index 00000000..5369b21c --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamFailure.kt @@ -0,0 +1,79 @@ +package com.lumenpearson.lessons.core.data.upstream + +import java.io.IOException +import okhttp3.HttpUrl + +/** + * What went wrong between the phone and a diary's own server. + * + * The family mirrors the server's `providers/diary/errors.py` one for one where + * the two sides meet the same answer, because the shared vectors + * (`server/tests/vectors/diary_protocol.json`) name the failures in those words + * and both implementations are held to them. It is kept apart from + * `DiaryFailure`, which is about *our* server's answers: a `503` from us and a + * `503` from a regional server mean different things to the person holding the + * phone, and one type for both would have to be told apart by where it came + * from, which is exactly what a type is for. + * + * No case carries the password or any character of it. [BadCredentials] carries + * only what the diary said, which is how a failure message ends up on a screen + * without a secret riding along. + */ +sealed class UpstreamFailure(message: String, cause: Throwable? = null) : Exception(message, cause) { + + /** The diary judged the login and password and refused them. */ + class BadCredentials(val upstreamMessage: String?) : + UpstreamFailure("The diary refused the credentials") + + /** + * The region lets people in through Госуслуги only: the catalog said so + * before anything was sent, or `logindata` said so before a password was. + */ + class SignInUnsupported : UpstreamFailure("The diary takes no password sign-in") + + /** + * Nothing judged what was typed: a transport failure, a timeout, a `5xx`, + * a `429`, or a `getdata` without a salt that can be used. Worth retrying. + */ + class Unavailable(val reason: Throwable? = null) : + UpstreamFailure("The diary is not answering", reason) { + /** A timeout is its own sentence on the screen; see `DiarySignInProblem.Timeout`. */ + val timedOut: Boolean get() = reason.isTimeout() + } + + /** The phone could not resolve or route to the host at all. */ + class Offline(val reason: Throwable) : UpstreamFailure("No network", reason) + + /** + * A `403` or a firewall page: the diary will not talk to this phone's + * address. HTTP-level only — see `NetSchoolSignIn` for why a refused + * connection is not read this way on a phone. + */ + class AddressRefused : UpstreamFailure("The diary refuses this address") + + /** A TLS chain the phone does not trust; nothing is relaxed to get past it. */ + class Untrusted(val reason: Throwable) : UpstreamFailure("Untrusted certificate", reason) + + /** An answer this port cannot read. Never a re-authentication loop. */ + class Unexpected(val detail: String? = null) : + UpstreamFailure("The diary answered in an unreadable way" + (detail?.let { ": $it" } ?: "")) +} + +/** + * A request to a host outside the allow-list, refused before a socket opens. + * + * An [IOException] rather than an [UpstreamFailure] because it is thrown from + * an OkHttp interceptor, and in OkHttp 5 anything else thrown there under + * `enqueue` takes the dispatcher thread down with it. It is a bug in this app + * whenever it fires — every URL is built from the catalog — so it is reported + * as one, never as «нет сети». + */ +class UpstreamNotAllowed(url: HttpUrl) : IOException("Not an allow-listed diary origin: ${url.scheme}://${url.host}:${url.port}") + +/** Whether [this] or anything it was caused by is a timeout. */ +internal fun Throwable?.isTimeout(): Boolean = + generateSequence(this) { it.cause }.take(8).any { + it is java.net.SocketTimeoutException || + // OkHttp's call timeout is a bare InterruptedIOException named «timeout». + (it is java.io.InterruptedIOException && it.message?.contains("timeout", ignoreCase = true) == true) + } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt new file mode 100644 index 00000000..88ef16cd --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt @@ -0,0 +1,206 @@ +package com.lumenpearson.lessons.core.data.upstream + +import java.io.IOException +import java.net.NoRouteToHostException +import java.net.UnknownHostException +import java.security.cert.CertPathValidatorException +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.suspendCancellableCoroutine +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.Headers +import okhttp3.HttpUrl +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response + +/** Scheme, host and port: what makes two URLs the same server. */ +data class UpstreamOrigin(val scheme: String, val host: String, val port: Int) { + companion object { + fun of(url: HttpUrl): UpstreamOrigin = UpstreamOrigin(url.scheme, url.host, url.port) + } +} + +/** + * One diary answer, read whole on OkHttp's thread so the caller never blocks + * on a socket and never has to remember to close anything. + */ +internal class UpstreamAnswer( + val code: Int, + val headers: Headers, + val url: HttpUrl, + val body: String, +) { + val contentType: String get() = headers["Content-Type"].orEmpty() +} + +/** + * The client the phone talks to the diaries with — and nothing else does. + * + * It shares nothing with the client that talks to our server, and that is the + * point: that one rewrites every host to the configured server + * (`BaseUrlInterceptor`) and signs requests with the class and diary bearers by + * path (`AuthInterceptor`, `DiaryAuthInterceptor`). A diary request through it + * would go to our server instead, or carry our bearer to somebody else's. + * `GithubApi.client` is the same arrangement for the same reason. + */ +internal object UpstreamHttp { + + /** + * Byte-identical to the server's `providers/diary/http.py` and + * `petersburg/client.py`, and pinned to both by the vectors: these + * upstreams are browsers' backends and have been known to answer + * differently to anything that does not look like one. + */ + const val USER_AGENT: String = + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + + "Chrome/124.0.0.0 Safari/537.36" + + /** Larger than any sign-in answer by orders of magnitude; past it, something is wrong. */ + private const val MAX_BODY_BYTES = 2L * 1024 * 1024 + + /** + * @param allowed read per request, so the guard and the catalog it comes + * from are one answer rather than a copy taken at startup. + */ + fun client(allowed: () -> Set): OkHttpClient = OkHttpClient.Builder() + // A redirect is the one way around an allow-list: a region answering + // 302 to another host would carry the next request there. The + // server's client refuses them for the same reason (`http.py`). + .followRedirects(false) + .followSslRedirects(false) + // The session travels per request, never in a jar, so two sign-ins — + // two families on one phone, or one family twice — cannot meet. + .cookieJar(CookieJar.NO_COOKIES) + // `getdata`'s salt is one-shot: a silent re-POST of the login would + // come back 409 and read as a wrong password. + .retryOnConnectionFailure(false) + .cache(null) + // A phone on a school's mobile signal. Not a parity point with the + // server, whose datacentre link is another matter. + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(20, TimeUnit.SECONDS) + .writeTimeout(10, TimeUnit.SECONDS) + .callTimeout(40, TimeUnit.SECONDS) + .addInterceptor(OriginGuard(allowed)) + .addInterceptor(BrowserHeaders) + .build() + + /** + * The named session cookie an answer carries, or `null`: the Kotlin twin + * of the server's `session_cookie` / `_session_cookie`, held to them by the + * vectors. Only a live cookie counts — a deletion (`Max-Age=0`, which + * OkHttp parses as an empty value that expired in the past) is not a + * session — and of several, the last in header order wins, which is what a + * browser sending the next request would use. + */ + fun sessionCookie(url: HttpUrl, headers: Headers, name: String, nowMillis: Long): String? = + Cookie.parseAll(url, headers) + .lastOrNull { it.name == name && it.value.isNotEmpty() && it.expiresAt > nowMillis } + ?.value + + /** + * One exchange, read whole, with every transport failure already turned + * into the [UpstreamFailure] it means. Cancelling the caller cancels the + * call. + */ + suspend fun fetch(client: OkHttpClient, request: Request): UpstreamAnswer { + val call = client.newCall(request) + return try { + call.await() + } catch (refused: UpstreamNotAllowed) { + throw refused + } catch (failure: IOException) { + throw classify(failure) + } + } + + /** What a transport failure means on a phone. */ + fun classify(failure: IOException): UpstreamFailure { + val chain = generateSequence(failure) { it.cause }.take(8).toList() + return when { + // A region signed only by a root the phone does not trust. Nothing + // is relaxed to get past it; the screen says so instead. + chain.any { + it is SSLHandshakeException || + it is SSLPeerUnverifiedException || + it is CertPathValidatorException + } -> UpstreamFailure.Untrusted(failure) + chain.any { it is UnknownHostException || it is NoRouteToHostException } -> + UpstreamFailure.Offline(failure) + else -> UpstreamFailure.Unavailable(failure) + } + } + + private suspend fun Call.await(): UpstreamAnswer = suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { cancel() } + enqueue( + object : Callback { + override fun onFailure(call: Call, e: IOException) { + continuation.resumeWithException(e) + } + + override fun onResponse(call: Call, response: Response) { + val answer = try { + response.use { read(it) } + } catch (e: IOException) { + continuation.resumeWithException(e) + return + } + continuation.resume(answer) + } + }, + ) + } + + private fun read(response: Response): UpstreamAnswer { + val body = response.body + val source = body.source() + source.request(MAX_BODY_BYTES + 1) + if (source.buffer.size > MAX_BODY_BYTES) { + throw IOException("diary answer larger than $MAX_BODY_BYTES bytes") + } + return UpstreamAnswer( + code = response.code, + headers = response.headers, + url = response.request.url, + body = body.string(), + ) + } +} + +/** + * Refuses any URL whose scheme, host and port are not an allow-listed origin, + * before a socket opens. Every URL is built from the bundled catalog, so this + * firing is a bug; it is here so that the bug is a refusal rather than a + * request to wherever a string happened to point. + */ +internal class OriginGuard(private val allowed: () -> Set) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val url = chain.request().url + if (UpstreamOrigin.of(url) !in allowed()) throw UpstreamNotAllowed(url) + return chain.proceed(chain.request()) + } +} + +/** + * A browser's `User-Agent`, and a refusal of any `Authorization` header: no + * bearer of ours has any business on a request to a diary, and one appearing + * here would mean something was wired to the wrong client. + */ +internal object BrowserHeaders : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + if (request.header("Authorization") != null) throw UpstreamNotAllowed(request.url) + return chain.proceed( + request.newBuilder().header("User-Agent", UpstreamHttp.USER_AGENT).build(), + ) + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt new file mode 100644 index 00000000..da866d9a --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt @@ -0,0 +1,93 @@ +package com.lumenpearson.lessons.core.data.upstream + +import java.math.BigInteger +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** + * Reading a diary's JSON the way the server's Python reads it. + * + * The ports are held to the server by the shared vectors, and the vectors are + * full of answers that are the wrong shape on purpose — a `cacheVer` of `true`, + * a `salt` of `333`, an `id` of `6.0`. Python's `isinstance` checks and + * truthiness decide those, so these helpers spell the same decisions out, one + * each, rather than leaving every call site to guess what `if not x` meant. + */ +internal object UpstreamJson { + + private val json = Json { isLenient = false } + + private val INTEGER = Regex("-?(0|[1-9][0-9]*)") + + /** The parsed body, or `null` for one that is not JSON at all. */ + fun parse(text: String): JsonElement? = try { + json.parseToJsonElement(text) + } catch (_: Exception) { + null + } + + /** + * A JSON string as itself, a JSON integer as its digits, and anything else + * as `""` — the server's `_scalar_text`. A `true` is not `"true"` and a + * missing value is not `"null"`: both used to be posted back upstream as + * words the diary never sent. + */ + fun scalarText(value: JsonElement?): String { + val primitive = value as? JsonPrimitive ?: return "" + if (primitive is JsonNull) return "" + if (primitive.isString) return primitive.content + return integerOrNull(primitive)?.toString().orEmpty() + } + + /** A JSON integer, or `null` — never a bool, a float, or a string of digits. */ + fun integer(value: JsonElement?): BigInteger? { + val primitive = value as? JsonPrimitive ?: return null + if (primitive is JsonNull || primitive.isString) return null + return integerOrNull(primitive) + } + + /** A JSON string's content, or `null` for anything else. */ + fun string(value: JsonElement?): String? = + (value as? JsonPrimitive)?.takeIf { it !is JsonNull && it.isString }?.content + + /** + * Python's truthiness: `null`, `false`, zero, `""`, `[]` and `{}` are + * false; everything else, including the string `"false"`, is true. + */ + fun truthy(value: JsonElement?): Boolean = when (value) { + null, JsonNull -> false + is JsonObject -> value.isNotEmpty() + is JsonArray -> value.isNotEmpty() + is JsonPrimitive -> when { + value.isString -> value.content.isNotEmpty() + value.content == "true" -> true + value.content == "false" -> false + else -> value.content.toBigDecimalOrNull()?.signum() != 0 + } + } + + private fun integerOrNull(primitive: JsonPrimitive): BigInteger? = + primitive.content.takeIf { INTEGER.matches(it) }?.let(::BigInteger) +} + +/** + * The two ways a stored session value can go into a header and stay one + * value, shared with the server (`providers/diary/http.py`) and pinned to it by + * the vectors: an RFC 6265 cookie octet run, and an RFC 7235 `token68`. + */ +internal object UpstreamValues { + + /** A cookie value that cannot become two cookies: no `;`, space, quote, comma or backslash. */ + val COOKIE_VALUE: Regex = Regex("[\\x21\\x23-\\x2B\\x2D-\\x3A\\x3C-\\x5B\\x5D-\\x7E]{1,4096}") + + /** A bearer-shaped header value that cannot end the header and start another. */ + val HEADER_TOKEN: Regex = Regex("[A-Za-z0-9._~+/=-]+") + + fun cookieValueOk(value: String?): Boolean = value != null && COOKIE_VALUE.matches(value) + + fun headerValueOk(value: String?): Boolean = value != null && HEADER_TOKEN.matches(value) +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamMarkers.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamMarkers.kt new file mode 100644 index 00000000..0a798160 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamMarkers.kt @@ -0,0 +1,34 @@ +package com.lumenpearson.lessons.core.data.upstream + +/** + * The diaries' own words, matched against their answers. + * + * **The one Kotlin file in `src/main` that may hold Cyrillic outside + * `@Preview` data and the timezone list**, and on purpose: these are not + * strings anybody reads. They are the upstream's protocol — the heading of a + * regional firewall's refusal page, the name «Сетевой город» gives a parent's + * role — and they have to be matched byte for byte, in the language the + * upstream writes them in. A string resource would be translated into English + * by the next person who saw an untranslated name, and the match would stop + * matching in the English build only. + * + * `DiaryProtocolVectorsTest` holds both constants to + * `server/tests/vectors/diary_protocol.json`, which the server's own client is + * held to as well, so the phone and the server cannot come to recognise a + * refusal differently. + */ +internal object UpstreamMarkers { + + /** + * Markers of a «we do not serve this address» page, whatever its status. + * The order is the server's `_WAF_MARKERS`, which the vectors pin. + */ + val WAF: List = listOf("Доступ к сайту", "Request forbidden", "Access denied", "blocked") + + /** + * Part of the name «Сетевой город» gives a parent's role — «Родитель», + * «Родители» — which is the role to sign in as when an account is also + * staff and the server asks which one it is today. + */ + const val PARENT_ROLE: String = "Родител" +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamSession.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamSession.kt new file mode 100644 index 00000000..2f22ec66 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamSession.kt @@ -0,0 +1,61 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Instant + +/** + * What a sign-in on the phone ends holding: a session the diary itself issued, + * about to be handed to our server and then forgotten. + * + * Deliberately awkward to keep. Not a data class, so nothing prints its fields; + * not `@Serializable`, `Parcelable` or `java.io.Serializable`, so it cannot be + * put in a saved-state bundle — which the system writes to disk — or in + * DataStore or Room by accident; and [toString] is final and says nothing. The + * secret fields are `internal`, so no screen can read them either: the only + * thing that does is `DiarySignInImpl.register`, on its way to our server. + * + * It lives in memory for the seconds between the sign-in and the registration. + * Process death in between means signing in again, which is the price of + * never writing a live credential down. + */ +sealed class UpstreamSession { + + /** Which diary, region, school and login this session is for. Never secret. */ + abstract val target: DiaryTarget + + /** When the diary handed it over; an old one is not registered. */ + internal abstract val openedAt: Instant + + /** + * Set once our server has accepted it. From then on the session is the + * server's to use and to end: registering it twice would mint a second + * row, and saying goodbye upstream would end the one the server holds — + * so both refuse a spent session, whoever still has a reference to it. + */ + @Volatile + internal var spent: Boolean = false + + final override fun toString(): String = "UpstreamSession(${target.provider.wire}, )" + + /** Petersburg's session: the `X-JWT-Token` it set, or `data.token`. */ + class Petersburg internal constructor( + override val target: DiaryTarget, + internal val token: String, + override val openedAt: Instant, + ) : UpstreamSession() + + /** + * «Сетевой город»'s session: the `at` bearer, its session cookies, and the + * `ver` its `logindata` gave (the server's own sign-in keeps the same one, + * for the SecurityWarning acknowledgement and the logout). + */ + class NetSchool internal constructor( + override val target: DiaryTarget, + internal val at: String, + internal val cookies: Map, + internal val ver: String?, + /** The login's `timeOut` in milliseconds, when it was a JSON integer. */ + internal val timeOut: Long?, + override val openedAt: Instant, + ) : UpstreamSession() +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalogTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalogTest.kt new file mode 100644 index 00000000..c58e9564 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalogTest.kt @@ -0,0 +1,74 @@ +package com.lumenpearson.lessons.core.data.catalog + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The bundled region catalog, read by the model the app reads it with. + * + * The file is the server's generator's output (`server/app/catalog/data/ + * regions.json`), put on this module's asset path and its test classpath in + * place. A catalog that does not parse here would be a phone that cannot pick a + * region or sign in anywhere, and nothing else would say so before a device. + */ +class RegionCatalogTest { + + private val text: String by lazy { + javaClass.classLoader!!.getResourceAsStream(RegionCatalog.ASSET)!! + .bufferedReader(Charsets.UTF_8).use { it.readText() } + } + + @Test + fun `the bundled catalog parses whole`() { + val catalog = RegionCatalog.parse(text) + + assertEquals(1, catalog.schema) + assertEquals(89, catalog.regions.size) + assertEquals(89, catalog.regions.map { it.key }.toSet().size) + assertNotNull(catalog.survey.month) + assertTrue(catalog.search.stopWords.isNotEmpty()) + } + + /** K16: names live in the JSON only, so the English twin is held here rather than by the resource test. */ + @Test + fun `every region and platform has a name in both languages`() { + val catalog = RegionCatalog.parse(text) + for (region in catalog.regions) { + assertTrue(region.key, region.nameRu.isNotBlank() && region.nameEn.isNotBlank()) + } + for ((key, platform) in catalog.platforms) { + assertTrue(key, platform.nameRu.isNotBlank() && platform.nameEn.isNotBlank()) + } + } + + /** The generator decides; the phone reads. A recommendation pointing past the list would be a crash. */ + @Test + fun `every recommendation points at a system the region has`() { + val catalog = RegionCatalog.parse(text) + for (region in catalog.regions) { + val index = region.recommended?.system ?: continue + assertTrue(region.key, index in region.systems.indices) + } + } + + @Test + fun `a newer generator's keys are ignored, not fatal`() { + val catalog = RegionCatalog.parse( + """ + { "schema": 2, "later": {"x": 1}, + "regions": [ { "key": "samara", "name_ru": "Самарская область", "name_en": "Samara Oblast", + "zone": "Europe/Samara", "future": true, + "systems": [ { "platform": "netschool", "action": "signin", "new_field": 1, + "netschool": { "region": "samara", "origin": "https://asurso.ru", + "password": true, "zone": "Europe/Samara" } } ] } ] } + """.trimIndent(), + ) + + assertEquals("https://asurso.ru", catalog.region("samara")?.systems?.single()?.netschool?.origin) + assertNull(catalog.region("tomsk")) + assertNull(catalog.region(null)) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt new file mode 100644 index 00000000..b6deefec --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt @@ -0,0 +1,130 @@ +package com.lumenpearson.lessons.core.data.catalog + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The region search, over the real bundled catalog read from the test + * classpath — the file the app ships, with the lexicon the server's directory + * reads too. + */ +class RegionSearchTest { + + private val catalog: RegionCatalog by lazy { + RegionCatalog.parse( + javaClass.classLoader!!.getResourceAsStream(RegionCatalog.ASSET)!! + .bufferedReader(Charsets.UTF_8).use { it.readText() }, + ) + } + + private val search by lazy { RegionSearch(catalog) } + + private fun keys(query: String) = search.search(query).map { it.region.key } + + private fun first(query: String) = search.search(query).firstOrNull()?.region?.key + + @Test + fun `a region's own name finds it first, in Russian and in English`() { + assertEquals("samara", first("Самарская область")) + assertEquals("samara", first("самарская")) + assertEquals("samara", first("Samara Oblast")) + assertEquals("moscow", first("Москва")) + assertEquals("moscow", first("moscow")) + } + + @Test + fun `yo and dashes fold`() { + assertEquals("khmao", first("ханты мансийский")) + assertEquals("khmao", first("Ханты–Мансийский")) + assertEquals("moscow-oblast", first("Королев")) + assertEquals("moscow-oblast", first("Королёв")) + } + + @Test + fun `type words are ignored`() { + assertEquals(first("Татарстан"), first("Республика Татарстан")) + assertEquals("leningrad", first("ленинградская обл")) + } + + @Test + fun `layout swap finds Samara from cfvfhf`() { + assertEquals("samara", first("cfvfhf")) + } + + @Test + fun `transliteration finds Moscow from moskva`() { + assertEquals("moscow", first("moskva")) + } + + @Test + fun `a code finds its region`() { + assertEquals(listOf("leningrad"), keys("47")) + assertEquals(listOf("saint-petersburg"), keys("78")) + assertEquals(listOf("adygea"), keys("1")) + } + + @Test + fun `aliases and cities`() { + assertEquals("saint-petersburg", first("Питер")) + assertEquals("leningrad", first("Ленобласть")) + assertEquals("khmao", first("ХМАО")) + assertEquals("leningrad", first("Гатчина")) + assertEquals("samara", first("Тольятти")) + val city = search.search("Тольятти").first() + assertEquals(MatchVia.CITY, city.via) + } + + @Test + fun `Altai returns both`() { + val both = keys("Алтай") + assertTrue(both.containsAll(listOf("altai-republic", "altai-krai"))) + } + + @Test + fun `ranking prefers the name over a city`() { + // «Самара» is a city of Samara Oblast and the start of nothing's name + // exactly; «Москва» is a name, and Moscow Oblast only starts with it. + val moscow = search.search("Москва") + assertEquals("moscow", moscow.first().region.key) + assertEquals(MatchVia.NAME, moscow.first().via) + } + + @Test + fun `a blank query is the whole list in its order`() { + val all = search.search(" ") + assertEquals(89, all.size) + assertEquals(all.sortedBy { it.region.order }, all) + } + + @Test + fun `nonsense finds nothing`() { + assertEquals(emptyList(), keys("qqqqzzzz")) + } + + /** + * The server's own table (`test_directory.py`, + * `test_a_type_word_and_a_short_number_is_answered_without_dadata`), plus + * the edges of the same rule. + */ + @Test + fun `isGenericSchool is the server's rule`() { + for (generic in listOf("Школа № 5", "СОШ 12", "гимназия 3", "МБОУ СОШ №7", "лицей N 2", "школа", "№5")) { + assertTrue(generic, search.isGenericSchool(generic)) + } + for (asked in listOf("лицей 1535", "гимназия 1 Казань", "Школа 179", "Президентский лицей")) { + assertFalse(asked, search.isGenericSchool(asked)) + } + } + + @Test + fun `looksLikeSchool tells a school from a place`() { + for (school in listOf("лицей 1535", "гимназия 1 Казань", "школа 5", "1535", "5 казань")) { + assertTrue(school, search.looksLikeSchool(school)) + } + for (place in listOf("Самара", "Тольятти", "47", "Ханты-Мансийск", "moskva")) { + assertFalse(place, search.looksLikeSchool(place)) + } + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt new file mode 100644 index 00000000..59e07534 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt @@ -0,0 +1,194 @@ +package com.lumenpearson.lessons.core.data.catalog + +import com.lumenpearson.lessons.core.data.diary.statusError +import com.lumenpearson.lessons.core.data.network.DirectoryApi +import com.lumenpearson.lessons.core.data.network.SchoolRegionDto +import com.lumenpearson.lessons.core.data.network.SchoolRegionsDto +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import java.io.IOException +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The school directory as the phone asks it: what is never asked, how every + * refusal is told apart by its header, and how the answer is placed against the + * bundled catalog. + */ +class SchoolDirectoryTest { + + private val catalog: RegionCatalog by lazy { + RegionCatalog.parse( + javaClass.classLoader!!.getResourceAsStream(RegionCatalog.ASSET)!! + .bufferedReader(Charsets.UTF_8).use { it.readText() }, + ) + } + + private class FakeDirectoryApi( + var answer: SchoolRegionsDto = SchoolRegionsDto(), + var failure: Throwable? = null, + ) : DirectoryApi { + val asked = mutableListOf() + override suspend fun schoolRegions(query: String): SchoolRegionsDto { + asked += query + failure?.let { throw it } + return answer + } + } + + private object NoSchools : DiarySchoolSearch { + override suspend fun search(regionKey: String, query: String): Result> = + Result.success(listOf(DiarySchool(1, "$regionKey:$query", null))) + } + + private fun directory(api: DirectoryApi) = ServerSchoolDirectory( + api = api, + search = { RegionSearch(catalog) }, + schools = NoSchools, + ioDispatcher = UnconfinedTestDispatcher(), + ) + + @Test + fun `a query under three characters asks nothing`() = runTest { + val api = FakeDirectoryApi() + + val result = directory(api).regionsForSchool(" л1 ") + + assertEquals(DirectoryProblem.TooShort, result.exceptionOrNull()) + assertTrue(api.asked.isEmpty()) + } + + /** A generic name places nothing and would spend the caller's searches and the shared allowance. */ + @Test + fun `a generic name is answered here and asks nothing`() = runTest { + val api = FakeDirectoryApi() + + val hits = directory(api).regionsForSchool("Школа № 5").getOrThrow() + + assertTrue(hits.generic) + assertTrue(hits.hits.isEmpty()) + assertTrue(api.asked.isEmpty()) + } + + @Test + fun `the query is sent as the server normalises it`() = runTest { + val api = FakeDirectoryApi() + + directory(api).regionsForSchool(" лицей 1535 ") + + assertEquals(listOf("лицей 1535"), api.asked) + } + + @Test + fun `hits are placed against the bundled catalog, and an unknown key is kept unplaced`() = runTest { + val api = FakeDirectoryApi( + answer = SchoolRegionsDto( + query = "лицей 1535", + regions = listOf( + SchoolRegionDto(region = "moscow", code = "77", schools = 3, cities = listOf("Москва")), + SchoolRegionDto(region = "somewhere-new", code = "99", schools = 1), + SchoolRegionDto(region = null, code = "94", label = "г Байконур", schools = 1), + ), + truncated = true, + ), + ) + + val hits = directory(api).regionsForSchool("лицей 1535").getOrThrow() + + assertEquals("moscow", hits.hits[0].region?.key) + assertNull(hits.hits[0].label) + assertNull(hits.hits[1].region) + assertEquals("somewhere-new", hits.hits[1].label) + assertNull(hits.hits[2].region) + assertEquals("г Байконур", hits.hits[2].label) + assertTrue(hits.truncated) + } + + @Test + fun `every refusal is told apart by its header, not its words`() = runTest { + val cases = listOf( + statusError(503, DirectoryApi.UNAVAILABLE_HEADER to "disabled") to DirectoryProblem.Disabled, + statusError(503, DirectoryApi.UNAVAILABLE_HEADER to "spent", "Retry-After" to "3600") to + DirectoryProblem.Spent(3600), + statusError(503, DirectoryApi.UNAVAILABLE_HEADER to "upstream") to DirectoryProblem.Upstream, + statusError(503) to DirectoryProblem.Upstream, + statusError(504) to DirectoryProblem.Upstream, + statusError(429, "Retry-After" to "120") to DirectoryProblem.Throttled(120), + statusError(422) to DirectoryProblem.TooShort, + statusError(404) to DirectoryProblem.ServerTooOld, + IOException("no network") to DirectoryProblem.Offline, + ServerAddressMissingException() to DirectoryProblem.ServerMissing, + ) + for ((failure, expected) in cases) { + val result = directory(FakeDirectoryApi(failure = failure)).regionsForSchool("лицей 1535") + assertEquals("$failure", expected, result.exceptionOrNull()) + } + val odd = directory(FakeDirectoryApi(failure = statusError(500))).regionsForSchool("лицей 1535") + assertTrue(odd.exceptionOrNull() is DirectoryProblem.Unexpected) + } + + @Test + fun `a region's own schools are the region's own server's`() = runTest { + val schools = directory(FakeDirectoryApi()).providerSchools("samara", "лицей").getOrThrow() + + assertEquals("samara:лицей", schools.single().name) + } + + // ---- the combined lookup ------------------------------------------------- + + private fun lookup(api: DirectoryApi) = RegionLookup( + search = { RegionSearch(catalog) }, + directory = directory(api), + ) + + @Test + fun `a place is looked up in the catalog alone`() = runTest { + val api = FakeDirectoryApi() + + val result = lookup(api).find("Тольятти") + + assertEquals(SchoolLookup.NotAsked, result.bySchool) + assertEquals("samara", result.suggested.first().key) + assertTrue(api.asked.isEmpty()) + } + + @Test + fun `a school is looked up in the directory, and its regions come first`() = runTest { + val api = FakeDirectoryApi( + answer = SchoolRegionsDto( + query = "гимназия 1 казань", + regions = listOf(SchoolRegionDto(region = "tatarstan", code = "16", schools = 2)), + ), + ) + + val result = lookup(api).find("гимназия 1 казань") + + assertTrue(result.bySchool is SchoolLookup.Found) + assertEquals("tatarstan", result.suggested.first().key) + assertEquals(1, result.suggested.count { it.key == "tatarstan" }) + } + + @Test + fun `a generic school name is said so, without a request`() = runTest { + val api = FakeDirectoryApi() + + val result = lookup(api).find("школа 5") + + assertEquals(SchoolLookup.Generic, result.bySchool) + assertTrue(api.asked.isEmpty()) + } + + @Test + fun `a directory that fails leaves the catalog's answer standing`() = runTest { + val api = FakeDirectoryApi(failure = statusError(503, DirectoryApi.UNAVAILABLE_HEADER to "spent")) + + val result = lookup(api).find("лицей 1535") + + assertEquals(SchoolLookup.Failed(DirectoryProblem.Spent(null)), result.bySchool) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/DiaryTargetStoreTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/DiaryTargetStoreTest.kt new file mode 100644 index 00000000..19fd4975 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/DiaryTargetStoreTest.kt @@ -0,0 +1,138 @@ +package com.lumenpearson.lessons.core.data.datastore + +import androidx.datastore.preferences.core.mutablePreferencesOf +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.DiaryTargetCodec +import java.time.ZoneId +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * Where this phone signs in to a diary, as it is kept: one JSON value that + * outlives the bearer, read back the same way by every flow that needs it. + * + * The edits are the ones `LessonsPreferences` runs inside DataStore's + * transaction, exercised on a plain `MutablePreferences`: what is under test is + * which keys each of them leaves behind, and none of that is about files. + */ +class DiaryTargetStoreTest { + + private val samara = DiaryTarget.netschool("samara", 1234, "Школа № 5", "ivanova", "Europe/Samara") + + @Test + fun `a target round-trips`() { + assertEquals(samara, DiaryTargetCodec.decode(DiaryTargetCodec.encode(samara))) + val petersburg = DiaryTarget.petersburg("parent@example.com") + assertEquals(petersburg, DiaryTargetCodec.decode(DiaryTargetCodec.encode(petersburg))) + } + + @Test + fun `the stored value names its version and its zone`() { + val stored = DiaryTargetCodec.encode(DiaryTarget.petersburg("parent@example.com")) + assertEquals(true, "\"v\":1" in stored) + assertEquals(true, "\"zone\":\"Europe/Moscow\"" in stored) + } + + /** A provider this build does not know is no target — never Petersburg by guess. */ + @Test + fun `an unknown provider, a later version or garbage reads as no target`() { + assertNull(DiaryTargetCodec.decode("""{"v":1,"provider":"eljur","login":"x"}""")) + assertNull(DiaryTargetCodec.decode("""{"v":2,"provider":"netschool","login":"x"}""")) + assertNull(DiaryTargetCodec.decode("not json")) + assertNull(DiaryTargetCodec.decode("")) + assertNull(DiaryTargetCodec.decode(null)) + } + + @Test + fun `legacy keys read as a Petersburg target in Moscow`() { + val prefs = mutablePreferencesOf(DiaryKeys.TOKEN to "ours", DiaryKeys.LOGIN to "parent@example.com") + + val target = prefs.toDiaryTarget()!! + assertEquals(DiaryProviderKey.PETERSBURG, target.provider) + assertEquals(ZoneId.of("Europe/Moscow"), target.zoneId()) + assertEquals(target, prefs.toDiarySession()!!.target) + } + + @Test + fun `an unknown provider reads as no target and no session`() { + val prefs = mutablePreferencesOf( + DiaryKeys.TOKEN to "ours", + DiaryKeys.LOGIN to "x", + DiaryKeys.TARGET to """{"v":1,"provider":"eljur","login":"x"}""", + ) + + assertNull(prefs.toDiaryTarget()) + // A bearer for an account this build cannot name is not sent. + assertNull(prefs.toDiarySession()) + } + + @Test + fun `a written session reads back with its target`() { + val prefs = mutablePreferencesOf() + + prefs.putDiarySession(DiarySession(login = "ivanova", token = "ours", target = samara)) + + assertEquals(DiarySession("ivanova", "ours", samara), prefs.toDiarySession()) + assertEquals(samara, prefs.toDiaryTarget()) + } + + @Test + fun `a bare 401 clears the token and keeps the target`() { + val prefs = mutablePreferencesOf() + prefs.putDiarySession(DiarySession(login = "ivanova", token = "ours", target = samara)) + prefs[DiaryKeys.STUDENT_ID] = 7L + + prefs.dropDiaryToken() + + assertNull(prefs.toDiarySession()) + assertEquals(samara, prefs.toDiaryTarget()) + assertEquals(7L, prefs[DiaryKeys.STUDENT_ID]) + } + + /** + * An install from before targets derives its target from the token and + * the login — so dropping the token would drop the target with it, unless + * it is written down first. + */ + @Test + fun `a bare 401 on a legacy install keeps its Petersburg target`() { + val prefs = mutablePreferencesOf(DiaryKeys.TOKEN to "ours", DiaryKeys.LOGIN to "parent@example.com") + + prefs.dropDiaryToken() + + assertNull(prefs.toDiarySession()) + assertEquals(DiaryTarget.petersburg("parent@example.com"), prefs.toDiaryTarget()) + } + + @Test + fun `signing out forgets the account and the pupil`() { + val prefs = mutablePreferencesOf() + prefs.putDiarySession(DiarySession(login = "ivanova", token = "ours", target = samara)) + prefs[DiaryKeys.STUDENT_ID] = 7L + + prefs.dropDiary() + + assertNull(prefs.toDiarySession()) + assertNull(prefs.toDiaryTarget()) + assertNull(prefs[DiaryKeys.STUDENT_ID]) + assertNull(prefs[DiaryKeys.LOGIN]) + } + + /** An old phone's tzdata may not know a zone the server names; midnight an hour off beats no diary. */ + @Test + fun `a zone the phone cannot read falls back to Moscow`() { + assertEquals(ZoneId.of("Europe/Moscow"), samara.copy(zone = "Mars/Olympus").zoneId()) + assertEquals(ZoneId.of("Europe/Samara"), samara.zoneId()) + } + + @Test + fun `the account key ignores case and spaces in the login, and nothing else`() { + assertEquals(samara.accountKey(), samara.copy(login = " IVANOVA ").accountKey()) + assertNotEquals(samara.accountKey(), samara.copy(region = "tomsk").accountKey()) + assertNotEquals(samara.accountKey(), DiaryTarget.petersburg("ivanova").accountKey()) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/MembershipsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/MembershipsTest.kt index 48996a4b..20e110eb 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/MembershipsTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/datastore/MembershipsTest.kt @@ -1,6 +1,8 @@ package com.lumenpearson.lessons.core.data.datastore import androidx.datastore.preferences.core.mutablePreferencesOf +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.Session import org.junit.Assert.assertEquals import org.junit.Assert.assertNull @@ -194,4 +196,43 @@ class MembershipsTest { assertNull(prefs.activeMembership()) assertNull(prefs[MembershipKeys.ACTIVE_CLASS_ID]) } + + // -- the class's diary binding (gap 3) ----------------------------------- + + @Test + fun `a session stored before bindings reads as unbound`() { + val prefs = mutablePreferencesOf( + MembershipKeys.SESSIONS to """[{"classId":1,"className":"7А","token":"t1"}]""", + ) + + assertNull(prefs.memberships().single().diary) + } + + @Test + fun `a binding round-trips with its membership`() { + val bound = session(1, "7А").copy( + diary = DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 1234, "Школа № 5"), + ) + val prefs = mutablePreferencesOf() + + prefs.writeMemberships(listOf(bound, session(2, "9Б"))) + + assertEquals(listOf(bound, session(2, "9Б")), prefs.memberships()) + } + + /** A binding this build cannot read costs the binding — never the class and its token. */ + @Test + fun `an unreadable binding costs the binding and not the membership`() { + val prefs = mutablePreferencesOf( + MembershipKeys.SESSIONS to + """[{"classId":1,"className":"7А","token":"t1","diary":{"provider":"eljur","region":"x"}},""" + + """{"classId":2,"className":"9Б","token":"t2","diary":"garbage"},""" + + """{"classId":3,"className":"5В","token":"t3","diary":{"provider":"netschool","schoolId":"not a number"}}]""", + ) + + val read = prefs.memberships() + + assertEquals(listOf(1L, 2L, 3L), read.map { it.classId }) + assertEquals(listOf(null, null, null), read.map { it.diary }) + } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheTest.kt new file mode 100644 index 00000000..1707d44f --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryCacheTest.kt @@ -0,0 +1,246 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.network.dto.DiaryEditDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryLessonDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto +import java.io.IOException +import java.time.LocalDate +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The offline diary, as the repository fills it and the screens read it. + * + * Driven through the real `DiaryRepositoryImpl` and the real `DiaryCacheImpl` + * over an in-memory DAO, so what is under test is the write-through as it + * ships: which answers are kept, under which week, and what «loaded» means. + */ +class DiaryCacheTest { + + private val monday = LocalDate.parse("2026-09-21") + private val sunday = LocalDate.parse("2026-09-27") + + @Test + fun `a week fetched empty is loaded, a week never fetched is not`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(lessons = emptyList())) + + rig.repository.schedule(1, monday, sunday) + + val fetched = rig.cache.week(1, monday).first() + assertNotNull(fetched.lessonsLoadedAt) + assertTrue(fetched.lessons.isEmpty()) + // The homework half of the same week was never asked: «не загружено», + // not «нет заданий». + assertNull(fetched.homeworkLoadedAt) + + val never = rig.cache.week(1, monday.plusWeeks(1)).first() + assertNull(never.lessonsLoadedAt) + } + + @Test + fun `two weeks in one read stamp both weeks and file each lesson under its own`() = runTest { + val rig = DiaryRig( + api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22"), lesson("2026-09-29", "Physics"))), + ) + + rig.repository.schedule(1, monday, monday.plusDays(13)) + + val first = rig.cache.week(1, monday).first() + val second = rig.cache.week(1, monday.plusWeeks(1)).first() + assertEquals(listOf("Algebra"), first.lessons.map { it.subject }) + assertEquals(listOf("Physics"), second.lessons.map { it.subject }) + assertNotNull(first.lessonsLoadedAt) + assertNotNull(second.lessonsLoadedAt) + } + + /** + * A range that is not whole weeks would stamp a week fetched when only part + * of it was, and its missing days would be drawn as empty. + */ + @Test + fun `a range that is not whole weeks passes through uncached`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22")))) + + val result = rig.repository.schedule(1, monday.plusDays(1), sunday) + + assertEquals(1, result.getOrThrow().size) + assertEquals(0, rig.dao.rowCount) + } + + @Test + fun `a new read of a week replaces the old one`() = runTest { + val api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22"), lesson("2026-09-23"))) + val rig = DiaryRig(api = api) + rig.repository.schedule(1, monday, sunday) + + api.lessons = listOf(lesson("2026-09-24", "History")) + rig.repository.schedule(1, monday, sunday) + + assertEquals(listOf("History"), rig.cache.week(1, monday).first().lessons.map { it.subject }) + } + + @Test + fun `corrections and times survive the round trip`() = runTest { + val corrected = DiaryLessonDto( + date = "2026-09-22", + number = 2, + subject = "Algebra", + startsAt = "09:00", + endsAt = "09:45", + room = "301", + target = "2026-09-22|2|Algebra", + edits = listOf(DiaryEditDto(field = "room", value = "301", original = "204", changedUpstream = true)), + ambiguous = true, + ) + val rig = DiaryRig(api = ScriptedDiaryApi(lessons = listOf(corrected))) + + val live = rig.repository.schedule(1, monday, sunday).getOrThrow() + + assertEquals(live, rig.cache.week(1, monday).first().lessons) + } + + @Test + fun `the marks window read is the one kept, and covers says so`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(marks = listOf(mark("2026-09-10"), mark("2026-09-11", "4")))) + val window = DiaryDateRange(LocalDate.parse("2026-09-01"), LocalDate.parse("2026-09-25")) + rig.repository.students() + + rig.repository.grades(1, window.from, window.to) + + val kept = rig.cache.marks(1).first() + assertEquals(listOf("5", "4"), kept.marks.map { it.value }) + assertTrue(kept.covers(window)) + assertFalse(kept.covers(window.copy(from = window.from.plusDays(1)))) + } + + /** + * A pupil still listed keeps the stamps of what was read for them; a + * pupil no longer listed takes every row of theirs along. + */ + @Test + fun `a new pupil list keeps what was read for pupils still on it and drops the rest`() = runTest { + val api = ScriptedDiaryApi( + students = listOf(student(1), student(2)), + lessons = listOf(lesson("2026-09-22")), + marks = listOf(mark("2026-09-10")), + ) + val rig = DiaryRig(api = api) + rig.repository.students() + rig.repository.grades(1, LocalDate.parse("2026-09-01"), LocalDate.parse("2026-09-25")) + rig.repository.schedule(2, monday, sunday) + + api.students = listOf(student(1)) + rig.repository.students() + + assertNotNull(rig.cache.marks(1).first().loadedAt) + assertEquals(listOf(1L), rig.cache.students.first().students.map { it.id }) + assertTrue(rig.dao.lessons.none { it.studentId == 2L }) + assertTrue(rig.dao.weeks.none { it.studentId == 2L }) + } + + @Test + fun `the terms are kept per pupil with when they were read`() = runTest { + val rig = DiaryRig( + api = ScriptedDiaryApi( + periods = listOf( + DiaryPeriodDto(id = 10, name = "I", startsOn = "2026-09-01", endsOn = "2026-10-26"), + DiaryPeriodDto(id = 11, name = "II", startsOn = "2026-11-05", endsOn = "2026-12-28", isCurrent = true), + ), + ), + ) + rig.repository.students() + + rig.repository.periods(1) + + val kept = rig.cache.periods(1).first() + assertEquals(listOf(10L, 11L), kept.periods.map { it.id }) + assertEquals(11L, kept.periods.single { it.isCurrent }.id) + assertNotNull(kept.loadedAt) + } + + @Test + fun `sign-out empties every table even offline`() = runTest { + val api = ScriptedDiaryApi( + lessons = listOf(lesson("2026-09-22")), + homework = listOf(homeworkDue("2026-09-23")), + marks = listOf(mark("2026-09-10")), + periods = listOf(DiaryPeriodDto(id = 10, name = "I")), + ) + val rig = DiaryRig(api = api) + rig.repository.students() + rig.repository.periods(1) + rig.repository.schedule(1, monday, sunday) + rig.repository.homework(1, monday, sunday) + rig.repository.grades(1, LocalDate.parse("2026-09-01"), LocalDate.parse("2026-09-25")) + assertTrue(rig.dao.rowCount > 0) + api.failures["logout"] = IOException("no network") + + val result = rig.repository.signOut() + + assertTrue(result.isSuccess) + assertEquals(0, rig.dao.rowCount) + } + + /** + * The answer to a read that was out when somebody signed out belongs to an + * account the phone has let go of. Written, it would leave a child's week + * on the phone after the screen had said it was gone. + */ + @Test + fun `a read that lands after a sign-out is not kept`() = runTest { + val api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22"))) + val rig = DiaryRig(api = api) + api.duringRequest = { route -> if (route.startsWith("schedule")) rig.cache.clear() } + + val result = rig.repository.schedule(1, monday, sunday) + + assertTrue(result.isSuccess) + assertEquals(0, rig.dao.rowCount) + } + + @Test + fun `a cache that cannot be written costs the copy and not the answer`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22")))) + val broken = object : DiaryCacheWriter by rig.cache { + override suspend fun putLessons( + generation: Long, + studentId: Long, + from: LocalDate, + to: LocalDate, + rows: List, + ) = throw IOException("no space left on device") + } + val repository = com.lumenpearson.lessons.core.data.repository.DiaryRepositoryImpl( + api = rig.api, + store = rig.store, + diarySignIn = UnusedSignIn, + cache = broken, + ioDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher(testScheduler), + ) + + assertEquals(1, repository.schedule(1, monday, sunday).getOrThrow().size) + } + + @Test + fun `a failed read writes nothing`() = runTest { + val api = ScriptedDiaryApi(lessons = listOf(lesson("2026-09-22"))) + api.failures["schedule"] = statusError(503) + val rig = DiaryRig(api = api) + + assertTrue(rig.repository.schedule(1, monday, sunday).isFailure) + assertEquals(0, rig.dao.rowCount) + } + + @Test + fun `an unreadable corrections column costs the marks, not the lesson`() { + assertEquals(emptyList(), DiaryEditsCodec.decode("not json")) + assertEquals(emptyList(), DiaryEditsCodec.decode("")) + assertEquals("", DiaryEditsCodec.encode(emptyList())) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDaoPolicyTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDaoPolicyTest.kt new file mode 100644 index 00000000..71935c3e --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDaoPolicyTest.kt @@ -0,0 +1,100 @@ +package com.lumenpearson.lessons.core.data.diary + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The two rules `DiaryDao` promises, read out of the shipped SQL. + * + * Room does not run on the JVM and the in-memory DAO the other tests drive + * implements only what each statement says, so neither can see a statement + * that says the wrong thing. This reads `DiaryDao.kt` the way + * `DaoDeletePolicyTest` reads `TimetableDao.kt`. What it cannot see: whether + * the SQL is valid (the Room compiler checks that at build time) and a table + * added to the database but not to [TABLES]. + */ +class DiaryDaoPolicyTest { + + private companion object { + val TABLES = listOf("diary_student", "diary_week", "diary_period", "diary_lesson", "diary_homework", "diary_mark") + } + + private val source: File = + File("src/main/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryDao.kt") + + /** Every `@Query`, its adjacent literals joined and its whitespace collapsed. */ + private val statements: List by lazy { + Regex("""@Query\(([\s\S]*?)abstract""") + .findAll(source.readText()) + .map { match -> + Regex("\"([^\"]*)\"") + .findAll(match.groupValues[1]) + .joinToString("") { it.groupValues[1] } + .replace(Regex("\\s+"), " ") + .trim() + } + .toList() + } + + @Test + fun `the DAO source is where this test thinks it is`() { + assertTrue("${source.absolutePath} is not there", source.isFile) + assertTrue("only ${statements.size} statements were read", statements.size > 20) + assertTrue(statements.any { it.startsWith("DELETE FROM diary_lesson WHERE") }) + } + + @Test + fun `every delete is scoped by pupil or empties its whole table, and none relies on foreign keys`() { + val deletes = statements.filter { it.startsWith("DELETE") } + val unscoped = deletes.filter { delete -> + val where = delete.substringAfter(" WHERE ", missingDelimiterValue = "") + val whole = TABLES.any { delete == "DELETE FROM $it" } + !whole && !where.startsWith("student_id ") && !where.startsWith("id ") + } + assertEquals("deletes that name no pupil: $unscoped", emptyList(), unscoped) + val entities = File(source.parentFile, "DiaryEntities.kt").readText() + assertTrue("a foreign key would make a delete depend on a PRAGMA", "ForeignKey" !in entities) + } + + /** `clear` is sign-out: a table it skipped would keep a child's marks after the screen said they were gone. */ + @Test + fun `clear empties every table`() { + val text = source.readText() + val clear = text.substringAfter("open suspend fun clear()").substringBefore("\n }") + for (table in TABLES) { + val method = statements.indexOf("DELETE FROM $table") + assertTrue("no whole-table delete for $table", method >= 0) + } + val calls = Regex("""deleteAll\w+\(\)""").findAll(clear).map { it.value }.toSet() + assertEquals(TABLES.size, calls.size) + } + + /** A pupil dropped from the list takes every row of theirs along, table by table. */ + @Test + fun `a vanished pupil is deleted from every table`() { + for (table in TABLES) { + val column = if (table == "diary_student") "id" else "student_id" + assertTrue( + "no delete of vanished pupils in $table", + "DELETE FROM $table WHERE $column NOT IN (:keep)" in statements, + ) + } + } + + /** + * API 26–29 ship SQLite older than 3.24. The SQL is checked, not the + * comments — the file's own note names the syntax it avoids — plus Room's + * `@Upsert`, which generates it. + */ + @Test + fun `no upsert syntax newer than API 26's SQLite`() { + for (statement in statements) { + for (newer in listOf("ON CONFLICT", "DO UPDATE", "UPSERT", "RETURNING")) { + assertTrue("$newer in: $statement", newer !in statement.uppercase()) + } + } + assertTrue("@Upsert generates ON CONFLICT … DO UPDATE", "@Upsert" !in source.readText()) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlanTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlanTest.kt new file mode 100644 index 00000000..460e6863 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportPlanTest.kt @@ -0,0 +1,106 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryRepository +import java.time.DayOfWeek +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.temporal.ChronoUnit +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Which days the import asks for, and the date rules the screen shares with it. */ +class DiaryImportPlanTest { + + @Test + fun `weeks are two whole Monday-aligned weeks`() { + var day = LocalDate.parse("2026-09-01") + while (day.isBefore(LocalDate.parse("2027-09-01"))) { + val plan = DiaryImportPlan.of(day) + assertEquals(DayOfWeek.MONDAY, plan.weeksFrom.dayOfWeek) + assertEquals(DayOfWeek.SUNDAY, plan.weeksTo.dayOfWeek) + assertEquals(13, ChronoUnit.DAYS.between(plan.weeksFrom, plan.weeksTo)) + assertTrue(day in plan.weeksFrom..plan.weeksFrom.plusDays(6)) + assertEquals(2, plan.mondays.size) + assertTrue(DiaryWindows.isWholeWeeks(plan.weeksFrom, plan.weeksTo)) + day = day.plusDays(1) + } + } + + @Test + fun `no span exceeds 62 days, with or without a term`() { + val terms = listOf( + null, + period("2026-09-01", "2026-10-26"), + period("2026-09-01", "2026-12-28"), + period("2027-01-09", "2027-05-31"), + period(null, null), + ) + var day = LocalDate.parse("2026-09-01") + while (day.isBefore(LocalDate.parse("2027-09-01"))) { + val plan = DiaryImportPlan.of(day) + assertTrue(ChronoUnit.DAYS.between(plan.weeksFrom, plan.weeksTo) <= DiaryRepository.MAX_RANGE_DAYS) + for (term in terms) { + val window = plan.marksWindow(term) + val span = ChronoUnit.DAYS.between(window.from, window.to) + assertTrue("$day $term: $span", span in 0..DiaryRepository.MAX_RANGE_DAYS) + assertFalse("$day $term: ends after today", window.to.isAfter(day)) + } + day = day.plusDays(1) + } + } + + @Test + fun `the marks window follows the term the way the marks tab cuts it`() { + val today = LocalDate.parse("2026-12-10") + // A term that fits: the whole of it so far. + assertEquals( + DiaryDateRange(LocalDate.parse("2026-11-05"), today), + DiaryImportPlan.of(today).marksWindow(period("2026-11-05", "2026-12-28")), + ) + // A term longer than the limit: its latest 62 days. + assertEquals( + DiaryDateRange(today.minusDays(62), today), + DiaryImportPlan.of(today).marksWindow(period("2026-09-01", "2026-12-28")), + ) + // A term already over ends at its own end. + assertEquals( + DiaryDateRange(LocalDate.parse("2026-09-01"), LocalDate.parse("2026-10-26")), + DiaryImportPlan.of(today).marksWindow(period("2026-09-01", "2026-10-26")), + ) + } + + @Test + fun `the weights sum to one`() { + assertEquals(1f, DiaryImportPhase.entries.sumOf { it.weight.toDouble() }.toFloat(), 1e-6f) + } + + @Test + fun `today is the diary's date, not the phone's`() { + val clock = java.time.Clock.fixed(Instant.parse("2026-09-27T21:30:00Z"), ZoneId.of("UTC")) + assertEquals(LocalDate.parse("2026-09-28"), DiaryWindows.today(ZoneId.of("Asia/Tomsk"), clock)) + assertEquals(LocalDate.parse("2026-09-28"), DiaryWindows.today(ZoneId.of("Europe/Moscow"), clock)) + assertEquals(LocalDate.parse("2026-09-27"), DiaryWindows.today(ZoneId.of("Europe/Kaliningrad"), clock)) + } + + @Test + fun `fresh means younger than half an hour, and never a read from the future`() { + val now = Instant.parse("2026-09-25T10:00:00Z") + assertTrue(diaryIsFresh(now.minusSeconds(29 * 60), now)) + assertFalse(diaryIsFresh(now.minusSeconds(30 * 60), now)) + assertFalse(diaryIsFresh(null, now)) + // A clock set back must not freeze the refresh for however far it went. + assertFalse(diaryIsFresh(now.plusSeconds(60), now)) + } + + private fun period(from: String?, to: String?) = DiaryPeriod( + id = 1, + name = "term", + startsOn = from?.let(LocalDate::parse), + endsOn = to?.let(LocalDate::parse), + isCurrent = true, + ) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt new file mode 100644 index 00000000..d9acd987 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt @@ -0,0 +1,297 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.HOMEWORK +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.MARKS +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.PERIODS +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.SCHEDULE +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase.STUDENTS +import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.io.IOException +import java.time.Duration +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** + * The import, over the real repository and the real cache. + * + * The clock is Friday 25 September 2026, 13:00 in Moscow, so the plan is the + * week of Monday 21 September and the next: 2026-09-21 .. 2026-10-04. + */ +class DiaryImportTest { + + private val weeks = "2026-09-21..2026-10-04" + + private val neverAsked: suspend (List) -> DiaryStudent = { + fail("the chooser was not supposed to be shown") + error("unreachable") + } + + @Test + fun `phases arrive in order and the fraction never goes backwards`() = runTest { + val rig = DiaryRig() + + val progress = rig.import.run(choose = neverAsked).toList() + + val phases = progress.filterIsInstance().map { it.phase } + assertEquals(listOf(STUDENTS, PERIODS, SCHEDULE, HOMEWORK, MARKS), phases) + val fractions = progress.flatMap { state -> + when (state) { + is DiaryImportProgress.Running -> listOf(state.completed, state.target) + else -> listOf(state.completed) + } + } + assertEquals(fractions.sorted(), fractions) + assertEquals(1f, progress.last().completed) + assertTrue(progress.last() is DiaryImportProgress.Done) + } + + @Test + fun `requests are sequential and within the plan`() = runTest { + val rig = DiaryRig() + + rig.import.run(choose = neverAsked).toList() + + assertEquals( + listOf( + "students", + "periods 1", + "schedule 1 $weeks", + "homework 1 $weeks", + // No current term: the last 62 days, which is what the marks + // tab asks for without one. + "grades 1 2026-07-25..2026-09-25", + ), + rig.api.calls, + ) + } + + @Test + fun `the marks window is the current term's, as the marks tab asks for it`() = runTest { + val api = ScriptedDiaryApi( + periods = listOf(DiaryPeriodDto(id = 7, name = "I", startsOn = "2026-09-01", endsOn = "2026-10-26", isCurrent = true)), + ) + val rig = DiaryRig(api = api) + + rig.import.run(choose = neverAsked).toList() + + assertEquals("grades 1 2026-09-01..2026-09-25", rig.api.calls.last()) + assertTrue(rig.cache.marks(1).first().covers(DiaryWindows.gradeWindow(rig.clock.today(), rig.cache.periods(1).first().periods.single()))) + } + + @Test + fun `one pupil is chosen silently, two ask, a stored choice is kept`() = runTest { + val one = DiaryRig() + val done = one.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Done + assertEquals(1L, done.student.id) + assertEquals(1L, one.store.student) + + val two = DiaryRig(api = ScriptedDiaryApi(students = listOf(student(1), student(2)))) + var offered: List = emptyList() + val progress = two.import.run(choose = { students -> + offered = students.map { it.id } + students.last() + }).toList() + assertEquals(listOf(1L, 2L), offered) + assertTrue(progress.any { it is DiaryImportProgress.ChoosingStudent }) + assertEquals(2L, two.store.student) + assertEquals(2L, two.cache.selectedStudentId.first()) + assertTrue(two.api.calls.contains("schedule 2 $weeks")) + + val remembered = DiaryRig( + api = ScriptedDiaryApi(students = listOf(student(1), student(2))), + store = MemoryDiaryStore(student = 2), + ) + val kept = remembered.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Done + assertEquals(2L, kept.student.id) + } + + /** The registration already answered with the pupils; asking again is an upstream call for nothing. */ + @Test + fun `pupils the registration just stored are not asked for again`() = runTest { + val rig = DiaryRig() + rig.cache.putStudents(rig.cache.generation(), listOf(pupil(1))) + + rig.import.run(choose = neverAsked).toList() + + assertFalse(rig.api.calls.contains("students")) + } + + @Test + fun `pupils stored long ago are asked for again`() = runTest { + val rig = DiaryRig() + rig.cache.putStudents(rig.cache.generation(), listOf(pupil(1))) + rig.clock.now = rig.clock.now.plus(DiaryFreshFor).plusSeconds(1) + + rig.import.run(choose = neverAsked).toList() + + assertEquals("students", rig.api.calls.first()) + } + + @Test + fun `failed marks or homework finish Done with skipped, failed schedule fails`() = runTest { + val soft = DiaryRig() + soft.api.failures["homework"] = statusError(503) + soft.api.failures["grades"] = IOException("no network") + soft.api.failures["periods"] = statusError(502) + val done = soft.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Done + assertEquals(setOf(PERIODS, HOMEWORK, MARKS), done.skipped) + // The homework half of the weeks stays «не загружено», not «нет заданий». + assertEquals(null, soft.cache.week(1, soft.clock.monday()).first().homeworkLoadedAt) + + val hard = DiaryRig() + hard.api.failures["schedule"] = statusError(503) + val failed = hard.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Failed + assertEquals(SCHEDULE, failed.phase) + assertTrue(failed.resumable) + assertFalse(hard.api.calls.any { it.startsWith("homework") || it.startsWith("grades") }) + } + + @Test + fun `resume starts at the failed phase and does not ask again for what landed`() = runTest { + val rig = DiaryRig() + rig.api.failures["schedule"] = statusError(503) + val failed = rig.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Failed + rig.api.failures.clear() + rig.api.calls.clear() + + val progress = rig.import.run(resumeFrom = failed.phase, choose = neverAsked).toList() + + assertTrue(progress.last() is DiaryImportProgress.Done) + assertEquals(listOf("schedule 1 $weeks", "homework 1 $weeks"), rig.api.calls.take(2)) + assertFalse(rig.api.calls.contains("students")) + assertFalse(rig.api.calls.any { it.startsWith("periods") }) + } + + @Test + fun `re-auth mid-import surfaces as ReauthRequired and stops there`() = runTest { + val rig = DiaryRig() + rig.api.failures["homework"] = statusError(401, DiaryFailure.REAUTH_HEADER to "required") + + val failed = rig.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Failed + + assertEquals(HOMEWORK, failed.phase) + assertEquals(DiarySignInProblem.ReauthRequired, failed.problem) + assertTrue(failed.resumable) + assertFalse(rig.api.calls.any { it.startsWith("grades") }) + } + + @Test + fun `a dead bearer stops the import and cannot be resumed`() = runTest { + val rig = DiaryRig() + rig.api.failures["periods"] = statusError(401) + + val failed = rig.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Failed + + assertEquals(DiarySignInProblem.SignInRequired, failed.problem) + assertFalse(failed.resumable) + } + + @Test + fun `no session is a sign-in, and nothing is asked`() = runTest { + val rig = DiaryRig(store = MemoryDiaryStore(session = null)) + + val failed = rig.import.run(choose = neverAsked).toList().single() as DiaryImportProgress.Failed + + assertEquals(DiarySignInProblem.SignInRequired, failed.problem) + assertTrue(rig.api.calls.isEmpty()) + } + + @Test + fun `an account with no pupil is NoStudent`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(students = emptyList())) + + val failed = rig.import.run(choose = neverAsked).toList().last() as DiaryImportProgress.Failed + + assertEquals(DiarySignInProblem.NoStudent, failed.problem) + assertFalse(failed.resumable) + } + + @Test + fun `the weeks are cut in the diary's zone, not the phone's`() = runTest { + // 22:30 UTC on Sunday is already Monday in Tomsk (UTC+7). + val tomsk = DiarySession( + login = "parent", + token = "ours", + target = DiaryTarget.netschool("tomsk", 5, null, "parent", "Asia/Tomsk"), + ) + val rig = DiaryRig(store = MemoryDiaryStore(session = tomsk)) + rig.clock.now = java.time.Instant.parse("2026-09-27T22:30:00Z") + + rig.import.run(choose = neverAsked).toList() + + assertTrue(rig.api.calls.contains("schedule 1 2026-09-28..2026-10-11")) + } + + @Test + fun `refreshIfStale reads this week and the next when they are old, and only then`() = runTest { + val rig = DiaryRig() + rig.import.run(choose = neverAsked).toList() + rig.api.calls.clear() + + assertEquals(false, rig.import.refreshIfStale().getOrThrow()) + assertTrue(rig.api.calls.isEmpty()) + + rig.clock.now = rig.clock.now.plus(DiaryFreshFor).plus(Duration.ofMinutes(1)) + assertEquals(true, rig.import.refreshIfStale().getOrThrow()) + assertEquals(listOf("schedule 1 $weeks", "homework 1 $weeks"), rig.api.calls) + } + + @Test + fun `refreshIfStale without a session asks nothing`() = runTest { + val rig = DiaryRig(store = MemoryDiaryStore(session = null, student = 1)) + + assertEquals(false, rig.import.refreshIfStale().getOrThrow()) + assertTrue(rig.api.calls.isEmpty()) + } + + @Test + fun `refreshIfStale reports a re-auth rather than hiding it`() = runTest { + val rig = DiaryRig(store = MemoryDiaryStore(student = 1)) + rig.api.failures["schedule"] = statusError(401, DiaryFailure.REAUTH_HEADER to "required") + + val result = rig.import.refreshIfStale() + + assertEquals(DiarySignInProblem.ReauthRequired, result.exceptionOrNull()) + } + + @Test + fun `refreshIfStale is a no-op while an import is running`() = runTest { + val rig = DiaryRig(api = ScriptedDiaryApi(students = listOf(student(1), student(2)))) + var during: Result? = null + + rig.import.run(choose = { students -> + during = rig.import.refreshIfStale() + students.first() + }).toList() + + assertEquals(false, during?.getOrThrow()) + assertEquals(1, rig.api.calls.count { it.startsWith("schedule") }) + } + + private fun pupil(id: Long) = DiaryStudent( + id = id, + firstName = "Pupil$id", + lastName = "Ivanova", + middleName = null, + fullName = "Ivanova Pupil$id", + school = null, + className = null, + ) + + private fun com.lumenpearson.lessons.core.data.upstream.MutableClock.today() = + DiaryWindows.today(java.time.ZoneId.of("Europe/Moscow"), this) + + private fun com.lumenpearson.lessons.core.data.upstream.MutableClock.monday() = + DiaryWindows.weekStart(today()) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryTestSupport.kt new file mode 100644 index 00000000..2e2528d8 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryTestSupport.kt @@ -0,0 +1,335 @@ +package com.lumenpearson.lessons.core.data.diary + +import com.lumenpearson.lessons.core.data.network.DiaryApi +import com.lumenpearson.lessons.core.data.network.dto.DiaryAttendanceDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryCapabilitiesDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryHomeworkDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryLessonDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryMarkDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryResetRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionResponseDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryStudentDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySubjectDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryTeacherDto +import com.lumenpearson.lessons.core.data.repository.DiaryRegistration +import com.lumenpearson.lessons.core.data.repository.DiaryRepositoryImpl +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiarySessionStore +import com.lumenpearson.lessons.core.data.repository.DiarySignIn +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.upstream.MutableClock +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.ResponseBody.Companion.toResponseBody +import retrofit2.HttpException +import retrofit2.Response + +/** + * `diary.db`, in memory, for the tests that need one that remembers. + * + * Only the abstract statements are here — the `replace…` transactions and + * `clear` are [DiaryDao]'s own, so the tests exercise the orchestration that + * ships rather than a second copy of it (the `InMemoryTimetableDao` rule). + * Every statement does exactly what its SQL says and nothing more: a fake that + * is more thorough than its query hides the defect it stands in for. + */ +internal class InMemoryDiaryDao : DiaryDao() { + + val students = mutableListOf() + val weeks = mutableListOf() + val periods = mutableListOf() + val lessons = mutableListOf() + val homework = mutableListOf() + val marks = mutableListOf() + private var nextRow = 1L + + private val revision = MutableStateFlow(0) + + private fun touch() { + revision.value += 1 + } + + /** Every row of every table, for «is it empty». */ + val rowCount: Int get() = students.size + weeks.size + periods.size + lessons.size + homework.size + marks.size + + override fun observeChanges(): Flow> = revision.map { emptyList() } + + override suspend fun students(): List = students.sortedBy { it.position } + + override suspend fun student(studentId: Long): DiaryStudentEntity? = students.firstOrNull { it.id == studentId } + + override suspend fun week(studentId: Long, monday: LocalDate): DiaryWeekEntity? = + weeks.firstOrNull { it.studentId == studentId && it.monday == monday } + + override suspend fun lessons(studentId: Long, from: LocalDate, to: LocalDate): List = + lessons.filter { it.studentId == studentId && it.date in from..to } + .sortedWith(compareBy({ it.date }, { it.position })) + + override suspend fun homework(studentId: Long, from: LocalDate, to: LocalDate): List = + homework.filter { it.studentId == studentId && it.dueDate in from..to } + .sortedWith(compareBy({ it.dueDate }, { it.position })) + + override suspend fun marks(studentId: Long): List = + marks.filter { it.studentId == studentId }.sortedBy { it.position } + + override suspend fun periods(studentId: Long): List = + periods.filter { it.studentId == studentId }.sortedBy { it.position } + + override suspend fun insertStudents(rows: List) { + rows.forEach { row -> + students.removeAll { it.id == row.id } + students += row + } + touch() + } + + override suspend fun insertWeeksIfAbsent(rows: List) { + rows.forEach { row -> + if (weeks.none { it.studentId == row.studentId && it.monday == row.monday }) weeks += row + } + touch() + } + + override suspend fun insertLessons(rows: List) { + lessons += rows.map { it.copy(rowId = nextRow++) } + touch() + } + + override suspend fun insertHomework(rows: List) { + homework += rows.map { it.copy(rowId = nextRow++) } + touch() + } + + override suspend fun insertMarks(rows: List) { + marks += rows.map { it.copy(rowId = nextRow++) } + touch() + } + + override suspend fun insertPeriods(rows: List) { + rows.forEach { row -> + check(periods.none { it.studentId == row.studentId && it.id == row.id }) { "primary key clash" } + periods += row + } + touch() + } + + override suspend fun stampLessons(studentId: Long, mondays: List, at: Long) { + weeks.replaceAll { if (it.studentId == studentId && it.monday in mondays) it.copy(lessonsSyncedAt = at) else it } + touch() + } + + override suspend fun stampHomework(studentId: Long, mondays: List, at: Long) { + weeks.replaceAll { if (it.studentId == studentId && it.monday in mondays) it.copy(homeworkSyncedAt = at) else it } + touch() + } + + override suspend fun stampMarks(studentId: Long, from: LocalDate, to: LocalDate, at: Long) { + students.replaceAll { + if (it.id == studentId) it.copy(marksFrom = from, marksTo = to, marksSyncedAt = at) else it + } + touch() + } + + override suspend fun stampPeriods(studentId: Long, at: Long) { + students.replaceAll { if (it.id == studentId) it.copy(periodsSyncedAt = at) else it } + touch() + } + + override suspend fun deleteStudentsOtherThan(keep: List) = drop { students.removeAll { it.id !in keep } } + override suspend fun deleteWeeksOtherThan(keep: List) = drop { weeks.removeAll { it.studentId !in keep } } + override suspend fun deletePeriodsOtherThan(keep: List) = drop { periods.removeAll { it.studentId !in keep } } + override suspend fun deleteLessonsOtherThan(keep: List) = drop { lessons.removeAll { it.studentId !in keep } } + override suspend fun deleteHomeworkOtherThan(keep: List) = drop { homework.removeAll { it.studentId !in keep } } + override suspend fun deleteMarksOtherThan(keep: List) = drop { marks.removeAll { it.studentId !in keep } } + + override suspend fun deleteLessons(studentId: Long, from: LocalDate, to: LocalDate) = + drop { lessons.removeAll { it.studentId == studentId && it.date in from..to } } + + override suspend fun deleteHomework(studentId: Long, from: LocalDate, to: LocalDate) = + drop { homework.removeAll { it.studentId == studentId && it.dueDate in from..to } } + + override suspend fun deleteMarks(studentId: Long) = drop { marks.removeAll { it.studentId == studentId } } + override suspend fun deletePeriods(studentId: Long) = drop { periods.removeAll { it.studentId == studentId } } + + override suspend fun deleteAllStudents() = drop { students.clear() } + override suspend fun deleteAllWeeks() = drop { weeks.clear() } + override suspend fun deleteAllPeriods() = drop { periods.clear() } + override suspend fun deleteAllLessons() = drop { lessons.clear() } + override suspend fun deleteAllHomework() = drop { homework.clear() } + override suspend fun deleteAllMarks() = drop { marks.clear() } + + private fun drop(block: () -> Unit) { + block() + touch() + } +} + +/** + * Our server's diary routes, scripted: fixed answers, an optional failure per + * route, and a log of every request in the order it was made. + */ +internal class ScriptedDiaryApi( + var students: List = listOf(student(1)), + var lessons: List = emptyList(), + var homework: List = emptyList(), + var marks: List = emptyList(), + var periods: List = emptyList(), +) : DiaryApi { + + /** `route → failure`; the route names are the ones in [calls]. */ + val failures = mutableMapOf() + + /** `students`, `periods 1`, `schedule 1 2026-09-21..2026-10-04`, … in order. */ + val calls = mutableListOf() + + /** Runs inside a request, before it answers — for a test that signs out mid-read. */ + var duringRequest: suspend (String) -> Unit = {} + + private suspend fun answer(route: String, value: () -> T): T { + calls += route + duringRequest(route) + failures[route.substringBefore(' ')]?.let { throw it } + return value() + } + + override suspend fun students(): List = answer("students") { students } + + override suspend fun schedule(studentId: Long, from: String, to: String): List = + answer("schedule $studentId $from..$to") { lessons } + + override suspend fun homework(studentId: Long, from: String, to: String): List = + answer("homework $studentId $from..$to") { homework } + + override suspend fun grades(studentId: Long, from: String, to: String): List = + answer("grades $studentId $from..$to") { marks } + + override suspend fun periods(studentId: Long): List = answer("periods $studentId") { periods } + + override suspend fun capabilities(): DiaryCapabilitiesDto = error("not used by the import") + override suspend fun registerSession(body: DiarySessionRequestDto): DiarySessionResponseDto = + error("not used by the import") + + override suspend fun logout() { + calls += "logout" + failures["logout"]?.let { throw it } + } + + override suspend fun subjects(studentId: Long, periodId: Long?): List = error("not used") + + override suspend fun teachers(studentId: Long): List = error("not used") + override suspend fun attendance(studentId: Long): List = error("not used") + override suspend fun overrides(studentId: Long): List = error("not used") + override suspend fun putOverride(studentId: Long, body: DiaryOverrideRequestDto): DiaryOverrideDto = + error("not used") + + override suspend fun resetOverride(studentId: Long, body: DiaryResetRequestDto) = error("not used") + override suspend fun resetOverrides(studentId: Long) = error("not used") +} + +/** The diary half of the preferences, in memory. */ +internal class MemoryDiaryStore( + session: DiarySession? = DiarySession(login = "parent", token = "ours"), + student: Long? = null, +) : DiarySessionStore { + private val sessionFlow = MutableStateFlow(session) + private val targetFlow = MutableStateFlow(session?.target) + private val studentFlow = MutableStateFlow(student) + + var session: DiarySession? + get() = sessionFlow.value + set(value) { + sessionFlow.value = value + if (value != null) targetFlow.value = value.target + } + + val student: Long? get() = studentFlow.value + + override val diarySession: Flow get() = sessionFlow + override suspend fun currentDiarySession(): DiarySession? = sessionFlow.value + override suspend fun writeDiarySession(value: DiarySession) { + session = value + } + + override suspend fun clearDiaryToken() { + sessionFlow.value = null + } + + override suspend fun forgetDiary() { + sessionFlow.value = null + targetFlow.value = null + studentFlow.value = null + } + + override val diaryTarget: Flow get() = targetFlow + override suspend fun currentDiaryTarget(): DiaryTarget? = targetFlow.value + override val selectedStudentId: Flow get() = studentFlow + override suspend fun selectStudent(id: Long?) { + studentFlow.value = id + } +} + +/** A sign-in nothing here calls. */ +internal object UnusedSignIn : DiarySignIn { + private fun unused(): Nothing = throw DiarySignInProblem.Unexpected("not used here") + override suspend fun preflight(target: DiaryTarget): Result = unused() + override suspend fun openUpstream(target: DiaryTarget, password: String): Result = unused() + override suspend fun register(upstream: UpstreamSession): Result = unused() + override suspend fun discard(upstream: UpstreamSession) = unused() + override suspend fun signIn(target: DiaryTarget, password: String): Result = unused() +} + +/** The real repository and the real cache over the fakes, as the container wires them. */ +internal class DiaryRig( + val api: ScriptedDiaryApi = ScriptedDiaryApi(), + val store: MemoryDiaryStore = MemoryDiaryStore(), + val clock: MutableClock = MutableClock(), +) { + val dao = InMemoryDiaryDao() + val cache = DiaryCacheImpl(dao = { dao }, selection = store, clock = clock) + val repository = DiaryRepositoryImpl( + api = api, + store = store, + diarySignIn = UnusedSignIn, + forgetLocal = cache::clear, + cache = cache, + ioDispatcher = UnconfinedTestDispatcher(), + ) + val import = DiaryImportImpl(repository = repository, store = store, cache = cache, clock = clock) +} + +internal fun student(id: Long, first: String = "Pupil$id") = + DiaryStudentDto(id = id, firstName = first, lastName = "Ivanova", fullName = "Ivanova $first") + +internal fun lesson(date: String, subject: String = "Algebra") = DiaryLessonDto(date = date, number = 1, subject = subject) + +internal fun homeworkDue(date: String, text: String = "p. 12") = + DiaryHomeworkDto(dueDate = date, subject = "Algebra", text = text) + +internal fun mark(date: String, value: String = "5") = DiaryMarkDto(subject = "Algebra", date = date, value = value, kind = "grade") + +/** A status our server answers, with its headers, the way Retrofit throws it. */ +internal fun statusError(code: Int, vararg headers: Pair): HttpException { + val request = Request.Builder().url("https://school.example/api/v1/diary/students").build() + val raw = okhttp3.Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(code) + .message("error") + .apply { headers.forEach { (name, value) -> header(name, value) } } + .build() + return HttpException( + Response.error("""{"detail":"no"}""".toResponseBody("application/json".toMediaType()), raw), + ) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptorTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptorTest.kt new file mode 100644 index 00000000..ea1703e0 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/AuthInterceptorTest.kt @@ -0,0 +1,63 @@ +package com.lumenpearson.lessons.core.data.network + +import com.lumenpearson.lessons.core.data.network.BearerHarness.Companion.CLASS_TOKEN +import mockwebserver3.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * The class's bearer goes on the class's calls, and on nothing anonymous: not + * on `/join` before there is a class, not on the diary, and not on the school + * directory — which a phone asks on its first screen, and which has no business + * learning which class is searching for which school. + */ +class AuthInterceptorTest { + + private lateinit var server: MockWebServer + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `a class call carries the class bearer`() { + val harness = BearerHarness(server) + + assertEquals("Bearer $CLASS_TOKEN", harness.authorizationOn("/api/v1/bundle?start=2026-09-01")) + assertEquals("Bearer $CLASS_TOKEN", harness.authorizationOn("/api/v1/manage/subjects")) + } + + @Test + fun `the directory search carries no class bearer`() { + val harness = BearerHarness(server) + + assertNull(harness.authorizationOn("/api/v1/directory/school-regions?q=%D0%BB%D0%B8%D1%86%D0%B5%D0%B9")) + } + + @Test + fun `join, health and warmup carry no bearer`() { + val harness = BearerHarness(server) + + assertNull(harness.authorizationOn("/api/v1/join", method = "POST")) + assertNull(harness.authorizationOn("/api/v1/health")) + assertNull(harness.authorizationOn("/api/v1/warmup")) + } + + /** With no class there is no class token to send, and nothing is sent in its place. */ + @Test + fun `a phone in no class signs nothing`() { + val harness = BearerHarness(server, classToken = null, diaryToken = null) + + assertNull(harness.authorizationOn("/api/v1/bundle")) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt new file mode 100644 index 00000000..82704ea2 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/BearerTestSupport.kt @@ -0,0 +1,50 @@ +package com.lumenpearson.lessons.core.data.network + +import mockwebserver3.Dispatcher +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody + +/** + * The app's own client — `NetworkModule.okHttpClient`, all three interceptors + * in their real order — pointed at [server] through the base-URL setting, with + * both bearers stored. What each request arrived carrying is the question. + * [basePath] is a server behind a reverse proxy at a path of its own. + */ +internal class BearerHarness( + private val server: MockWebServer, + classToken: String? = CLASS_TOKEN, + diaryToken: String? = DIARY_TOKEN, + basePath: String = "/", +) { + private val client = NetworkModule.okHttpClient( + tokenProvider = { classToken }, + baseUrlProvider = { server.url(basePath).toString() }, + diaryTokenProvider = { diaryToken }, + ) + + init { + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json").body("{}").build() + } + } + + /** The `Authorization` header [path] arrived with, or `null`. */ + fun authorizationOn(path: String, method: String = "GET"): String? { + val body = if (method == "GET") null else "{}".toRequestBody("application/json".toMediaType()) + // The placeholder host is what Retrofit builds against; the base-URL + // interceptor rewrites it, exactly as for every real call. + val request = Request.Builder().url("http://base-url.invalid$path").method(method, body).build() + client.newCall(request).execute().close() + return server.takeRequest().headers["Authorization"] + } + + companion object { + const val CLASS_TOKEN = "class-token" + const val DIARY_TOKEN = "diary-token" + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptorTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptorTest.kt new file mode 100644 index 00000000..e1c83b52 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/DiaryAuthInterceptorTest.kt @@ -0,0 +1,84 @@ +package com.lumenpearson.lessons.core.data.network + +import com.lumenpearson.lessons.core.data.network.BearerHarness.Companion.CLASS_TOKEN +import com.lumenpearson.lessons.core.data.network.BearerHarness.Companion.DIARY_TOKEN +import mockwebserver3.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * The diary's bearer goes on diary reads and nowhere else — and not on the + * three diary calls that are anonymous on the server, because a stale bearer + * riding the request that is meant to replace it is a dead session, or another + * account's, sent along for nothing. + * + * Driven through the app's real client, all three interceptors in order, so a + * change to any of them — or to their order — is seen here. + */ +class DiaryAuthInterceptorTest { + + private lateinit var server: MockWebServer + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `registration and capabilities carry no bearer even when one is stored`() { + val harness = BearerHarness(server) + + assertNull(harness.authorizationOn("/api/v1/diary/session", method = "POST")) + assertNull(harness.authorizationOn("/api/v1/diary/capabilities")) + // Never called by this build, and anonymous on the server all the same. + assertNull(harness.authorizationOn("/api/v1/diary/login", method = "POST")) + } + + @Test + fun `a diary read carries the diary bearer and never the class token`() { + val harness = BearerHarness(server) + + for (path in listOf( + "/api/v1/diary/students", + "/api/v1/diary/students/7/schedule?from=2026-09-21&to=2026-09-27", + "/api/v1/diary/students/7/overrides", + )) { + assertEquals(path, "Bearer $DIARY_TOKEN", harness.authorizationOn(path)) + } + assertEquals("Bearer $DIARY_TOKEN", harness.authorizationOn("/api/v1/diary/logout", method = "POST")) + } + + /** A phone in a class but signed in to no diary sends its diary calls bare, not with the class's token. */ + @Test + fun `no diary path ever carries the class token`() { + val harness = BearerHarness(server, diaryToken = null) + + for (path in listOf( + "/api/v1/diary/students", + "/api/v1/diary/session", + "/api/v1/diary/capabilities", + )) { + assertNull(path, harness.authorizationOn(path)) + } + assertEquals("Bearer $CLASS_TOKEN", harness.authorizationOn("/api/v1/bundle")) + } + + /** The server may sit behind a reverse proxy at a path of its own; the rule is about the diary's part. */ + @Test + fun `a base URL with a path prefix is still told apart`() { + val prefixed = BearerHarness(server, basePath = "/lessons/") + + assertEquals("Bearer $DIARY_TOKEN", prefixed.authorizationOn("/api/v1/diary/students")) + assertNull(prefixed.authorizationOn("/api/v1/diary/session", method = "POST")) + assertEquals("Bearer $CLASS_TOKEN", prefixed.authorizationOn("/api/v1/bundle")) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt index cb7fc9b3..1333141f 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/DiaryJsonTest.kt @@ -27,13 +27,70 @@ class DiaryJsonTest { private val json = NetworkModule.json() @Test - fun `a login answer decodes`() { - val decoded = json.decodeFromString( - """{ "token": "abc.def", "login": "parent@example.com", "issued_at": "later" }""", + fun `a registration answer decodes, zone and pupils included`() { + val decoded = json.decodeFromString( + """ + { + "token": "abc.def", "login": "ivanova", "provider": "netschool", + "region": "samara", "school_id": 1234, "school_name": null, + "zone": "Europe/Samara", "issued_at": "later", + "students": [{ "id": 7, "first_name": "Пётр", "last_name": "Иванов", + "full_name": "Иванов Пётр" }] + } + """.trimIndent(), ) assertEquals("abc.def", decoded.token) - assertEquals("parent@example.com", decoded.login) + assertEquals("ivanova", decoded.login) + assertEquals("samara", decoded.region) + assertEquals(1234L, decoded.schoolId) + assertNull(decoded.schoolName) + assertEquals("Europe/Samara", decoded.zone) + assertEquals(listOf(7L), decoded.students.map { it.id }) + } + + /** A data class would print the bearer into any log that printed the answer. */ + @Test + fun `a registration answer never prints its token`() { + val decoded = DiarySessionResponseDto(token = "secret-bearer", login = "ivanova") + + assertTrue("secret-bearer" !in decoded.toString()) + } + + @Test + fun `capabilities decode, the regions a server keeps sessions for included`() { + val decoded = json.decodeFromString( + """ + { "enabled": true, "registration": true, "later": 1, + "providers": { "petersburg": {}, "netschool": { "regions": ["samara", "tomsk"] } } } + """.trimIndent(), + ) + + assertTrue(decoded.enabled) + assertTrue(decoded.registration) + assertTrue(decoded.providers.petersburg != null) + assertEquals(listOf("samara", "tomsk"), decoded.providers.netschool?.regions) + } + + /** + * The registration body the server takes, field for field. Petersburg's + * half of the union has no `region` or `school_id`, and the server forbids + * unknown keys — so a `null` written out for either would be a `422`. + */ + @Test + fun `a Petersburg registration body carries no region or school at all`() { + val body = DiarySessionRequestDto( + provider = "petersburg", + login = "parent@example.com", + credential = json.encodeToJsonElement(PetersburgCredentialDto.serializer(), PetersburgCredentialDto("a.b.c")) + as kotlinx.serialization.json.JsonObject, + ) + + val written = json.parseToJsonElement(json.encodeToString(DiarySessionRequestDto.serializer(), body)) + as kotlinx.serialization.json.JsonObject + + assertEquals(setOf("provider", "login", "credential"), written.keys) + assertTrue("a.b.c" !in body.toString()) } @Test diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinJsonTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinJsonTest.kt new file mode 100644 index 00000000..45ff1c7f --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/dto/JoinJsonTest.kt @@ -0,0 +1,71 @@ +package com.lumenpearson.lessons.core.data.network.dto + +import com.lumenpearson.lessons.core.data.network.NetworkModule +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The join's answer and the class's diary binding it carries (K25): the only + * place a phone learns which diary its class reads, so a family that joined by + * code signs in without searching for their school. + */ +class JoinJsonTest { + + private val json = NetworkModule.json() + + @Test + fun `a join with a binding carries it`() { + val dto = json.decodeFromString( + JoinResponseDto.serializer(), + """ + {"token": "t", "class_id": 7, "class_name": "7А", "school": null, "timezone": "Europe/Samara", + "diary": {"provider": "netschool", "region": "samara", "school_id": 1234, "school_name": "Школа № 5"}} + """.trimIndent(), + ) + + assertEquals( + DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 1234, "Школа № 5"), + dto.diary?.toDomain(), + ) + } + + @Test + fun `a server from before bindings, and a class with none, read as unbound`() { + val older = json.decodeFromString( + JoinResponseDto.serializer(), + """{"token": "t", "class_id": 7, "class_name": "7А"}""", + ) + val none = json.decodeFromString( + JoinResponseDto.serializer(), + """{"token": "t", "class_id": 7, "class_name": "7А", "timezone": "Europe/Moscow", "diary": null}""", + ) + + assertNull(older.diary) + assertNull(none.diary) + } + + /** A provider a later server adds is no binding, never Petersburg by guess. */ + @Test + fun `an unknown provider is no binding`() { + assertNull(DiaryBindingDto(provider = "eljur", region = "x").toDomain()) + assertNull(DiaryBindingDto().toDomain()) + } + + @Test + fun `a binding becomes a sign-in target only when it has what the diary needs`() { + val petersburg = DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null) + assertEquals(DiaryTarget.petersburg("parent"), petersburg.targetFor("parent")) + + val samara = DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 1234, "Школа № 5") + val target = samara.targetFor("ivanova") + assertEquals("samara", target?.region) + assertEquals(1234L, target?.schoolId) + + assertNull(samara.copy(schoolId = null).targetFor("ivanova")) + assertNull(samara.copy(region = " ").targetFor("ivanova")) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryFailureTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryFailureTest.kt index 51be794a..b8b4ca33 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryFailureTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryFailureTest.kt @@ -95,6 +95,57 @@ class DiaryFailureTest { assertTrue((failure as DiaryFailure.Offline).reason is IOException) } + /** + * The server said «слишком много попыток» and how long to wait; the app + * used to answer «Не получилось: 429» (#153). + */ + @Test + fun `429 is a throttle carrying the wait`() { + assertEquals( + DiaryFailure.Throttled(retryAfterSeconds = 120), + DiaryFailure.of(httpError(429, "Retry-After" to "120")), + ) + } + + @Test + fun `429 without a readable wait is still a throttle`() { + assertEquals( + DiaryFailure.Throttled(retryAfterSeconds = null), + DiaryFailure.of(httpError(429, "Retry-After" to "Wed, 21 Oct 2026 07:28:00 GMT")), + ) + } + + /** «Выключен на сервере» and «не отвечает» are both 503s; the header tells them apart (#153). */ + @Test + fun `503 marked disabled is the diary switched off, not down`() { + assertEquals( + DiaryFailure.Disabled, + DiaryFailure.of(httpError(503, DiaryFailure.UNAVAILABLE_HEADER to "disabled")), + ) + } + + @Test + fun `503 marked address-refused is the diary refusing our server`() { + assertEquals( + DiaryFailure.ServerAddressRefused, + DiaryFailure.of(httpError(503, DiaryFailure.UNAVAILABLE_HEADER to "address-refused")), + ) + } + + @Test + fun `503 marked upstream is the diary being down`() { + assertEquals( + DiaryFailure.Unavailable, + DiaryFailure.of(httpError(503, DiaryFailure.UNAVAILABLE_HEADER to "upstream")), + ) + } + + /** The platform's 30-second ceiling: slow, not wrong, so worth another try (#153). */ + @Test + fun `504 is the diary being slow, not an unexpected status`() { + assertEquals(DiaryFailure.Unavailable, DiaryFailure.of(httpError(504))) + } + /** Classifying twice must not wrap a classification in another one. */ @Test fun `an already classified failure passes through`() { diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryTest.kt index cc9297c9..c7dcc6ce 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepositoryTest.kt @@ -4,16 +4,18 @@ import com.lumenpearson.lessons.core.data.network.DiaryApi import com.lumenpearson.lessons.core.data.network.dto.DiaryAttendanceDto import com.lumenpearson.lessons.core.data.network.dto.DiaryHomeworkDto import com.lumenpearson.lessons.core.data.network.dto.DiaryLessonDto -import com.lumenpearson.lessons.core.data.network.dto.DiaryLoginRequestDto -import com.lumenpearson.lessons.core.data.network.dto.DiaryLoginResponseDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryCapabilitiesDto import com.lumenpearson.lessons.core.data.network.dto.DiaryMarkDto import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideDto import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideRequestDto import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto import com.lumenpearson.lessons.core.data.network.dto.DiaryResetRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionResponseDto import com.lumenpearson.lessons.core.data.network.dto.DiaryStudentDto import com.lumenpearson.lessons.core.data.network.dto.DiarySubjectDto import com.lumenpearson.lessons.core.data.network.dto.DiaryTeacherDto +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession import java.io.IOException import java.time.LocalDate import kotlinx.coroutines.flow.Flow @@ -44,50 +46,60 @@ class DiaryRepositoryTest { private val store = FakeStore() + /** + * The repository's sign-in is [DiarySignIn]'s, whole: the target goes + * through as it was given and the session that comes back is the one the + * sign-in stored. What is stored, and what never is, is `DiarySignInTest`'s. + */ @Test - fun `signing in stores the token the server minted`() = runTest { - val repository = repository(FakeApi()) + fun `signing in hands the target to the sign-in and answers its session`() = runTest { + val signIn = FakeSignIn() + val repository = repository(FakeApi(), signIn) + val target = DiaryTarget.netschool("samara", 1234, null, "ivanova", "Europe/Samara") - val result = repository.signIn(" parent@example.com ", "hunter2") + val result = repository.signIn(target, "hunter2") + assertEquals(listOf(target), signIn.asked) assertEquals("diary-token", result.getOrNull()?.token) - assertEquals("parent@example.com", store.stored?.login) - assertEquals("diary-token", store.stored?.token) } - /** - * The password is the one value in this app that must not be kept, so the - * test that would catch it being kept is the one that looks at the store. - */ @Test - fun `signing in stores nothing but the login and the token`() = runTest { - val repository = repository(FakeApi()) + fun `a refused sign-in comes back as the sign-in's own problem`() = runTest { + val signIn = FakeSignIn(answer = Result.failure(DiarySignInProblem.WrongPassword("Неверный пароль"))) + val repository = repository(FakeApi(), signIn) - repository.signIn("parent@example.com", "hunter2") + val result = repository.signIn(DiaryTarget.petersburg("parent@example.com"), "wrong") - val stored = store.stored - assertTrue(stored != null && "hunter2" !in stored.toString()) + assertEquals(DiarySignInProblem.WrongPassword("Неверный пароль"), result.exceptionOrNull()) + assertNull(store.stored) } @Test - fun `refused credentials are a sign-in failure and store nothing`() = runTest { - val repository = repository(FakeApi(loginFailure = httpError(401))) + fun `a dead session token is dropped so the section can offer a sign-in`() = runTest { + store.stored = DiarySession(login = "parent@example.com", token = "stale") + val repository = repository(FakeApi(callFailure = httpError(401))) - val result = repository.signIn("parent@example.com", "wrong") + val result = repository.students() assertEquals(DiaryFailure.SignInRequired, result.exceptionOrNull()) assertNull(store.stored) } + /** + * The bearer is dead; the account is not. Without the target, a family + * that had only ever used a «Сетевой город» diary would be sent back to + * the start by an expired token instead of being asked for the password. + */ @Test - fun `a dead session token is dropped so the section can offer a sign-in`() = runTest { - store.stored = DiarySession(login = "parent@example.com", token = "stale") + fun `a dead session token keeps which diary it was for`() = runTest { + val target = DiaryTarget.netschool("samara", 1234, "Школа № 5", "ivanova", "Europe/Samara") + store.stored = DiarySession(login = "ivanova", token = "stale", target = target) val repository = repository(FakeApi(callFailure = httpError(401))) - val result = repository.students() + repository.students() - assertEquals(DiaryFailure.SignInRequired, result.exceptionOrNull()) assertNull(store.stored) + assertEquals(target, store.target) } /** @@ -111,12 +123,25 @@ class DiaryRepositoryTest { @Test fun `signing out clears the session even when the server cannot be told`() = runTest { store.stored = DiarySession(login = "parent@example.com", token = "ours") - val repository = repository(FakeApi(logoutFailure = IOException("no network"))) + store.student = 7 + var forgotten = 0 + val repository = DiaryRepositoryImpl( + api = FakeApi(logoutFailure = IOException("no network")), + store = store, + diarySignIn = FakeSignIn(), + forgetLocal = { forgotten++ }, + ioDispatcher = UnconfinedTestDispatcher(), + ) val result = repository.signOut() assertTrue(result.isSuccess) assertNull(store.stored) + // Signing out is the one thing that forgets the account itself, and + // whatever was kept offline for it. + assertNull(store.target) + assertNull(store.student) + assertEquals(1, forgotten) } /** The server's own 62-day rule, applied before the round trip rather than after it. */ @@ -341,11 +366,12 @@ class DiaryRepositoryTest { @Test fun `a 401 whose sign-out cannot be written is still a failure, not a crash`() = runTest { val unwritable = object : DiarySessionStore by store { - override suspend fun clearDiarySession() = throw IOException("no space left on device") + override suspend fun clearDiaryToken() = throw IOException("no space left on device") } val repository = DiaryRepositoryImpl( api = FakeApi(callFailure = httpError(401)), store = unwritable, + diarySignIn = FakeSignIn(), ioDispatcher = UnconfinedTestDispatcher(), ) @@ -354,19 +380,50 @@ class DiaryRepositoryTest { assertEquals(DiaryFailure.SignInRequired, result.exceptionOrNull()) } - private fun repository(api: DiaryApi) = DiaryRepositoryImpl( + private fun repository(api: DiaryApi, signIn: DiarySignIn = FakeSignIn()) = DiaryRepositoryImpl( api = api, store = store, + diarySignIn = signIn, ioDispatcher = UnconfinedTestDispatcher(), ) + /** A sign-in that answers what it is told and records what it was asked for. */ + private class FakeSignIn( + private val answer: Result? = null, + ) : DiarySignIn { + val asked = mutableListOf() + + override suspend fun preflight(target: DiaryTarget): Result = Result.success(Unit) + + override suspend fun openUpstream(target: DiaryTarget, password: String): Result = + Result.failure(DiarySignInProblem.Unexpected("not used here")) + + override suspend fun register(upstream: UpstreamSession): Result = + Result.failure(DiarySignInProblem.Unexpected("not used here")) + + override suspend fun discard(upstream: UpstreamSession) = Unit + + override suspend fun signIn(target: DiaryTarget, password: String): Result { + asked += target + return answer ?: Result.success( + DiaryRegistration( + session = DiarySession(login = target.login, token = "diary-token", target = target), + students = emptyList(), + ), + ) + } + } + /** The store, with nothing in it but what was last written. */ private class FakeStore : DiarySessionStore { var stored: DiarySession? = null set(value) { field = value flow.value = value + if (value != null) target = value.target } + var target: DiaryTarget? = null + var student: Long? = null private val flow = MutableStateFlow(null) override val diarySession: Flow get() = flow @@ -375,8 +432,21 @@ class DiaryRepositoryTest { stored = value } - override suspend fun clearDiarySession() { + override suspend fun clearDiaryToken() { + stored = null + } + + override suspend fun forgetDiary() { stored = null + target = null + student = null + } + + override val diaryTarget: Flow get() = MutableStateFlow(target) + override suspend fun currentDiaryTarget(): DiaryTarget? = target + override val selectedStudentId: Flow get() = MutableStateFlow(student) + override suspend fun selectStudent(id: Long?) { + student = id } } @@ -385,7 +455,6 @@ class DiaryRepositoryTest { * whichever failure the case under test asked for. */ private class FakeApi( - private val loginFailure: Throwable? = null, private val logoutFailure: Throwable? = null, private val callFailure: Throwable? = null, private val stored: List = emptyList(), @@ -410,10 +479,10 @@ class DiaryRepositoryTest { var resetAllCalls: Int = 0 private set - override suspend fun login(body: DiaryLoginRequestDto): DiaryLoginResponseDto { - loginFailure?.let { throw it } - return DiaryLoginResponseDto(token = "diary-token", login = body.login) - } + override suspend fun capabilities(): DiaryCapabilitiesDto = DiaryCapabilitiesDto(enabled = true, registration = true) + + override suspend fun registerSession(body: DiarySessionRequestDto): DiarySessionResponseDto = + throw AssertionError("the repository registers nothing itself; DiarySignIn does") override suspend fun logout() { logoutFailure?.let { throw it } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt new file mode 100644 index 00000000..4b5fcc63 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt @@ -0,0 +1,162 @@ +package com.lumenpearson.lessons.core.data.repository + +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem.Action +import com.lumenpearson.lessons.core.data.upstream.UpstreamFailure +import com.lumenpearson.lessons.core.data.upstream.UpstreamNotAllowed +import java.io.IOException +import java.io.InterruptedIOException +import java.net.SocketTimeoutException +import javax.net.ssl.SSLHandshakeException +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import retrofit2.HttpException +import retrofit2.Response + +/** + * The one failure vocabulary the sign-in, the school search and the import + * screens switch on: every way in maps to exactly one problem and one action. + * + * The rows marked #153 are the phone's half of that issue — a 429 that read + * «Не получилось: 429», a «switched off» 503 that read «не отвечает», and a + * Vercel 504 that read as an unknown status. + */ +class DiarySignInProblemTest { + + private val host = "region.zabedu.ru" + + @Test + fun `every failure maps to one problem and one action`() { + val table: List>> = listOf( + // The diary's own server. + row("wrong password", UpstreamFailure.BadCredentials("Неверный пароль"), + DiarySignInProblem.WrongPassword("Неверный пароль"), Action.RETYPE), + row("Госуслуги only", UpstreamFailure.SignInUnsupported(), + DiarySignInProblem.GosuslugiOnly(null), Action.HANDOFF), + row("diary down", UpstreamFailure.Unavailable(IOException("reset")), + DiarySignInProblem.ProviderUnavailable(host), Action.RETRY), + row("diary slow", UpstreamFailure.Unavailable(SocketTimeoutException("timeout")), + DiarySignInProblem.Timeout(host), Action.RETRY), + row("diary unreachable", UpstreamFailure.Offline(IOException("dns")), + DiarySignInProblem.ProviderOffline(host), Action.RETRY), + row("diary refuses the phone", UpstreamFailure.AddressRefused(), + DiarySignInProblem.ProviderRefusesPhone(host), Action.RETRY), + row("certificate", UpstreamFailure.Untrusted(SSLHandshakeException("PKIX")), + DiarySignInProblem.ProviderUntrusted(host), Action.NONE), + row("captcha", UpstreamFailure.Unexpected("html"), + DiarySignInProblem.ProviderUnreadable(host), Action.RETRY), + // Our server. + row("no address", ServerAddressMissingException(), DiarySignInProblem.ServerMissing, Action.SET_SERVER), + row("no network", IOException("unreachable"), DiarySignInProblem.Offline, Action.RETRY), + row("socket timeout", SocketTimeoutException("timeout"), DiarySignInProblem.Timeout(null), Action.RETRY), + row("call timeout", InterruptedIOException("timeout"), DiarySignInProblem.Timeout(null), Action.RETRY), + row("401", http(401), DiarySignInProblem.SignInRequired, Action.RETYPE), + row("401 re-auth", http(401, DiaryFailure.REAUTH_HEADER to "required"), + DiarySignInProblem.ReauthRequired, Action.RETYPE), + row("409", http(409), DiarySignInProblem.ServerRefusedSession, Action.NONE), + row("429 (#153)", http(429, "Retry-After" to "90"), DiarySignInProblem.TooManyAttempts(90), Action.WAIT), + row("502", http(502), DiarySignInProblem.ProviderUnreadable(null), Action.RETRY), + row("503 disabled (#153)", http(503, DiaryFailure.UNAVAILABLE_HEADER to "disabled"), + DiarySignInProblem.ServerDisabled, Action.NONE), + row("503 address-refused (#153)", http(503, DiaryFailure.UNAVAILABLE_HEADER to "address-refused"), + DiarySignInProblem.ServerAddressRefused, Action.NONE), + row("503 upstream", http(503, DiaryFailure.UNAVAILABLE_HEADER to "upstream"), + DiarySignInProblem.ProviderUnavailable(null), Action.RETRY), + row("bare 503", http(503), DiarySignInProblem.ProviderUnavailable(null), Action.RETRY), + row("504 (#153)", http(504), DiarySignInProblem.Timeout(null), Action.RETRY), + // What reads already classified. + row("read throttled", DiaryFailure.Throttled(12), DiarySignInProblem.TooManyAttempts(12), Action.WAIT), + row("read disabled", DiaryFailure.Disabled, DiarySignInProblem.ServerDisabled, Action.NONE), + row("read address refused", DiaryFailure.ServerAddressRefused, DiarySignInProblem.ServerAddressRefused, Action.NONE), + row("read re-auth", DiaryFailure.ReauthRequired, DiarySignInProblem.ReauthRequired, Action.RETYPE), + row("read signed out", DiaryFailure.SignInRequired, DiarySignInProblem.SignInRequired, Action.RETYPE), + row("read down", DiaryFailure.Unavailable, DiarySignInProblem.ProviderUnavailable(null), Action.RETRY), + row("read unreadable", DiaryFailure.Unreadable, DiarySignInProblem.ProviderUnreadable(null), Action.RETRY), + row("read offline", DiaryFailure.Offline(IOException("x")), DiarySignInProblem.Offline, Action.RETRY), + row("read offline, no address", DiaryFailure.Offline(ServerAddressMissingException()), + DiarySignInProblem.ServerMissing, Action.SET_SERVER), + ) + for ((label, thrown, expected) in table) { + val problem = DiarySignInProblem.of(thrown, host = if (thrown is UpstreamFailure) host else null) + assertEquals(label, expected.first, problem) + assertEquals(label, expected.second, problem.action) + } + } + + /** A 422 is a body the server refused before asking anybody: a bug here, never «retype». */ + @Test + fun `422 is unexpected, not a password to retype`() { + val problem = DiarySignInProblem.of(http(422), registering = true) + assertTrue(problem is DiarySignInProblem.Unexpected) + assertEquals(Action.RETRY, problem.action) + } + + @Test + fun `403 is an account with no pupil on registration only`() { + assertEquals(DiarySignInProblem.NoStudent, DiarySignInProblem.of(http(403), registering = true)) + assertTrue(DiarySignInProblem.of(http(403)) is DiarySignInProblem.Unexpected) + } + + /** The diary let the family in; our server was the one out of reach. The session is still held. */ + @Test + fun `a network failure while registering is not a network failure before anything happened`() { + val problem = DiarySignInProblem.of(IOException("reset"), registering = true) + assertEquals(DiarySignInProblem.RegisterUnreachable, problem) + assertTrue(problem.retryKeepsSession) + } + + @Test + fun `a host outside the allow-list is a bug, never no network`() { + val problem = DiarySignInProblem.of(UpstreamNotAllowed("https://evil.example/".toHttpUrl())) + assertTrue(problem is DiarySignInProblem.Unexpected) + } + + @Test + fun `only a failure nobody judged keeps the session for a retry`() { + val kept = listOf( + DiarySignInProblem.RegisterUnreachable, + DiarySignInProblem.Timeout(null), + DiarySignInProblem.ProviderUnavailable(null), + DiarySignInProblem.TooManyAttempts(10), + ) + val dropped = listOf( + DiarySignInProblem.ServerRefusedSession, + DiarySignInProblem.NoStudent, + DiarySignInProblem.ServerDisabled, + DiarySignInProblem.ServerAddressRefused, + DiarySignInProblem.ProviderUnreadable(null), + DiarySignInProblem.SessionAgedOut, + DiarySignInProblem.Unexpected("422"), + ) + kept.forEach { assertTrue(it.toString(), it.retryKeepsSession) } + dropped.forEach { assertTrue(it.toString(), !it.retryKeepsSession) } + } + + @Test + fun `an already classified problem passes through`() { + assertEquals(DiarySignInProblem.NoStudent, DiarySignInProblem.of(DiarySignInProblem.NoStudent)) + } + + private fun row(label: String, thrown: Throwable, problem: DiarySignInProblem, action: Action) = + Triple(label, thrown, problem to action) + + private fun http(code: Int, vararg headers: Pair): HttpException { + val request = Request.Builder().url("https://school.example/api/v1/diary/session").build() + val raw = okhttp3.Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(code) + .message("error") + .apply { headers.forEach { (name, value) -> header(name, value) } } + .build() + return HttpException( + Response.error("""{"detail":"no"}""".toResponseBody("application/json".toMediaType()), raw), + ) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt new file mode 100644 index 00000000..909673d0 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt @@ -0,0 +1,575 @@ +package com.lumenpearson.lessons.core.data.repository + +import com.lumenpearson.lessons.core.data.network.DiaryApi +import com.lumenpearson.lessons.core.data.network.NetworkModule +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException +import com.lumenpearson.lessons.core.data.network.dto.DiaryAttendanceDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryCapabilitiesDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryHomeworkDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryLessonDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryMarkDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryOverrideRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryPeriodDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryProvidersDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryResetRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionRequestDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySessionResponseDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryStudentDto +import com.lumenpearson.lessons.core.data.network.dto.DiarySubjectDto +import com.lumenpearson.lessons.core.data.network.dto.DiaryTeacherDto +import com.lumenpearson.lessons.core.data.network.dto.NetSchoolCapabilitiesDto +import com.lumenpearson.lessons.core.data.upstream.FakeUpstreamDirectory +import com.lumenpearson.lessons.core.data.upstream.MutableClock +import com.lumenpearson.lessons.core.data.upstream.NetSchoolScript +import com.lumenpearson.lessons.core.data.upstream.NetSchoolSignIn +import com.lumenpearson.lessons.core.data.upstream.PETERSBURG_JWT +import com.lumenpearson.lessons.core.data.upstream.SCRIPT_SESSION_COOKIE +import com.lumenpearson.lessons.core.data.upstream.Vectors +import com.lumenpearson.lessons.core.data.upstream.UpstreamHttp +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession +import com.lumenpearson.lessons.core.data.upstream.jsonAnswer +import com.lumenpearson.lessons.core.data.upstream.netschoolTarget +import com.lumenpearson.lessons.core.data.upstream.originOf +import com.lumenpearson.lessons.core.data.upstream.rawAnswer +import com.lumenpearson.lessons.core.data.upstream.regionAt +import java.io.IOException +import java.time.Duration +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import retrofit2.HttpException +import retrofit2.Response + +/** + * Getting into a diary from the phone, end to end: the preflight that runs + * before a password is taken, the sign-in with the diary's own server (a real + * socket, MockWebServer), the registration with ours (scripted), and what is + * kept at the end of it — our bearer and the target, never the diary's session + * and never the password. + */ +class DiarySignInTest { + + private lateinit var server: MockWebServer + private lateinit var script: NetSchoolScript + private val api = ScriptedDiaryApi() + private val store = RecordingStore() + private val clock = MutableClock() + private var forgotten = 0 + + @Before + fun setUp() { + server = MockWebServer() + script = NetSchoolScript() + server.dispatcher = script + server.start() + } + + @After + fun tearDown() { + server.close() + } + + // ---- the whole way in ---------------------------------------------------- + + @Test + fun `a sign-in registers and stores our bearer and the target, never the upstream credential`() = runBlocking { + val registration = signIn().signIn(netschoolTarget(), "hunter2").getOrThrow() + + val stored = store.session!! + assertEquals("ours", stored.token) + assertEquals("parent", stored.login) + assertEquals("zabaikalsky", stored.target.region) + assertEquals(42L, stored.target.schoolId) + assertEquals("Школа № 1", stored.target.schoolName) + // The zone is the server's, so the phone's «today» is its too. + assertEquals("Asia/Chita", stored.target.zone) + assertEquals(stored, registration.session) + assertEquals(listOf(7L), registration.students.map { it.id }) + + // Nothing the diary handed over, and nothing typed, is kept anywhere. + val everything = "$stored ${store.target} ${store.student}" + for (secret in listOf("after-role", "hunter2", NetSchoolScript_COOKIE)) { + assertFalse(secret, secret in everything) + } + } + + /** + * The one body that ever leaves for our server carries the diary's session + * and no password — there is no field for one, and the server refuses any + * key it does not know. + */ + @Test + fun `the registration body is the server's shape and carries no password`() = runBlocking { + signIn().signIn(netschoolTarget(), "hunter2").getOrThrow() + + val written = Json.parseToJsonElement( + NetworkModule.json().encodeToString(DiarySessionRequestDto.serializer(), api.registered.single()), + ).jsonObject + assertEquals(setOf("provider", "login", "region", "school_id", "credential"), written.keys) + assertEquals("netschool", written.getValue("provider").jsonPrimitive.content) + assertEquals("42", written.getValue("school_id").jsonPrimitive.content) + val credential = written.getValue("credential").jsonObject + assertEquals(setOf("at", "cookies", "ver"), credential.keys) + assertEquals("after-role", credential.getValue("at").jsonPrimitive.content) + assertEquals( + mapOf("NSSESSIONID" to NetSchoolScript_COOKIE), + credential.getValue("cookies").jsonObject.mapValues { it.value.jsonPrimitive.content }, + ) + assertFalse("hunter2" in written.toString()) + } + + @Test + fun `a Petersburg sign-in registers the token Petersburg issued`() = runBlocking { + signIn().signIn(DiaryTarget.petersburg(" parent@example.com "), "secret").getOrThrow() + + val body = api.registered.single() + assertEquals("petersburg", body.provider) + assertEquals("parent@example.com", body.login) + assertNull(body.region) + assertEquals(PETERSBURG_JWT, body.credential.getValue("token").jsonPrimitive.content) + assertEquals(DiaryProviderKey.PETERSBURG, store.session!!.target.provider) + } + + // ---- the preflight: before any password ---------------------------------- + + @Test + fun `no server address fails before any upstream request`() = runBlocking { + api.capabilities = { throw ServerAddressMissingException() } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.ServerMissing, failure) + assertEquals(0, server.requestCount) + } + + @Test + fun `a 404 on capabilities fails before the password is sent`() = runBlocking { + api.capabilities = { throw httpError(404) } + + val failure = signIn().preflight(netschoolTarget()).exceptionOrNull() + + assertEquals(DiarySignInProblem.ServerTooOld, failure) + assertEquals(0, server.requestCount) + } + + @Test + fun `a server with its diary switched off fails before the password is sent`() = runBlocking { + api.capabilities = { DiaryCapabilitiesDto(enabled = false, registration = true) } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.ServerDisabled, failure) + assertEquals(0, server.requestCount) + } + + @Test + fun `a region the server does not list fails before the password is sent`() = runBlocking { + api.capabilities = { listing(regions = listOf("samara")) } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.RegionNotServed, failure) + assertEquals(0, server.requestCount) + } + + @Test + fun `a region the phone's catalog does not know is not asked about at all`() = runBlocking { + val failure = signIn().preflight(netschoolTarget(region = "volgograd")).exceptionOrNull() + + assertEquals(DiarySignInProblem.RegionNotServed, failure) + assertEquals(0, api.capabilityCalls) + } + + @Test + fun `a Gosuslugi-only region is handed off to its own site with nothing sent`() = runBlocking { + val directory = FakeUpstreamDirectory(null, listOf(regionAt(server, key = "tula", password = false))) + + val failure = signIn(directory).signIn(netschoolTarget(region = "tula"), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.GosuslugiOnly("https://region.zabedu.ru"), failure) + assertEquals(0, server.requestCount) + assertEquals(0, api.capabilityCalls) + } + + @Test + fun `a login too short fails before anything is sent`() = runBlocking { + val failure = signIn().openUpstream(netschoolTarget(login = " ab "), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.LoginTooShort, failure) + assertEquals(0, server.requestCount) + } + + // ---- the diary's own answer ---------------------------------------------- + + @Test + fun `a refusal by the diary names the diary's host`() = runBlocking { + script.logindata = { rawAnswer(403, "application/json", "{}") } + + val failure = signIn().openUpstream(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.ProviderRefusesPhone(originOf(server).host), failure) + } + + /** K19: `logindata` says «Госуслуги only» and names no site; the catalog does. */ + @Test + fun `logindata saying Gosuslugi only hands off to the catalog's site`() = runBlocking { + script.logindata = { jsonAnswer(200, Json.parseToJsonElement("""{"schoolLogin":false}""")) } + + val failure = signIn().openUpstream(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.GosuslugiOnly("https://region.zabedu.ru"), failure) + } + + @Test + fun `a wrong password carries what the diary said and nothing typed`() = runBlocking { + script.logins.addLast { jsonAnswer(409, Json.parseToJsonElement("""{"message":"Неверный пароль"}""")) } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.WrongPassword("Неверный пароль"), failure) + assertFalse("hunter2" in failure.toString()) + assertTrue(api.registered.isEmpty()) + } + + /** A session the diary shaped in a way the server would refuse is «unreadable», not a 422 from us. */ + @Test + fun `a Petersburg token that is not a JWT is never sent`() = runBlocking { + script.petersburg = { rawAnswer(200, "application/json", """{"data":{"token":"not-a-jwt"}}""") } + + val failure = signIn().signIn(DiaryTarget.petersburg("parent@example.com"), "secret").exceptionOrNull() + + assertTrue(failure is DiarySignInProblem.ProviderUnreadable) + assertTrue(api.registered.isEmpty()) + } + + @Test + fun `a NetSchool session without its session cookie is never sent`() = runBlocking { + val sessionless = NetSchoolScript(logindata = { jsonAnswer(200, Vectors.flow.getValue("logindata")) }) + server.dispatcher = sessionless + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + + val failure = signIn.register(upstream).exceptionOrNull() + + assertTrue(failure is DiarySignInProblem.ProviderUnreadable) + assertTrue(api.registered.isEmpty()) + // And said goodbye to, since nobody can use it. + assertEquals(1, sessionless.to(NetSchoolSignIn.LOGOUT_PATH).size) + } + + // ---- the registration ---------------------------------------------------- + + @Test + fun `a refused registration logs out upstream once`() = runBlocking { + api.register = { throw httpError(409) } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertEquals(DiarySignInProblem.ServerRefusedSession, failure) + assertEquals(1, script.to(NetSchoolSignIn.LOGOUT_PATH).size) + assertNull(store.session) + } + + @Test + fun `registration 403 is an account with no pupil`() = runBlocking { + api.register = { throw httpError(403) } + + assertEquals(DiarySignInProblem.NoStudent, signIn().signIn(netschoolTarget(), "x1").exceptionOrNull()) + } + + /** A 422 is a body the server refused before asking anybody — ours to fix, not a password to retype. */ + @Test + fun `registration 422 is unexpected, not a wrong password`() = runBlocking { + api.register = { throw httpError(422) } + + val failure = signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull() + + assertTrue(failure is DiarySignInProblem.Unexpected) + assertEquals(DiarySignInProblem.Action.RETRY, (failure as DiarySignInProblem).action) + } + + @Test + fun `registration 503s are told apart by their header`() = runBlocking { + val cases = mapOf( + "disabled" to DiarySignInProblem.ServerDisabled, + "address-refused" to DiarySignInProblem.ServerAddressRefused, + "upstream" to DiarySignInProblem.ProviderUnavailable(null), + ) + for ((reason, wanted) in cases) { + api.register = { throw httpError(503, DiaryFailure.UNAVAILABLE_HEADER to reason) } + assertEquals(reason, wanted, signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull()) + } + } + + @Test + fun `registration 504 is a timeout`() = runBlocking { + api.register = { throw httpError(504) } + + assertEquals(DiarySignInProblem.Timeout(null), signIn().signIn(netschoolTarget(), "hunter2").exceptionOrNull()) + } + + /** + * Throttled: the session is still good and still held, so the retry after + * the wait registers it again — without asking for the password. + */ + @Test + fun `registration 429 carries the wait and keeps the session for a retry`() = runBlocking { + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + api.register = { throw httpError(429, "Retry-After" to "30") } + + val failure = signIn.register(upstream).exceptionOrNull() as DiarySignInProblem + + assertEquals(DiarySignInProblem.TooManyAttempts(30), failure) + assertTrue(failure.retryKeepsSession) + assertTrue(script.to(NetSchoolSignIn.LOGOUT_PATH).isEmpty()) + + api.register = ACCEPT + assertEquals("ours", signIn.register(upstream).getOrThrow().session.token) + assertEquals(1, script.to(NetSchoolSignIn.LOGIN_PATH).size) + } + + @Test + fun `a registration that cannot reach the server keeps the session for a retry`() = runBlocking { + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + api.register = { throw IOException("connection reset") } + + val failure = signIn.register(upstream).exceptionOrNull() as DiarySignInProblem + + assertEquals(DiarySignInProblem.RegisterUnreachable, failure) + assertTrue(failure.retryKeepsSession) + api.register = ACCEPT + assertTrue(signIn.register(upstream).isSuccess) + } + + @Test + fun `an aged-out upstream session is discarded, not registered`() = runBlocking { + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + clock.now = clock.now.plus(Duration.ofMinutes(11)) + + val failure = signIn.register(upstream).exceptionOrNull() + + assertEquals(DiarySignInProblem.SessionAgedOut, failure) + assertTrue(api.registered.isEmpty()) + assertEquals(1, script.to(NetSchoolSignIn.LOGOUT_PATH).size) + } + + /** «Сетевой город» says how long its sessions idle for; that, not ten minutes, is the limit. */ + @Test + fun `a session's own idle window decides when it is too old`() = runBlocking { + script.logins.addLast { jsonAnswer(200, Json.parseToJsonElement("""{"at":"bearer-1","timeOut":1800000}""")) } + script.logindata = { + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json") + .addHeader("Set-Cookie", "NSSESSIONID=s1; Path=/").body("{}").build() + } + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + clock.now = clock.now.plus(Duration.ofMinutes(20)) + + assertTrue(signIn.register(upstream).isSuccess) + } + + @Test + fun `a registered session is never registered or discarded again`() = runBlocking { + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + signIn.register(upstream).getOrThrow() + + signIn.discard(upstream) + val again = signIn.register(upstream).exceptionOrNull() + + assertTrue(again is DiarySignInProblem.Unexpected) + assertEquals(1, api.registered.size) + // Saying goodbye would end the session the server now holds. + assertTrue(script.to(NetSchoolSignIn.LOGOUT_PATH).isEmpty()) + } + + @Test + fun `backing out before registration says goodbye upstream once`() = runBlocking { + val signIn = signIn() + val upstream = signIn.openUpstream(netschoolTarget(), "hunter2").getOrThrow() + + signIn.discard(upstream) + signIn.discard(upstream) + + assertEquals(1, script.to(NetSchoolSignIn.LOGOUT_PATH).size) + } + + // ---- what is kept ----------------------------------------------------------- + + /** Re-authentication: the same provider, region and school, and only the password typed. */ + @Test + fun `re-auth reuses provider, region and school`() = runBlocking { + val kept = DiaryTarget.netschool("zabaikalsky", 42, "Школа № 1", "parent", "Asia/Chita") + store.target = kept + + signIn().signIn(kept, "hunter2").getOrThrow() + + val body = api.registered.single() + assertEquals("zabaikalsky", body.region) + assertEquals(42L, body.schoolId) + assertEquals("42", script.to(NetSchoolSignIn.LOGIN_PATH).single().body!!.utf8().substringAfter("scid=").substringBefore('&')) + } + + @Test + fun `a different account empties what was kept first, and the same account keeps it`() = runBlocking { + store.target = DiaryTarget.netschool("zabaikalsky", 42, null, "parent", "Asia/Chita") + store.student = 7 + + signIn().signIn(netschoolTarget(login = "PARENT"), "hunter2").getOrThrow() + assertEquals(0, forgotten) + assertEquals(7L, store.student) + + signIn().signIn(netschoolTarget(login = "other-parent"), "hunter2").getOrThrow() + assertEquals(1, forgotten) + assertNull(store.student) + } + + @Test + fun `an upstream session never prints or exposes its secret`() = runBlocking { + val upstream: UpstreamSession = signIn().openUpstream(netschoolTarget(), "hunter2").getOrThrow() + + assertEquals("UpstreamSession(netschool, )", upstream.toString()) + assertFalse(upstream is java.io.Serializable) + } + + // ---- plumbing --------------------------------------------------------------- + + private fun signIn( + directory: FakeUpstreamDirectory = FakeUpstreamDirectory(originOf(server), listOf(regionAt(server))), + ) = DiarySignInImpl( + api = api, + store = store, + directory = { directory }, + client = { UpstreamHttp.client { directory.allowedOrigins() } }, + forgetLocal = { forgotten++ }, + clock = clock, + ioDispatcher = Dispatchers.Unconfined, + ) + + private fun listing(regions: List = listOf("zabaikalsky")) = DiaryCapabilitiesDto( + enabled = true, + registration = true, + providers = DiaryProvidersDto(petersburg = JsonObject(emptyMap()), netschool = NetSchoolCapabilitiesDto(regions)), + ) + + /** Our server, as far as registration goes; every read fails the test. */ + private inner class ScriptedDiaryApi : DiaryApi { + var capabilities: () -> DiaryCapabilitiesDto = { listing() } + var register: (DiarySessionRequestDto) -> DiarySessionResponseDto = ACCEPT + var capabilityCalls = 0 + val registered = mutableListOf() + + override suspend fun capabilities(): DiaryCapabilitiesDto { + capabilityCalls++ + return capabilities.invoke() + } + + override suspend fun registerSession(body: DiarySessionRequestDto): DiarySessionResponseDto { + val answer = register(body) + registered += body + return answer + } + + override suspend fun logout() = fail() + override suspend fun students(): List = fail() + override suspend fun schedule(studentId: Long, from: String, to: String): List = fail() + override suspend fun homework(studentId: Long, from: String, to: String): List = fail() + override suspend fun grades(studentId: Long, from: String, to: String): List = fail() + override suspend fun periods(studentId: Long): List = fail() + override suspend fun subjects(studentId: Long, periodId: Long?): List = fail() + override suspend fun teachers(studentId: Long): List = fail() + override suspend fun attendance(studentId: Long): List = fail() + override suspend fun overrides(studentId: Long): List = fail() + override suspend fun putOverride(studentId: Long, body: DiaryOverrideRequestDto): DiaryOverrideDto = fail() + override suspend fun resetOverride(studentId: Long, body: DiaryResetRequestDto) = fail() + override suspend fun resetOverrides(studentId: Long) = fail() + + private fun fail(): Nothing = throw AssertionError("a sign-in reads nothing from the diary") + } + + /** The store, with nothing in it but what was last written. */ + private class RecordingStore : DiarySessionStore { + var session: DiarySession? = null + var target: DiaryTarget? = null + var student: Long? = null + + override val diarySession: Flow get() = MutableStateFlow(session) + override suspend fun currentDiarySession(): DiarySession? = session + override suspend fun writeDiarySession(value: DiarySession) { + session = value + target = value.target + } + + override suspend fun clearDiaryToken() { + session = null + } + + override suspend fun forgetDiary() { + session = null + target = null + student = null + } + + override val diaryTarget: Flow get() = MutableStateFlow(target) + override suspend fun currentDiaryTarget(): DiaryTarget? = target + override val selectedStudentId: Flow get() = MutableStateFlow(student) + override suspend fun selectStudent(id: Long?) { + student = id + } + } + + private companion object { + /** What the script's `logindata` sets as `NSSESSIONID`. */ + const val NetSchoolScript_COOKIE = SCRIPT_SESSION_COOKIE + } +} + +/** Our server's answer to a registration it accepts, echoing what was sent. */ +private val ACCEPT: (DiarySessionRequestDto) -> DiarySessionResponseDto = { body -> + DiarySessionResponseDto( + token = "ours", + login = body.login, + provider = body.provider, + region = body.region, + schoolId = body.schoolId, + schoolName = if (body.provider == "netschool") "Школа № 1" else null, + zone = if (body.provider == "netschool") "Asia/Chita" else "Europe/Moscow", + students = listOf(DiaryStudentDto(id = 7, firstName = "Пётр", lastName = "Иванов", fullName = "Иванов Пётр")), + ) +} + +private fun httpError(code: Int, vararg headers: Pair): HttpException { + val request = Request.Builder().url("https://school.example/api/v1/diary/session").build() + val raw = okhttp3.Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(code) + .message("error") + .apply { headers.forEach { (name, value) -> header(name, value) } } + .build() + return HttpException( + Response.error("""{"detail":"no"}""".toResponseBody("application/json".toMediaType()), raw), + ) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt new file mode 100644 index 00000000..839d5e61 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/ShellModeTest.kt @@ -0,0 +1,117 @@ +package com.lumenpearson.lessons.core.data.repository + +import androidx.datastore.preferences.core.mutablePreferencesOf +import com.lumenpearson.lessons.core.data.datastore.DiaryKeys +import com.lumenpearson.lessons.core.data.datastore.ShellKeys +import com.lumenpearson.lessons.core.data.datastore.shellState +import com.lumenpearson.lessons.core.data.datastore.writeMemberships +import com.lumenpearson.lessons.core.data.diary.MemoryDiaryStore +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Which home the app opens on, and the two decisions that hang off it. + * + * The mode is read from the stored keys only, in one emission, so these tests + * write keys into a plain `MutablePreferences` — the same function the + * preferences' flow maps every emission through. + */ +class ShellModeTest { + + private val session = Session(classId = 7, className = "7A", school = null, token = "class-token") + private val samara = DiaryTarget.netschool("samara", 1234, "School 5", "ivanova", "Europe/Samara") + + @Test + fun `a class outranks a diary`() { + assertEquals(ShellMode.CLASS, shellModeOf(session, samara)) + assertEquals(ShellMode.CLASS, shellModeOf(session, null)) + } + + @Test + fun `a diary without a class is the diary home, not the join screen`() { + assertEquals(ShellMode.DIARY, shellModeOf(null, samara)) + } + + @Test + fun `nothing stored is none`() { + assertEquals(ShellMode.NONE, shellModeOf(null, null)) + assertEquals(ShellState(ShellMode.NONE, held = false), mutablePreferencesOf().shellState()) + } + + /** A bare `401` drops the bearer and keeps the target: the family belongs on their diary's form. */ + @Test + fun `a diary target without a token is still diary mode`() { + val prefs = mutablePreferencesOf( + DiaryKeys.TARGET to DiaryTargetCodec.encode(samara), + ) + assertEquals(ShellMode.DIARY, prefs.shellState().mode) + } + + @Test + fun `an install from before targets, signed in to Petersburg, is diary mode`() { + val prefs = mutablePreferencesOf( + DiaryKeys.TOKEN to "diary-token", + DiaryKeys.LOGIN to "parent@example.com", + ) + assertEquals(ShellMode.DIARY, prefs.shellState().mode) + } + + /** #151: leaving the last class with a diary signed in lands on the diary, where its sign-out is. */ + @Test + fun `leaving the last class with a diary signed in is diary mode`() { + val prefs = mutablePreferencesOf(DiaryKeys.TARGET to DiaryTargetCodec.encode(samara)) + prefs.writeMemberships(listOf(session)) + assertEquals(ShellMode.CLASS, prefs.shellState().mode) + + prefs.writeMemberships(emptyList()) + + assertEquals(ShellMode.DIARY, prefs.shellState().mode) + } + + @Test + fun `the hold is read with the mode, from the same keys`() { + val prefs = mutablePreferencesOf(ShellKeys.ONBOARDING_HELD to true) + prefs.writeMemberships(listOf(session)) + + assertEquals(ShellState(ShellMode.CLASS, held = true), prefs.shellState()) + } + + /** #152: a cold start in no class must not arm the periodic class sync again. */ + @Test + fun `periodic sync is armed only in a class`() { + assertEquals(SyncArming.Armed(30), syncArmingFor(ShellMode.CLASS, 30)) + assertEquals(SyncArming.Disarmed, syncArmingFor(ShellMode.NONE, 30)) + assertEquals(SyncArming.Disarmed, syncArmingFor(ShellMode.DIARY, 30)) + } + + /** K24: the widget's sentence depends on the mode, and it redraws only when told. */ + @Test + fun `the mode changes a registration or a sign-out makes are announced, and a dead bearer is not`() = runTest { + var announced = 0 + val store = ModeAnnouncingDiaryStore(MemoryDiaryStore(session = null)) { announced++ } + + store.writeDiarySession(DiarySession(login = "ivanova", token = "t", target = samara)) + assertEquals(1, announced) + + store.clearDiaryToken() + assertEquals(1, announced) + + store.forgetDiary() + assertEquals(2, announced) + } + + @Test + fun `the store still does what it is asked when it announces`() = runTest { + val inner = MemoryDiaryStore(session = null) + val store = ModeAnnouncingDiaryStore(inner) {} + + store.writeDiarySession(DiarySession(login = "ivanova", token = "t", target = samara)) + assertTrue(inner.session != null) + + store.forgetDiary() + assertFalse(inner.session != null) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt new file mode 100644 index 00000000..701192ab --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt @@ -0,0 +1,69 @@ +package com.lumenpearson.lessons.core.data.sync + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Nothing that runs without somebody looking at the app reads the diary. + * + * It is a rule about the product rather than about code. A diary read is what + * keeps our server's copy of a family's session alive (`last_used_at`), and the + * owner's rule is that «activity» means a person using the app — so a worker + * or a widget that read the diary would keep a session alive for ever with + * nobody behind it, and would also wake the phone to do it. The foreground + * refresh (`DiaryImport.refreshIfStale`) is the one sanctioned reader. + * + * No behaviour test can see a read that is simply never supposed to exist, + * so this reads the sources the way `DaoDeletePolicyTest` reads the SQL: the + * sync worker, every file of the widget module, and the alerts — the three + * things the system wakes on its own. What it cannot see: a diary read reached + * through some other name, or a new background entry point outside these + * folders. + */ +class SyncWorkerSourceTest { + + private companion object { + /** The types and the container properties that reach the diary. */ + val DIARY = Regex("""\b(DiaryRepository|DiaryImport|DiaryCache|DiaryApi|diaryRepository|diaryImport|diaryCache)\b""") + } + + private val worker = File("src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt") + private val widget = File("../../widget/src/main") + private val alerts = File("src/main/kotlin/com/lumenpearson/lessons/core/data/notifications") + + private fun kotlinUnder(root: File): List = + root.walkTopDown().filter { it.isFile && it.extension == "kt" }.toList() + + @Test + fun `the sources are where this test thinks they are`() { + assertTrue(worker.absolutePath, worker.isFile) + assertTrue(widget.absolutePath, kotlinUnder(widget).size >= 5) + assertTrue(alerts.absolutePath, kotlinUnder(alerts).size >= 3) + } + + @Test + fun `the worker and the widget never reference the diary`() { + val offenders = (listOf(worker) + kotlinUnder(widget) + kotlinUnder(alerts)) + .flatMap { file -> + file.readLines().mapIndexedNotNull { index, line -> + DIARY.find(line)?.let { "${file.path}:${index + 1}: ${line.trim()}" } + } + } + assertEquals( + "A background path reaches the diary; see the class note for why it may not:\n" + + offenders.joinToString("\n"), + emptyList(), + offenders, + ) + } + + /** The guard's own regex, so a rename of the diary types is noticed here first. */ + @Test + fun `the guard recognises what it is looking for`() { + assertTrue(DIARY.containsMatchIn("Graph.container.diaryRepository.students()")) + assertTrue(DIARY.containsMatchIn("val import: DiaryImport")) + assertTrue(!DIARY.containsMatchIn("DiaryRepositoryImplementation")) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/Cp1251Test.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/Cp1251Test.kt new file mode 100644 index 00000000..58bbe329 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/Cp1251Test.kt @@ -0,0 +1,59 @@ +package com.lumenpearson.lessons.core.data.upstream + +import java.nio.CharBuffer +import java.nio.charset.Charset +import java.nio.charset.CodingErrorAction +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The windows-1251 table the «Сетевой город» hash is computed over. + * + * The phone carries its own table rather than asking the platform, because + * Android's charsets come from ICU and nothing here has checked ICU's + * windows-1251 against CPython's `cp1251`, which is what the server hashes + * with. The JVM's own charset is known to agree with CPython on every BMP code + * point, so this holds the table to the JVM's, character by character. + */ +class Cp1251Test { + + @Test + fun `the table encodes every BMP code point exactly as the JVM windows-1251 charset does`() { + val encoder = Charset.forName("windows-1251").newEncoder() + .onUnmappableCharacter(CodingErrorAction.REPORT) + .onMalformedInput(CodingErrorAction.REPORT) + var encodable = 0 + for (code in 0..0xFFFF) { + val char = code.toChar() + if (char.isSurrogate()) continue + val jvm = if (encoder.canEncode(char)) { + encoder.reset() + val buffer = encoder.encode(CharBuffer.wrap(charArrayOf(char))) + ByteArray(buffer.remaining()).also { buffer.get(it) } + } else { + null + } + val ours = Cp1251.encode(char.toString()) + if (jvm == null) { + assertNull("U+%04X".format(code), ours) + } else { + encodable++ + assertArrayEquals("U+%04X".format(code), jvm, ours) + } + } + // ASCII's 128 and the high half's 127: every byte but 0x98. + assertEquals(255, encodable) + } + + /** A question mark in place of a character would hash a different password, and say nothing. */ + @Test + fun `0x98 and characters outside the table are refused, never replaced by a question mark`() { + assertNull(Cp1251.encode("a\u0098b")) + assertNull(Cp1251.encode("ü")) + assertNull(Cp1251.encode("😀")) + assertNull(Cp1251.encode("\uD83D")) + assertArrayEquals(byteArrayOf(0xB8.toByte(), 0xA8.toByte(), 0xB9.toByte()), Cp1251.encode("ёЁ№")) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt new file mode 100644 index 00000000..36b09514 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt @@ -0,0 +1,439 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.repository.DiarySessionIdleDays +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull +import mockwebserver3.MockWebServer +import okhttp3.Headers.Companion.headersOf +import okhttp3.HttpUrl.Companion.toHttpUrl +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The shared known answers for both diary sign-ins, run through the real + * Kotlin code — the phone's half of `server/tests/test_diary_protocol_vectors.py`. + * + * The sign-in protocol of each diary now lives in two codebases: the phone + * signs in itself and hands the session over, and the server signs in with a + * password on the bot's page and the older `/login`. Two implementations of one + * protocol drift apart within a month unless something holds them to one set of + * answers; `server/tests/vectors/diary_protocol.json` is that set, read in + * place, and neither implementation is the oracle. + * + * Every request-shaped case goes over a real socket to MockWebServer, through + * the same client the app uses, so a case that fails here is a behaviour of the + * code and not of a re-implementation of its rules. A rule that is not a + * request — the hash, the role pick, the charset checks — is asked of the + * function that implements it. + * + * What a failure here means: the Kotlin side changed and the file did not, or + * the reverse. Change them together, and the server's test with them. + */ +class DiaryProtocolVectorsTest { + + private lateinit var server: MockWebServer + private val clock = MutableClock() + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + // ---- what both sides share ---------------------------------------------- + + @Test + fun `the user agent, the Petersburg origin and its session cookie are the server's`() { + val root = Vectors.root + assertEquals(root.getValue("user_agent").jsonPrimitive.content, UpstreamHttp.USER_AGENT) + assertEquals(Vectors.petersburg.getValue("session_cookie").jsonPrimitive.content, PetersburgSignIn.SESSION_COOKIE) + assertEquals(Vectors.petersburg.getValue("login_path").jsonPrimitive.content, PetersburgSignIn.LOGIN_PATH) + // And the origin the phone signs in to is the catalog's, which is the + // only place the phone learns a host from. + val catalog = RegionCatalog.parse(resource("regions.json")) + assertEquals( + Vectors.petersburg.getValue("origin").jsonPrimitive.content.toHttpUrl(), + CatalogUpstreamDirectory(catalog).petersburg, + ) + } + + @Test + fun `the idle window the screens promise is the server's`() { + val days = Vectors.root.getValue("session").jsonObject.getValue("idle_days").jsonPrimitive.int + assertEquals(days.toLong(), DiarySessionIdleDays) + } + + @Test + fun `the credential charset rule matches the shared vectors`() { + val credential = Vectors.root.getValue("credential").jsonObject + assertEquals( + credential.getValue("pattern").jsonPrimitive.content, + "^" + UpstreamValues.COOKIE_VALUE.pattern + "$", + ) + for (case in Vectors.cases(credential, "cases")) { + val value = case.getValue("value").jsonPrimitive.content + val ok = case.getValue("ok").jsonPrimitive.booleanOrNull!! + assertEquals("credential ${value.quoted()}", ok, UpstreamValues.cookieValueOk(value)) + } + } + + @Test + fun `the header token rule matches the shared vectors`() { + val token = Vectors.root.getValue("header_token").jsonObject + assertEquals( + token.getValue("pattern").jsonPrimitive.content, + "^" + UpstreamValues.HEADER_TOKEN.pattern + "$", + ) + for (case in Vectors.cases(token, "cases")) { + val value = case.getValue("value").jsonPrimitive.content + val ok = case.getValue("ok").jsonPrimitive.booleanOrNull!! + assertEquals("header value ${value.quoted()}", ok, UpstreamValues.headerValueOk(value)) + } + } + + // ---- Petersburg ----------------------------------------------------------- + + @Test + fun `petersburg login answers match the shared vectors`() = runBlocking { + val fields = Vectors.petersburg.getValue("login_fields").jsonObject + for (case in Vectors.cases(Vectors.petersburg, "login_cases")) { + val name = case.getValue("name").jsonPrimitive.content + server.enqueue( + rawAnswer( + status = case.getValue("status").jsonPrimitive.int, + contentType = case.getValue("content_type").jsonPrimitive.content, + body = case.getValue("body").jsonPrimitive.content, + cookies = case.getValue("set_cookie").jsonArray.map { it.jsonPrimitive.content }, + ), + ) + val outcome = runCatching { + PetersburgSignIn(clientFor(server), originOf(server), clock) + .signIn(DiaryTarget.petersburg("parent@example.com"), "secret") + } + + val request = server.takeRequest() + assertEquals(name, Vectors.petersburg.getValue("login_path").jsonPrimitive.content, request.url.encodedPath) + // Nobody is signed in yet, so nothing rides along. + assertNull(name, request.headers["Cookie"]) + val sent = Json.parseToJsonElement(request.body!!.utf8()).jsonObject + assertEquals(name, fields.keys + setOf("login", "password"), sent.keys) + for ((field, value) in fields) assertEquals("$name: $field", value, sent[field]) + + val expect = case.getValue("expect").jsonObject + val failure = expect["failure"]?.jsonPrimitive?.content + if (failure != null) { + assertEquals(name, failure, kindOf(outcome.exceptionOrNull())) + } else { + assertEquals(name, expect.getValue("token").jsonPrimitive.content, outcome.getOrThrow().token) + } + } + } + + @Test + fun `the session cookie rule matches the shared vectors`() { + val cookie = Vectors.petersburg.getValue("session_cookie").jsonPrimitive.content + val url = (Vectors.petersburg.getValue("origin").jsonPrimitive.content + + Vectors.petersburg.getValue("login_path").jsonPrimitive.content).toHttpUrl() + val withCookies = Vectors.cases(Vectors.petersburg, "login_cases") + .filter { it.getValue("set_cookie").jsonArray.isNotEmpty() } + assertTrue("the vectors carry cookie cases", withCookies.isNotEmpty()) + for (case in withCookies) { + val headers = headersOf( + *case.getValue("set_cookie").jsonArray + .flatMap { listOf("Set-Cookie", it.jsonPrimitive.content) } + .toTypedArray(), + ) + val token = case.getValue("expect").jsonObject.getValue("token").jsonPrimitive.content + // «body» means the answer carried no live session cookie at all. + val wanted = token.takeUnless { it == "body" } + assertEquals( + case.getValue("name").jsonPrimitive.content, + wanted, + UpstreamHttp.sessionCookie(url, headers, cookie, clock.millis()), + ) + } + } + + // ---- «Сетевой город» ------------------------------------------------------ + + @Test + fun `the session cookies and the login form are the server's`() { + assertEquals( + Vectors.netschool.getValue("session_cookies").jsonArray.map { it.jsonPrimitive.content }, + NetSchoolSignIn.SESSION_COOKIES, + ) + } + + @Test + fun `netschool hashes match the shared vectors`() { + for (case in Vectors.cases(Vectors.netschool, "hash")) { + val salt = case.getValue("salt").jsonPrimitive.content + val password = case.getValue("password").jsonPrimitive.content + val hashed = NetSchoolPassword.hash(salt, password) + if ("failure" in case) { + // Refused, and refused without the character in hand: the + // caller's failure carries nothing of what was typed. + assertNull(password.quoted(), hashed) + continue + } + assertEquals( + password.quoted(), + case.getValue("pw").jsonPrimitive.content to case.getValue("pw2").jsonPrimitive.content, + hashed, + ) + } + } + + @Test + fun `an unencodable password is bad credentials and the failure carries no part of it`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + val failure = runCatching { + NetSchoolSignIn(clientFor(server), clock).signIn(regionAt(server), netschoolTarget(), "пароль😀") + }.exceptionOrNull() + + assertEquals("bad_credentials", kindOf(failure)) + assertFalse("😀" in failure.toString()) + assertFalse("пароль" in failure.toString()) + // Nothing was posted: the refusal came before the login. + assertTrue(script.to(NetSchoolSignIn.LOGIN_PATH).isEmpty()) + } + + @Test + fun `logindata answers match the shared vectors`() = runBlocking { + for (case in Vectors.cases(Vectors.netschool, "logindata_cases")) { + val body = case.getValue("body") + val script = NetSchoolScript(logindata = { jsonAnswer(200, body) }) + val outcome = signIn(script) + + val expect = case.getValue("expect").jsonPrimitive.content + assertEquals("logindata $body", expect, kindOf(outcome.exceptionOrNull())) + if (expect == "ok") { + // The session's `ver` is logindata's `cacheVer`, and only a + // string or an integer — never the word "null" or "true". + assertEquals("logindata $body", case["ver"]?.jsonPrimitive?.contentOrNull, outcome.getOrThrow().ver) + } else { + // Nothing that failed at logindata may have asked for a salt. + assertTrue(script.to(NetSchoolSignIn.GETDATA_PATH).isEmpty()) + } + } + } + + @Test + fun `getdata answers match the shared vectors`() = runBlocking { + val formFields = Vectors.netschool.getValue("login_form_fields").jsonArray.map { it.jsonPrimitive.content } + for (case in Vectors.cases(Vectors.netschool, "getdata_cases")) { + val body = case.getValue("body") + val script = NetSchoolScript( + getdata = { jsonAnswer(200, body) }, + logins = ArrayDeque(listOf({ jsonAnswer(200, Json.parseToJsonElement("""{"at":"x"}""")) })), + ) + val outcome = signIn(script) + + val expect = case.getValue("expect").jsonPrimitive.content + assertEquals("getdata $body", expect, kindOf(outcome.exceptionOrNull())) + val logins = script.to(NetSchoolSignIn.LOGIN_PATH) + if (expect != "ok") { + // Nothing that failed at getdata may have posted a password. + assertTrue("getdata $body", logins.isEmpty()) + continue + } + val form = logins.single().form() + assertEquals("getdata $body", formFields, form.keys.toList()) + for ((field, value) in case.getValue("form").jsonObject) { + assertEquals("getdata $body: $field", value.jsonPrimitive.content, form[field]) + } + } + } + + @Test + fun `login answers match the shared vectors`() = runBlocking { + for (case in Vectors.cases(Vectors.netschool, "login_cases")) { + val status = case.getValue("status").jsonPrimitive.int + val body = case.getValue("body") + val label = "$status $body" + val answer = { jsonAnswer(status, body) } + val logins = if (case["tried_role"]?.jsonPrimitive?.booleanOrNull == true) { + ArrayDeque(listOf({ jsonAnswer(200, Vectors.flow.getValue("role_question")) }, answer)) + } else { + ArrayDeque(listOf(answer)) + } + val script = NetSchoolScript(logins = logins) + val outcome = signIn(script) + val expect = case.getValue("expect").jsonObject + + val failure = expect["failure"]?.jsonPrimitive?.content + if (failure != null) { + val thrown = outcome.exceptionOrNull() + assertEquals(label, failure, kindOf(thrown)) + if ("message" in expect) { + assertEquals( + label, + expect.getValue("message").jsonPrimitive.contentOrNull, + (thrown as UpstreamFailure.BadCredentials).upstreamMessage, + ) + } + continue + } + val session = outcome.getOrThrow() + if (expect["needs_role"]?.jsonPrimitive?.booleanOrNull == true) { + // Rerun with a fresh salt, and the role picked from the answer. + assertEquals(label, 2, script.to(NetSchoolSignIn.GETDATA_PATH).size) + val (first, second) = script.to(NetSchoolSignIn.LOGIN_PATH).map { it.form() } + assertFalse(label, "rolegroup" in first) + assertEquals(label, expect.getValue("rolegroup").jsonPrimitive.content, second["rolegroup"]) + assertEquals(label, "after-role", session.at) + continue + } + assertEquals(label, expect.getValue("at").jsonPrimitive.content, session.at) + assertEquals(label, expect.getValue("time_out").jsonPrimitive.longOrNull, session.timeOut) + } + } + + @Test + fun `role pick matches the shared vectors`() { + for (case in Vectors.cases(Vectors.netschool, "role_pick")) { + val body = case.getValue("body").jsonObject + assertEquals( + body.toString(), + case.getValue("expect").jsonPrimitive.contentOrNull, + NetSchoolSignIn.pickParentRole(body), + ) + } + } + + /** The one Cyrillic protocol constant beside the WAF markers, held to the vectors' parent role. */ + @Test + fun `the parent role marker matches the parent role the vectors name`() { + val question = Vectors.flow.getValue("role_question").jsonObject + val role = question.getValue("accountInfo").jsonObject.getValue("userRoles").jsonArray + .first().jsonObject.getValue("role").jsonObject + assertTrue(UpstreamMarkers.PARENT_ROLE in role.getValue("name").jsonPrimitive.content) + } + + @Test + fun `the refusal rule and its markers match the shared vectors`() = runBlocking { + val refusal = Vectors.netschool.getValue("refusal").jsonObject + assertEquals( + refusal.getValue("markers").jsonArray.map { it.jsonPrimitive.content }, + UpstreamMarkers.WAF, + ) + for (case in Vectors.cases(refusal, "cases")) { + val label = "${case["status"]} ${case["body"]}" + val script = NetSchoolScript( + logindata = { + rawAnswer( + status = case.getValue("status").jsonPrimitive.int, + contentType = case.getValue("content_type").jsonPrimitive.content, + body = case.getValue("body").jsonPrimitive.content, + ) + }, + ) + val refused = signIn(script).exceptionOrNull() is UpstreamFailure.AddressRefused + assertEquals(label, case.getValue("refused").jsonPrimitive.booleanOrNull, refused) + } + } + + @Test + fun `school search queries are cut like the shared vectors`() = runBlocking { + val search = Vectors.netschool.getValue("schools_search").jsonObject + assertEquals(search.getValue("path").jsonPrimitive.content, NetSchoolSchoolSearch.PATH) + assertEquals(search.getValue("query_parameter").jsonPrimitive.content, NetSchoolSchoolSearch.QUERY_PARAMETER) + val limit = search.getValue("query_cut_code_points").jsonPrimitive.int + assertEquals(limit, NetSchoolSchoolSearch.QUERY_CUT_CODE_POINTS) + for (case in Vectors.cases(search, "query_cases")) { + val script = NetSchoolScript() + server.dispatcher = script + val query = case.getValue("query").jsonPrimitive.content + searchOf(script).search("zabaikalsky", query).getOrThrow() + + val request = script.to(NetSchoolSchoolSearch.PATH).single() + // No session rides a search. + assertNull(request.headers["at"]) + assertNull(request.headers["Cookie"]) + val sent = request.url.queryParameter(NetSchoolSchoolSearch.QUERY_PARAMETER)!! + assertEquals(query.take(12), case.getValue("sent").jsonPrimitive.content, sent) + assertTrue(sent.codePointCount(0, sent.length) <= limit) + } + } + + @Test + fun `school search rows match the shared vectors`() = runBlocking { + val search = Vectors.netschool.getValue("schools_search").jsonObject + for (case in Vectors.cases(search, "cases")) { + val body = case.getValue("body") + val script = NetSchoolScript(search = { jsonAnswer(200, body) }) + server.dispatcher = script + val outcome = searchOf(script).search("zabaikalsky", "школа") + + val expect = case.getValue("expect") + if (expect is JsonPrimitive) { + assertEquals(body.toString(), "unexpected", expect.content) + assertTrue(body.toString(), outcome.exceptionOrNull() is DiarySignInProblem.ProviderUnreadable) + continue + } + val wanted = expect.jsonArray.map { row -> + val fields = row.jsonObject + DiarySchool( + id = fields.getValue("id").jsonPrimitive.longOrNull!!, + name = fields.getValue("name").jsonPrimitive.content, + address = fields["address"]?.takeUnless { it is JsonNull }?.jsonPrimitive?.content, + ) + } + assertEquals(body.toString(), wanted, outcome.getOrThrow()) + } + } + + // ---- plumbing ------------------------------------------------------------- + + private suspend fun signIn(script: NetSchoolScript): Result { + server.dispatcher = script + val flow = Vectors.flow + val target = netschoolTarget( + login = flow.getValue("login").jsonPrimitive.content, + schoolId = flow.getValue("school_id").jsonPrimitive.longOrNull!!, + ) + return runCatching { + NetSchoolSignIn(clientFor(server), clock) + .signIn(regionAt(server), target, flow.getValue("password").jsonPrimitive.content) + } + } + + private fun searchOf(script: NetSchoolScript): NetSchoolSchoolSearch { + server.dispatcher = script + val directory = FakeUpstreamDirectory(petersburg = null, regions = listOf(regionAt(server))) + return NetSchoolSchoolSearch( + client = { clientFor(server) }, + directory = { directory }, + ioDispatcher = kotlinx.coroutines.Dispatchers.Unconfined, + ) + } + + private fun resource(name: String): String = + javaClass.classLoader!!.getResourceAsStream(name)!!.bufferedReader(Charsets.UTF_8).use { it.readText() } + + private fun String.quoted(): String = JsonPrimitive(this).toString() +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearchTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearchTest.kt new file mode 100644 index 00000000..f025df3c --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearchTest.kt @@ -0,0 +1,121 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import mockwebserver3.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The phone's own school search, straight to the region's server: what it + * sends, what it refuses to send, and how its failures read. The row rule and + * the query cut are the shared vectors' (`DiaryProtocolVectorsTest`). + */ +class NetSchoolSchoolSearchTest { + + private lateinit var server: MockWebServer + private lateinit var script: NetSchoolScript + + @Before + fun setUp() { + server = MockWebServer() + script = NetSchoolScript() + server.dispatcher = script + server.start() + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `the query is cut at 60 code points, never inside a surrogate pair`() = runBlocking { + val query = "а" + "😀".repeat(70) + + search().search("zabaikalsky", query).getOrThrow() + + val sent = script.to(NetSchoolSchoolSearch.PATH).single().url.queryParameter("name")!! + assertEquals(60, sent.codePointCount(0, sent.length)) + assertTrue(sent.last().isLowSurrogate()) + } + + @Test + fun `no session header rides a search`() = runBlocking { + search().search("zabaikalsky", "лицей").getOrThrow() + + val request = script.to(NetSchoolSchoolSearch.PATH).single() + assertNull(request.headers["at"]) + assertNull(request.headers["Cookie"]) + assertNull(request.headers["Authorization"]) + assertEquals("XMLHttpRequest", request.headers["X-Requested-With"]) + } + + @Test + fun `a firewall page is the region refusing the phone, named by its host`() = runBlocking { + script.search = { rawAnswer(200, "text/html", "

Access denied

") } + + val failure = search().search("zabaikalsky", "лицей").exceptionOrNull() + + assertEquals(DiarySignInProblem.ProviderRefusesPhone(originOf(server).host), failure) + } + + @Test + fun `a region that answers 5xx is unavailable`() = runBlocking { + script.search = { rawAnswer(502, "text/html", "") } + + val failure = search().search("zabaikalsky", "лицей").exceptionOrNull() + + assertEquals(DiarySignInProblem.ProviderUnavailable(originOf(server).host), failure) + } + + @Test + fun `a query too short to mean anything sends nothing`() = runBlocking { + val rows = search().search("zabaikalsky", " ш ").getOrThrow() + + assertTrue(rows.isEmpty()) + assertEquals(0, server.requestCount) + } + + @Test + fun `a region outside the allow-list sends nothing`() = runBlocking { + val failure = search().search("volgograd", "лицей").exceptionOrNull() + + assertEquals(DiarySignInProblem.RegionNotServed, failure) + assertEquals(0, server.requestCount) + } + + /** There is no school to pick for a sign-in this app will never make. */ + @Test + fun `a Gosuslugi-only region sends nothing`() = runBlocking { + val directory = FakeUpstreamDirectory(null, listOf(regionAt(server, key = "tula", password = false))) + val failure = NetSchoolSchoolSearch({ clientFor(server) }, { directory }, Dispatchers.Unconfined) + .search("tula", "лицей").exceptionOrNull() + + assertTrue(failure is DiarySignInProblem.GosuslugiOnly) + assertEquals(0, server.requestCount) + } + + @Test + fun `at most fifty rows come back`() = runBlocking { + val rows = (1..80).joinToString(",", "[", "]") { """{"id":$it,"name":"Школа № $it"}""" } + script.search = { jsonAnswer(200, Json.parseToJsonElement(rows)) } + + val found = search().search("zabaikalsky", "школа").getOrThrow() + + assertEquals(DiarySchoolSearch.MAX_ROWS, found.size) + assertEquals(1L, found.first().id) + } + + private fun search() = NetSchoolSchoolSearch( + client = { clientFor(server) }, + directory = { FakeUpstreamDirectory(null, listOf(regionAt(server))) }, + ioDispatcher = Dispatchers.Unconfined, + ) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignInTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignInTest.kt new file mode 100644 index 00000000..9f16dd8e --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignInTest.kt @@ -0,0 +1,252 @@ +package com.lumenpearson.lessons.core.data.upstream + +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * «Сетевой город»'s sign-in on the phone, over a real socket: the order of the + * steps, what each one carries, and — above all — where the password and its + * hashes may and may not appear. The answers themselves are the shared + * vectors' (`DiaryProtocolVectorsTest`); this is the shape of the exchange. + */ +class NetSchoolSignInTest { + + private lateinit var server: MockWebServer + private val clock = MutableClock() + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `a sign-in walks logindata, getdata and login in that order and ends holding at and cookies`() = runBlocking { + val script = NetSchoolScript( + logindata = { + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json") + .addHeader("Set-Cookie", "NSSESSIONID=s1; Path=/").body("""{"cacheVer":"639"}""").build() + }, + logins = ArrayDeque( + listOf({ + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json") + .addHeader("Set-Cookie", "ESRNSec=e1; Path=/").body("""{"at":"bearer-1","timeOut":900000}""").build() + }), + ), + ) + server.dispatcher = script + + val session = signIn() + + assertEquals( + listOf(NetSchoolSignIn.LOGINDATA_PATH, NetSchoolSignIn.GETDATA_PATH, NetSchoolSignIn.LOGIN_PATH), + script.seen.map { it.url.encodedPath }, + ) + assertEquals("bearer-1", session.at) + assertEquals(mapOf("NSSESSIONID" to "s1", "ESRNSec" to "e1"), session.cookies) + assertEquals("639", session.ver) + assertEquals(900_000L, session.timeOut) + assertEquals("zabaikalsky", session.target.region) + assertEquals(42L, session.target.schoolId) + } + + @Test + fun `the password and its hashes never appear in a URL, and the password in no body`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + + signIn(password = "hunter2") + + val (pw, pw2) = NetSchoolPassword.hash("333", "hunter2")!! + for (request in script.seen) { + val url = request.url.toString() + assertFalse(url, "hunter2" in url || pw in url || pw2 in url) + assertFalse("hunter2" in request.body?.utf8().orEmpty()) + assertFalse(request.headers.toString().contains("hunter2")) + } + val form = script.to(NetSchoolSignIn.LOGIN_PATH).single().form() + assertEquals(pw, form["pw"]) + assertEquals(pw2, form["pw2"]) + assertEquals("42", form["scid"]) + assertEquals("parent", form["un"]) + } + + @Test + fun `getdata carries the cookie logindata set and no content type`() = runBlocking { + val script = NetSchoolScript( + logindata = { + MockResponse.Builder().code(200).addHeader("Content-Type", "application/json") + .addHeader("Set-Cookie", "NSSESSIONID=s1; Path=/").body("""{"schoolLogin":true}""").build() + }, + ) + server.dispatcher = script + + signIn() + + val getdata = script.to(NetSchoolSignIn.GETDATA_PATH).single() + assertEquals("POST", getdata.method) + assertEquals("NSSESSIONID=s1", getdata.headers["Cookie"]) + assertEquals(0L, getdata.bodySize) + assertNull(getdata.headers["Content-Type"]) + assertEquals("XMLHttpRequest", getdata.headers["X-Requested-With"]) + // logindata is asked before there is anything to carry. + assertNull(script.to(NetSchoolSignIn.LOGINDATA_PATH).single().headers["Cookie"]) + } + + @Test + fun `a Gosuslugi-only answer stops before getdata`() = runBlocking { + val script = NetSchoolScript(logindata = { jsonAnswer(200, Json.parseToJsonElement("""{"schoolLogin":false}""")) }) + server.dispatcher = script + + val failure = runCatching { signIn() }.exceptionOrNull() + + assertTrue(failure is UpstreamFailure.SignInUnsupported) + assertTrue(script.to(NetSchoolSignIn.GETDATA_PATH).isEmpty()) + } + + @Test + fun `a catalog row without password sends nothing`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + + val failure = runCatching { + NetSchoolSignIn(clientFor(server), clock).signIn(regionAt(server, password = false), netschoolTarget(), "x") + }.exceptionOrNull() + + assertTrue(failure is UpstreamFailure.SignInUnsupported) + assertEquals(0, server.requestCount) + } + + @Test + fun `choose-session-role retries once with a fresh salt and the parent role`() = runBlocking { + var salts = 0 + val script = NetSchoolScript( + getdata = { + salts++ + jsonAnswer(200, Json.parseToJsonElement("""{"salt":"${330 + salts}","lt":"$salts","ver":"2"}""")) + }, + logins = ArrayDeque(listOf({ jsonAnswer(200, Vectors.flow.getValue("role_question")) })), + ) + server.dispatcher = script + + val session = signIn() + + val (first, second) = script.to(NetSchoolSignIn.LOGIN_PATH).map { it.form() } + assertEquals("1", first["lt"]) + assertEquals("2", second["lt"]) + assertEquals(NetSchoolPassword.hash("332", "hunter2")!!.second, second["pw2"]) + assertEquals("12", second["rolegroup"]) + assertEquals("after-role", session.at) + } + + /** A second «which role» after one was chosen is a refusal, not a loop. */ + @Test + fun `a second role question is not retried`() = runBlocking { + val question = { jsonAnswer(200, Vectors.flow.getValue("role_question")) } + val script = NetSchoolScript(logins = ArrayDeque(listOf(question, question, question))) + server.dispatcher = script + + val failure = runCatching { signIn() }.exceptionOrNull() + + assertTrue(failure is UpstreamFailure.BadCredentials) + assertEquals(2, script.to(NetSchoolSignIn.LOGIN_PATH).size) + } + + @Test + fun `403 and a firewall page are address refused`() = runBlocking { + for (answer in listOf( + { rawAnswer(403, "application/json", "{}") }, + { rawAnswer(200, "text/html", "

Доступ к сайту ограничен

") }, + )) { + server.dispatcher = NetSchoolScript(logindata = answer) + assertTrue(runCatching { signIn() }.exceptionOrNull() is UpstreamFailure.AddressRefused) + } + } + + /** + * A redirect to the region's login page, or anywhere else, is read as the + * answer it is — not JSON — and never followed to where it points. + */ + @Test + fun `a redirect is not followed`() = runBlocking { + val script = NetSchoolScript( + logindata = { + MockResponse.Builder().code(302).addHeader("Location", "https://elsewhere.example/").build() + }, + ) + server.dispatcher = script + + val failure = runCatching { signIn() }.exceptionOrNull() + + assertTrue("got $failure", failure is UpstreamFailure.Unexpected) + assertEquals(1, script.seen.size) + } + + @Test + fun `the login is trimmed before it is sent`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + + val session = NetSchoolSignIn(clientFor(server), clock) + .signIn(regionAt(server), netschoolTarget(login = " parent "), "hunter2") + + assertEquals("parent", script.to(NetSchoolSignIn.LOGIN_PATH).single().form()["un"]) + assertEquals("parent", session.target.login) + } + + /** + * For a session our server refused: goodbye upstream, with `at` in a + * header and the body — never in the URL, which somebody logs. + */ + @Test + fun `logout posts at and ver in the body and nothing in the URL`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + val session = signIn() + + NetSchoolSignIn(clientFor(server), clock).logout(session, regionAt(server)) + + val logout = script.to(NetSchoolSignIn.LOGOUT_PATH).single() + assertEquals(mapOf("at" to "after-role", "ver" to "639"), logout.form()) + assertEquals("after-role", logout.headers["at"]) + assertFalse("after-role" in logout.url.toString()) + } + + @Test + fun `a logout that fails is swallowed`() = runBlocking { + val script = NetSchoolScript() + server.dispatcher = script + val session = signIn() + server.close() + + // Nothing thrown: we are leaving anyway. + NetSchoolSignIn(clientFor(server), clock).logout(session, regionAt(server)) + } + + @Test + fun `an upstream session never prints its secret`() = runBlocking { + server.dispatcher = NetSchoolScript() + + val session = signIn() + + assertFalse("after-role" in session.toString()) + assertFalse(session.toString().contains("NSSESSIONID")) + } + + private suspend fun signIn(password: String = "hunter2"): UpstreamSession.NetSchool = + NetSchoolSignIn(clientFor(server), clock).signIn(regionAt(server), netschoolTarget(), password) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignInTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignInTest.kt new file mode 100644 index 00000000..aef95264 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignInTest.kt @@ -0,0 +1,117 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Petersburg's sign-in on the phone, over a real socket. The answers are the + * shared vectors' (`DiaryProtocolVectorsTest`); this is what the request + * carries, and the two failures a vector cannot express. + */ +class PetersburgSignInTest { + + private lateinit var server: MockWebServer + private val clock = MutableClock() + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + @Test + fun `the login body carries exactly the five fields, activation_code as an explicit null`() = runBlocking { + server.enqueue(rawAnswer(200, "application/json", """{"data":{"token":"a.b.c"}}""")) + + signIn(login = " parent@example.com ", password = " spaced password ") + + val request = server.takeRequest() + assertEquals("POST", request.method) + val body = Json.parseToJsonElement(request.body!!.utf8()).jsonObject + assertEquals(setOf("type", "login", "activation_code", "password", "_isEmpty"), body.keys) + assertEquals(JsonNull, body["activation_code"]) + assertEquals("email", body.getValue("type").jsonPrimitive.content) + assertEquals("false", body.getValue("_isEmpty").jsonPrimitive.content) + // The login trimmed, the password exactly as typed. + assertEquals("parent@example.com", body.getValue("login").jsonPrimitive.content) + assertEquals(" spaced password ", body.getValue("password").jsonPrimitive.content) + assertTrue(request.headers["Content-Type"]!!.startsWith("application/json")) + } + + @Test + fun `a browser user agent is sent and Authorization and Cookie never are`() = runBlocking { + server.enqueue(rawAnswer(200, "application/json", """{"data":{"token":"a.b.c"}}""")) + + signIn() + + val request = server.takeRequest() + assertEquals(UpstreamHttp.USER_AGENT, request.headers["User-Agent"]) + assertEquals("application/json", request.headers["Accept"]) + assertNull(request.headers["Authorization"]) + assertNull(request.headers["Cookie"]) + } + + @Test + fun `the password never appears in the URL`() = runBlocking { + server.enqueue(rawAnswer(200, "application/json", """{"data":{"token":"a.b.c"}}""")) + + signIn(password = "hunter2") + + assertFalse("hunter2" in server.takeRequest().url.toString()) + } + + @Test + fun `a timeout is unavailable and says so`() = runBlocking { + server.enqueue(MockResponse.Builder().code(200).headersDelay(2, TimeUnit.SECONDS).build()) + val impatient = clientFor(server).newBuilder().readTimeout(200, TimeUnit.MILLISECONDS).build() + + val failure = runCatching { + PetersburgSignIn(impatient, originOf(server), clock).signIn(DiaryTarget.petersburg("parent"), "x") + }.exceptionOrNull() + + assertTrue(failure is UpstreamFailure.Unavailable && failure.timedOut) + } + + /** Nobody is signed in yet, so a page of HTML is «unreadable», never «sign in again» — which would loop. */ + @Test + fun `a 200 of HTML is unreadable, not a re-auth loop`() = runBlocking { + server.enqueue(rawAnswer(200, "text/html", "
captcha
")) + + val failure = runCatching { signIn() }.exceptionOrNull() + + assertTrue(failure is UpstreamFailure.Unexpected) + } + + @Test + fun `the session is the cookie's and the target's login is trimmed`() = runBlocking { + server.enqueue(rawAnswer(200, "application/json", """{"data":{"token":"body"}}""", listOf("X-JWT-Token=cookie.jwt.value; Path=/"))) + + val session = signIn(login = " parent@example.com ") + + assertEquals("cookie.jwt.value", session.token) + assertEquals("parent@example.com", session.target.login) + assertFalse("cookie.jwt.value" in session.toString()) + } + + private suspend fun signIn(login: String = "parent@example.com", password: String = "secret") = + PetersburgSignIn(clientFor(server), originOf(server), clock).signIn(DiaryTarget.petersburg(login), password) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectoryTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectoryTest.kt new file mode 100644 index 00000000..92840f0b --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamDirectoryTest.kt @@ -0,0 +1,127 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.catalog.CatalogNetSchool +import com.lumenpearson.lessons.core.data.catalog.CatalogPlatform +import com.lumenpearson.lessons.core.data.catalog.CatalogRegion +import com.lumenpearson.lessons.core.data.catalog.CatalogSystem +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The allow-list, as the phone builds it from the bundled catalog — the only + * place a host the phone sends a password to can come from. + */ +class UpstreamDirectoryTest { + + private val bundled: RegionCatalog by lazy { + RegionCatalog.parse( + javaClass.classLoader!!.getResourceAsStream(RegionCatalog.ASSET)!! + .bufferedReader(Charsets.UTF_8).use { it.readText() }, + ) + } + + @Test + fun `the directory refuses an http, path-carrying or credentialed origin`() { + for (refused in listOf( + "http://sgo.example.ru", + "https://sgo.example.ru/webapi", + "https://sgo.example.ru/", + "https://sgo.example.ru?x=1", + "https://user:pass@sgo.example.ru", + "https://sgo.example.ru#top", + "ftp://sgo.example.ru", + "not a url", + )) { + assertNull(refused, CatalogUpstreamDirectory.originOrNull(refused)) + } + assertNotNull(CatalogUpstreamDirectory.originOrNull("https://sgo.example.ru")) + } + + @Test + fun `a catalog row with an unusable origin never reaches the allow-list`() { + val catalog = RegionCatalog( + regions = listOf( + region("good", "https://good.example.ru"), + region("plain", "http://plain.example.ru"), + region("pathy", "https://pathy.example.ru/webapi"), + ), + ) + + val directory = CatalogUpstreamDirectory(catalog) + + assertNotNull(directory.netschool("good")) + assertNull(directory.netschool("plain")) + assertNull(directory.netschool("pathy")) + assertEquals(setOf(UpstreamOrigin("https", "good.example.ru", 443)), directory.allowedOrigins()) + } + + /** + * The bundled file, read the way the app reads it: every «Сетевой город» + * region the server's allow-list has, on `https`, and nothing else. + * `regions.py` has nineteen rows, three of them Госуслуги-only. + */ + @Test + fun `the bundled catalog yields the server's allow-list and only that`() { + val directory = CatalogUpstreamDirectory(bundled) + val netschool = bundled.regions.flatMap { it.systems }.mapNotNull { it.netschool } + + assertEquals(19, netschool.map { it.region }.toSet().size) + for (row in netschool) { + val region = directory.netschool(row.region) + assertNotNull(row.region, region) + assertEquals(row.region, "https", region!!.origin.scheme) + assertEquals(row.region, row.password, region.password) + assertEquals(row.region, row.zone, region.zone) + } + assertEquals(setOf("altai-krai", "primorye", "tula"), netschool.filterNot { it.password }.map { it.region }.toSet()) + // Nineteen regions and Petersburg, and no other origin at all. + assertEquals(20, directory.allowedOrigins().size) + assertTrue(directory.allowedOrigins().all { it.scheme == "https" }) + } + + @Test + fun `the Sakhalin origin keeps its port`() { + val sakhalin = CatalogUpstreamDirectory(bundled).netschool("sakhalin")!! + assertEquals(11111, sakhalin.origin.port) + assertTrue(UpstreamOrigin("https", "netcity.admsakhalin.ru", 11111) in CatalogUpstreamDirectory(bundled).allowedOrigins()) + } + + /** + * K19: a «Сетевой город» region that takes Госуслуги only hands off to its + * own site, which is what the catalog says — not to a Госуслуги page the + * app guessed. + */ + @Test + fun `a Gosuslugi-only region hands off to the catalog's own address`() { + val directory = CatalogUpstreamDirectory(bundled) + for (key in listOf("altai-krai", "primorye", "tula")) { + val region = directory.netschool(key)!! + assertFalse(key, region.password) + assertEquals(key, region.origin.toString().trimEnd('/'), region.handoffUrl?.trimEnd('/')) + } + } + + @Test + fun `Petersburg comes from the catalog's platform row`() { + assertEquals("dnevnik2.petersburgedu.ru", CatalogUpstreamDirectory(bundled).petersburg?.host) + val none = CatalogUpstreamDirectory(RegionCatalog(platforms = mapOf("x" to CatalogPlatform(provider = "netschool")))) + assertNull(none.petersburg) + } + + private fun region(key: String, origin: String) = CatalogRegion( + key = key, + zone = "Europe/Moscow", + systems = listOf( + CatalogSystem( + platform = "netschool", + action = "signin", + netschool = CatalogNetSchool(region = key, origin = origin, password = true, zone = "Europe/Moscow"), + ), + ), + ) +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt new file mode 100644 index 00000000..94d57dca --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt @@ -0,0 +1,213 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.network.AuthInterceptor +import com.lumenpearson.lessons.core.data.network.BaseUrlInterceptor +import com.lumenpearson.lessons.core.data.network.DiaryAuthInterceptor +import java.io.IOException +import java.net.UnknownHostException +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLHandshakeException +import kotlinx.coroutines.runBlocking +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import okhttp3.CookieJar +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.Request +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test + +/** + * The client the phone talks to the diaries with, and the rules that make it + * safe to hand a password to: one allow-list, no redirects, no cookie jar, no + * bearer of ours, and every transport failure turned into what it means. + */ +class UpstreamHttpTest { + + private lateinit var server: MockWebServer + + @Before + fun setUp() { + server = MockWebServer() + server.start() + } + + @After + fun tearDown() { + server.close() + } + + /** + * First, because every other test in this package stands on it: OkHttp's + * Android build asks `android.util.Log` which platform it is on, and a JVM + * unit test has only the stub. If this fails, nothing else here means + * anything. + */ + @Test + fun `a real call reaches MockWebServer from a JVM unit test`() = runBlocking { + server.enqueue(MockResponse.Builder().code(200).body("hello").build()) + + val answer = UpstreamHttp.fetch(clientFor(server), Request.Builder().url(server.url("/ping")).build()) + + assertEquals(200, answer.code) + assertEquals("hello", answer.body) + assertEquals("/ping", server.takeRequest().url.encodedPath) + } + + @Test + fun `an origin outside the allow-list is refused before a socket opens`() = runBlocking { + val elsewhere = UpstreamHttp.client { setOf(UpstreamOrigin("https", "region.zabedu.ru", 443)) } + + try { + UpstreamHttp.fetch(elsewhere, Request.Builder().url(server.url("/webapi/logindata")).build()) + fail("a host outside the allow-list was reached") + } catch (refused: UpstreamNotAllowed) { + // expected + } + assertEquals(0, server.requestCount) + } + + /** The port is part of the origin: the same host on another port is another server. */ + @Test + fun `the same host on another port is not allowed`() = runBlocking { + val url = server.url("/") + val otherPort = UpstreamHttp.client { setOf(UpstreamOrigin(url.scheme, url.host, url.port + 1)) } + + val failure = runCatching { + UpstreamHttp.fetch(otherPort, Request.Builder().url(server.url("/")).build()) + }.exceptionOrNull() + + assertTrue(failure is UpstreamNotAllowed) + assertEquals(0, server.requestCount) + } + + @Test + fun `the provider client carries none of the school server's interceptors`() { + val client = clientFor(server) + + val kinds = client.interceptors.map { it::class } + assertEquals(listOf(OriginGuard::class, BrowserHeaders::class), kinds) + for (ours in listOf(BaseUrlInterceptor::class, AuthInterceptor::class, DiaryAuthInterceptor::class)) { + assertFalse(ours in kinds) + } + assertTrue(client.networkInterceptors.isEmpty()) + assertFalse(client.followRedirects) + assertFalse(client.followSslRedirects) + assertFalse(client.retryOnConnectionFailure) + assertSame(CookieJar.NO_COOKIES, client.cookieJar) + assertNull(client.cache) + } + + @Test + fun `a browser user agent is sent and an Authorization header is refused`() = runBlocking { + server.enqueue(MockResponse.Builder().code(200).build()) + UpstreamHttp.fetch(clientFor(server), Request.Builder().url(server.url("/")).build()) + assertEquals(UpstreamHttp.USER_AGENT, server.takeRequest().headers["User-Agent"]) + + val signed = Request.Builder().url(server.url("/")).header("Authorization", "Bearer ours").build() + val failure = runCatching { UpstreamHttp.fetch(clientFor(server), signed) }.exceptionOrNull() + assertTrue(failure is UpstreamNotAllowed) + assertEquals(1, server.requestCount) + } + + /** + * Two families on one phone, or one family twice: the first answer's + * cookie must not ride out on the second request, which is how two + * sessions meet. + */ + @Test + fun `two sign-ins never share a cookie`() = runBlocking { + val client = clientFor(server) + server.enqueue(MockResponse.Builder().code(200).addHeader("Set-Cookie", "NSSESSIONID=first; Path=/").build()) + server.enqueue(MockResponse.Builder().code(200).build()) + + UpstreamHttp.fetch(client, Request.Builder().url(server.url("/webapi/logindata")).build()) + UpstreamHttp.fetch(client, Request.Builder().url(server.url("/webapi/logindata")).build()) + + server.takeRequest() + assertNull(server.takeRequest().headers["Cookie"]) + } + + /** A redirect is the one way around an allow-list, so it is read, never followed. */ + @Test + fun `a redirect is not followed`() = runBlocking { + server.enqueue( + MockResponse.Builder().code(302).addHeader("Location", "https://elsewhere.example/steal").build(), + ) + + val answer = UpstreamHttp.fetch(clientFor(server), Request.Builder().url(server.url("/")).build()) + + assertEquals(302, answer.code) + assertEquals(1, server.requestCount) + } + + @Test + fun `a TLS failure is untrusted, never offline`() = runBlocking { + val client = clientFor(server).newBuilder() + .addInterceptor { throw SSLHandshakeException("PKIX path building failed") } + .build() + + val failure = runCatching { + UpstreamHttp.fetch(client, Request.Builder().url(server.url("/")).build()) + }.exceptionOrNull() + + assertTrue("got $failure", failure is UpstreamFailure.Untrusted) + } + + @Test + fun `a timeout is unavailable and says it timed out`() = runBlocking { + server.enqueue(MockResponse.Builder().code(200).headersDelay(2, TimeUnit.SECONDS).build()) + val impatient = clientFor(server).newBuilder().readTimeout(200, TimeUnit.MILLISECONDS).build() + + val failure = runCatching { + UpstreamHttp.fetch(impatient, Request.Builder().url(server.url("/")).build()) + }.exceptionOrNull() + + assertTrue("got $failure", failure is UpstreamFailure.Unavailable) + assertTrue((failure as UpstreamFailure.Unavailable).timedOut) + } + + /** + * On a phone a refused connection is its own network far more often than + * a regional firewall — see `NetSchoolSignIn` — so it is «try again», not + * «this diary refuses you». + */ + @Test + fun `a refused connection on the phone is unavailable, not address refused`() = runBlocking { + val url = server.url("/webapi/logindata") + val client = clientFor(server) + server.close() + + val failure = runCatching { UpstreamHttp.fetch(client, Request.Builder().url(url).build()) }.exceptionOrNull() + + assertTrue("got $failure", failure is UpstreamFailure.Unavailable) + assertFalse((failure as UpstreamFailure.Unavailable).timedOut) + } + + @Test + fun `a name that does not resolve is offline`() { + val failure = UpstreamHttp.classify(IOException("lookup", UnknownHostException("sgo.example"))) + assertTrue(failure is UpstreamFailure.Offline) + } + + @Test + fun `a session cookie is read from the last live one of its name`() { + val url = "https://region.zabedu.ru/webapi/login".toHttpUrl() + val headers = okhttp3.Headers.headersOf( + "Set-Cookie", "NSSESSIONID=old; Path=/", + "Set-Cookie", "ESRNSec=sec; Path=/", + "Set-Cookie", "NSSESSIONID=new; Path=/webapi", + "Set-Cookie", "NSSESSIONID=; Max-Age=0; Path=/", + ) + + assertEquals("new", UpstreamHttp.sessionCookie(url, headers, "NSSESSIONID", 0)) + assertEquals("sec", UpstreamHttp.sessionCookie(url, headers, "ESRNSec", 0)) + assertNull(UpstreamHttp.sessionCookie(url, headers, "X-JWT-Token", 0)) + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamTestSupport.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamTestSupport.kt new file mode 100644 index 00000000..9d0ab062 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamTestSupport.kt @@ -0,0 +1,165 @@ +package com.lumenpearson.lessons.core.data.upstream + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.net.URLDecoder +import java.time.Clock +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import mockwebserver3.Dispatcher +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okhttp3.HttpUrl +import okhttp3.OkHttpClient + +/** + * `server/tests/vectors/diary_protocol.json`, read in place from the server's + * tests — `core/data/build.gradle.kts` puts that folder on the test classpath — + * so there is one file of known answers and not two that agree until somebody + * edits one. + */ +internal object Vectors { + val root: JsonObject by lazy { + val stream = Vectors::class.java.classLoader!!.getResourceAsStream("diary_protocol.json") + ?: error("diary_protocol.json is not on the test classpath; see core/data/build.gradle.kts") + Json.parseToJsonElement(stream.bufferedReader(Charsets.UTF_8).use { it.readText() }).jsonObject + } + + val petersburg: JsonObject get() = root.getValue("petersburg").jsonObject + val netschool: JsonObject get() = root.getValue("netschool").jsonObject + val flow: JsonObject get() = netschool.getValue("flow").jsonObject + + fun cases(parent: JsonObject, key: String): List = + parent.getValue(key).jsonArray.map { it.jsonObject } +} + +/** The vectors' name for a failure, most specific first — as the server's `_kind`. */ +internal fun kindOf(failure: Throwable?): String = when (failure) { + null -> "ok" + is UpstreamFailure.AddressRefused -> "address_refused" + is UpstreamFailure.Unavailable -> "unavailable" + is UpstreamFailure.BadCredentials -> "bad_credentials" + is UpstreamFailure.SignInUnsupported -> "sign_in_unsupported" + is UpstreamFailure.Unexpected -> "unexpected" + else -> failure::class.simpleName ?: "?" +} + +/** Shaped like the `X-JWT-Token` Petersburg issues, which is what the server accepts. */ +internal const val PETERSBURG_JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjF9.c2lnbmF0dXJl" + +/** The `NSSESSIONID` [NetSchoolScript]'s `logindata` sets unless a test says otherwise. */ +internal const val SCRIPT_SESSION_COOKIE = "nss-cookie-value" + +/** A clock a test moves by hand. */ +internal class MutableClock(var now: Instant = Instant.parse("2026-09-25T10:00:00Z")) : Clock() { + override fun getZone(): ZoneId = ZoneOffset.UTC + override fun withZone(zone: ZoneId?): Clock = this + override fun instant(): Instant = now +} + +internal fun jsonAnswer(status: Int, body: JsonElement, vararg headers: Pair): MockResponse = + MockResponse.Builder() + .code(status) + .addHeader("Content-Type", "application/json") + .apply { headers.forEach { (name, value) -> addHeader(name, value) } } + .body(body.toString()) + .build() + +internal fun rawAnswer(status: Int, contentType: String, body: String, cookies: List = emptyList()): MockResponse = + MockResponse.Builder() + .code(status) + .addHeader("Content-Type", contentType) + .apply { cookies.forEach { addHeader("Set-Cookie", it) } } + .body(body) + .build() + +/** The provider client, allowed to talk to [server] and nothing else. */ +internal fun clientFor(server: MockWebServer): OkHttpClient = + UpstreamHttp.client { setOf(UpstreamOrigin.of(server.url("/"))) } + +/** The origin of [server] as the catalog would give it: scheme, host and port. */ +internal fun originOf(server: MockWebServer): HttpUrl = server.url("/") + +internal fun regionAt(server: MockWebServer, key: String = "zabaikalsky", password: Boolean = true) = + NetSchoolRegion( + key = key, + origin = originOf(server), + password = password, + zone = "Asia/Chita", + handoffUrl = "https://region.zabedu.ru", + ) + +internal fun netschoolTarget(login: String = "parent", schoolId: Long = 42, region: String = "zabaikalsky") = + DiaryTarget.netschool(region = region, schoolId = schoolId, schoolName = null, login = login, zone = "Asia/Chita") + +/** A directory of exactly the regions and Petersburg origin a test hands it. */ +internal class FakeUpstreamDirectory( + override val petersburg: HttpUrl?, + private val regions: List = emptyList(), +) : UpstreamDirectory { + override fun netschool(regionKey: String?): NetSchoolRegion? = regions.firstOrNull { it.key == regionKey } + + override fun allowedOrigins(): Set = buildSet { + petersburg?.let { add(UpstreamOrigin.of(it)) } + regions.forEach { add(UpstreamOrigin.of(it.origin)) } + } +} + +/** + * «Сетевой город» as a script: `logindata`, `getdata` and `login` answer what + * the test says, falling back to the vectors' own flow, and every request is + * recorded in the order it arrived. + */ +internal class NetSchoolScript( + var logindata: () -> MockResponse = { + jsonAnswer(200, Vectors.flow.getValue("logindata"), "Set-Cookie" to "NSSESSIONID=$SCRIPT_SESSION_COOKIE; Path=/") + }, + var getdata: () -> MockResponse = { jsonAnswer(200, Vectors.flow.getValue("getdata")) }, + val logins: ArrayDeque<() -> MockResponse> = ArrayDeque(), + var search: () -> MockResponse = { jsonAnswer(200, JsonArray(emptyList())) }, + var petersburg: () -> MockResponse = { + rawAnswer(200, "application/json", """{"data":{"token":"$PETERSBURG_JWT"}}""") + }, +) : Dispatcher() { + + val seen: MutableList = java.util.Collections.synchronizedList(mutableListOf()) + + override fun dispatch(request: RecordedRequest): MockResponse { + seen += request + return when (request.url.encodedPath) { + NetSchoolSignIn.LOGINDATA_PATH -> logindata() + NetSchoolSignIn.GETDATA_PATH -> getdata() + NetSchoolSignIn.LOGIN_PATH -> + logins.removeFirstOrNull()?.invoke() + ?: jsonAnswer(200, Json.parseToJsonElement("""{"at":"after-role"}""")) + NetSchoolSignIn.LOGOUT_PATH -> jsonAnswer(200, JsonObject(emptyMap())) + NetSchoolSchoolSearch.PATH -> search() + PetersburgSignIn.LOGIN_PATH -> petersburg() + else -> MockResponse.Builder().code(404).build() + } + } + + fun to(path: String): List = seen.filter { it.url.encodedPath == path } +} + +/** + * A form body as the fields it carries, in order, decoded — never as bytes: + * OkHttp and httpx write the same form differently (`+` against `%20`, `~`). + */ +internal fun RecordedRequest.form(): LinkedHashMap { + val text = body?.utf8().orEmpty() + val out = LinkedHashMap() + if (text.isEmpty()) return out + for (pair in text.split('&')) { + val (name, value) = pair.split('=', limit = 2).let { it[0] to it.getOrElse(1) { "" } } + out[URLDecoder.decode(name, Charsets.UTF_8)] = URLDecoder.decode(value, Charsets.UTF_8) + } + return out +} diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index c91d4eee..b3181f03 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -8,6 +8,10 @@ # Room, Navigation, DataStore, Retrofit, OkHttp, kotlinx-serialization # -> android/nowinandroid, cross-checked against Maven Central. # +# mockwebserver3 -> OkHttp's own 5.5.0 release, which publishes it beside +# okhttp at the same version; it rides `version.ref = "okhttp"` so the +# two can never be bumped apart. +# # The first CI run failed on invented versions (room 2.9.2, navigation 2.9.6, # okhttp 5.2.0, kotlinx-serialization-json 1.9.1) that do not exist in any # repository. Verify a version against its repository before adding it here. @@ -70,6 +74,7 @@ retrofit-core = { group = "com.squareup.retrofit2", name = "retrofit", version.r retrofit-kotlinx-serialization = { group = "com.squareup.retrofit2", name = "converter-kotlinx-serialization", version.ref = "retrofit" } okhttp-core = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" } +okhttp-mockwebserver3 = { group = "com.squareup.okhttp3", name = "mockwebserver3", version.ref = "okhttp" } kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" } kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" } kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } From ce9c749ffdf26303e2d632e28a19cbd60727afd4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 16:28:31 +0000 Subject: [PATCH 16/30] Let a reader open the terms and the privacy policy from the app, online or not MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first screen is to say «Продолжая, вы принимаете Условия использования и Политику конфиденциальности», and a sentence like that is only honest if both documents open wherever the phone is. This adds the pieces for it; placing the line on the onboarding screen is the onboarding part's. - LESSONS_LEGAL_BASE_URL / lessons.legal.baseUrl becomes BuildConfig.LEGAL_BASE_URL. The build refuses a value that is not https, carries a query or fragment, or would break the generated Java string, rather than keeping it: it is the first link of every install. With nothing set it defaults to docs/legal on the repository's default branch (blob/HEAD), so a fresh clone links a real, current document. apk.yml resolves the folder of whichever repository it runs in, overridable by a repository variable, checks it before compiling, passes it to the build and prints it in the summary. The property and the step land together, as BuildPropertyReachTest requires. - docs/legal/ is mounted as an asset folder of :app, so the APK carries the one copy that is published. A small reader in :core:data (core/data/.../legal) opens it with the guide's own parser and reads legal.json for the edition and date; the "ru, otherwise en" rule is lifted out of DocsRepositoryImpl into docsLanguage() so the guide and the policy cannot pick different languages. - ui/legal: LegalAcceptanceLine (always drawn, small, under the button, both names links) and LegalOpener, which opens the current edition in the browser when there is an address and a validated network and a browser starts, and otherwise the bundled copy in a sheet that names its edition. The links are LinkAnnotation.Clickable so every tap can fall back; the sentence is one template with placeholders, because aapt2 trims the spaces at a string's edges. The sheet draws the sections through the guide's block renderer, moved unchanged from DocsScreen.kt into DocsBlocks.kt so the two texts cannot be drawn two ways. - «О приложении» gains two rows for the documents through the same opener. - #155: the design credit was three strings and aapt2 trimmed the space before the link, so the card read «по мотивамEssentials» / "afterEssentials". It is one template now, and StringEdgeSpaceTest refuses any string with a bare space at its edge in any module or language. - #156: CrashReporter writes to getExternalFilesDir("crash_reports") (or filesDir/crash_reports) and neither backup rule file excluded it, while the first run says a report stays on the phone. Both locations are now excluded from the pre-12 backup, the cloud backup and a device transfer, and BackupRulesTest reads both XML files and the reporter's folder name. The privacy policy's paragraph about the phone said crash reports may reach the backup; it now says they are excluded. legal.json stays at edition 1: nothing has been published. Tests: LegalDocumentsTest and LegalLinksTest in :core:data (the shipped texts' parity, links, markers, manifest, and no asset-name collision across docs/app, docs/legal and the region catalog); LegalAcceptanceLineTest, LegalDocumentSheetTest (including that the APK's assets really carry all four files), LegalBuildPropertyTest, BackupRulesTest, StringEdgeSpaceTest and two AboutCardTest cases in :app. Not covered: nothing here has run on a device — not the backup exclusion (#156 needs a phone and bmgr), not the browser handoff or its fallback, not TalkBack on the inline links, not the sheet with a long document. The line is not yet on the onboarding screen. docs/build.md, README and the CI path filter for docs/legal are the docs part's; the build's error message already points at docs/build.md. The texts were never reviewed by a lawyer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .github/workflows/apk.yml | 60 +++++ android/app/build.gradle.kts | 56 ++++ .../lessons/ui/docs/DocsBlocks.kt | 198 ++++++++++++++ .../lessons/ui/docs/DocsScreen.kt | 167 ------------ .../lessons/ui/legal/LegalAcceptanceLine.kt | 72 +++++ .../lessons/ui/legal/LegalDocumentSheet.kt | 174 ++++++++++++ .../lessons/ui/legal/LegalOpener.kt | 116 ++++++++ .../lessons/ui/legal/LinkedSentence.kt | 83 ++++++ .../lessons/ui/settings/AboutCard.kt | 113 +++++--- .../lessons/ui/translate/TranslationXml.kt | 3 +- .../app/src/main/res/values-en/strings.xml | 5 +- .../src/main/res/values-en/strings_legal.xml | 19 ++ android/app/src/main/res/values/strings.xml | 5 +- .../app/src/main/res/values/strings_legal.xml | 31 +++ android/app/src/main/res/xml/backup_rules.xml | 11 +- .../main/res/xml/data_extraction_rules.xml | 9 +- .../lumenpearson/lessons/BackupRulesTest.kt | 115 ++++++++ .../lessons/LegalBuildPropertyTest.kt | 97 +++++++ .../lessons/StringEdgeSpaceTest.kt | 61 +++++ .../ui/legal/LegalAcceptanceLineTest.kt | 125 +++++++++ .../ui/legal/LegalDocumentSheetTest.kt | 154 +++++++++++ .../lessons/ui/settings/AboutCardTest.kt | 19 ++ .../lessons/core/data/docs/DocsLanguage.kt | 13 + .../core/data/docs/DocsRepositoryImpl.kt | 8 +- .../lessons/core/data/legal/LegalDocuments.kt | 153 +++++++++++ .../core/data/legal/LegalDocumentsTest.kt | 254 ++++++++++++++++++ .../lessons/core/data/legal/LegalLinksTest.kt | 105 ++++++++ docs/legal/privacy.en.md | 4 +- docs/legal/privacy.ru.md | 4 +- 29 files changed, 2014 insertions(+), 220 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsBlocks.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLine.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LinkedSentence.kt create mode 100644 android/app/src/main/res/values-en/strings_legal.xml create mode 100644 android/app/src/main/res/values/strings_legal.xml create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/StringEdgeSpaceTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLineTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheetTest.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsLanguage.kt create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocuments.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocumentsTest.kt create mode 100644 android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalLinksTest.kt diff --git a/.github/workflows/apk.yml b/.github/workflows/apk.yml index f7a32eab..b6ea4c4f 100644 --- a/.github/workflows/apk.yml +++ b/.github/workflows/apk.yml @@ -8,6 +8,10 @@ # Signing: if the four keystore secrets are set the release APK is signed with # your key. If they are not, it is signed with the debug key so it still # installs; the job summary says which happened. See docs/build.md. +# +# Legal links: the APK links the terms and the privacy policy in docs/legal/ of +# the repository this runs in, unless the LESSONS_LEGAL_BASE_URL repository +# variable says otherwise; the summary prints which. name: APK on: @@ -129,6 +133,49 @@ jobs: # for a wire nobody can see from outside the step. echo "built_at=$(date -u +'%Y-%m-%dT%H:%MZ')" >> "$GITHUB_OUTPUT" + # Where the first screen's two links go: docs/legal/ of *this* repository, + # so a fork's APK links the fork's documents with nothing configured. + # `HEAD` when the payload carries no default branch: GitHub resolves + # blob/HEAD/ to the default branch, so the fallback means the same thing - + # unlike github.ref_name (a tag freezes the policy at that tag, a deleted + # branch 404s on every install for the rest of its life). A repository + # *variable*, not a secret, overrides it: the value is public, and a + # secret would be masked in the summary below. Checked here, in seconds, + # as well as by build.gradle.kts, so a bad value fails before the compile + # rather than eight minutes into it; the whitespace check also stops a + # newline in the variable from writing extra step outputs. + - name: Resolve legal documents + id: legal + env: + OVERRIDE: ${{ vars.LESSONS_LEGAL_BASE_URL }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + PRIVATE_REPO: ${{ github.event.repository.private }} + GH_SERVER: ${{ github.server_url }} + run: | + if [ -n "$OVERRIDE" ]; then + URL="${OVERRIDE%/}" + SOURCE="repository variable" + else + URL="$GH_SERVER/$GITHUB_REPOSITORY/blob/${DEFAULT_BRANCH:-HEAD}/docs/legal" + SOURCE="docs/legal of this repository" + if [ "$PRIVATE_REPO" = "true" ]; then + echo "::warning::This repository is private, so the derived address of docs/legal opens for nobody outside it. Set the LESSONS_LEGAL_BASE_URL repository variable; see docs/build.md." + fi + fi + case "$URL" in + *[[:space:]]*|*'"'*|*'\'*) + echo "::error::LESSONS_LEGAL_BASE_URL contains whitespace, a quote or a backslash." + exit 1 + ;; + https://?*) ;; + *) + echo "::error::LESSONS_LEGAL_BASE_URL must be an https:// address; it is \"$URL\". See docs/build.md." + exit 1 + ;; + esac + echo "url=$URL" >> "$GITHUB_OUTPUT" + echo "source=$SOURCE" >> "$GITHUB_OUTPUT" + - name: Decode keystore id: keystore env: @@ -263,6 +310,9 @@ jobs: LESSONS_BUILD_COMMIT: ${{ github.sha }} LESSONS_BUILD_NUMBER: ${{ github.run_number }} LESSONS_BUILD_TIME: ${{ steps.version.outputs.built_at }} + # The folder the terms and the privacy policy are linked from, worked + # out by the «Resolve legal documents» step above. + LESSONS_LEGAL_BASE_URL: ${{ steps.legal.outputs.url }} INPUT_BUILD_TYPE: ${{ inputs.build_type || 'release' }} run: | case "$INPUT_BUILD_TYPE" in @@ -343,7 +393,16 @@ jobs: # button is actually asking. GITHUB_CLIENT_ID: ${{ secrets.LESSONS_GITHUB_CLIENT_ID }} CONTACT_EMAIL: ${{ secrets.LESSONS_CONTACT_EMAIL }} + # Printed in full, because it is public: it is the first link of + # every install this run produces. + LEGAL_URL: ${{ steps.legal.outputs.url }} + LEGAL_SOURCE: ${{ steps.legal.outputs.source }} run: | + if [ -n "$LEGAL_URL" ]; then + LEGAL="\`$LEGAL_URL\` ($LEGAL_SOURCE)" + else + LEGAL="**not resolved** - see the «Resolve legal documents» step" + fi if [ -n "$INPUT_VERSION_CODE" ]; then CODE_SOURCE=" (given)" else @@ -373,6 +432,7 @@ jobs: echo "| APKs produced | ${{ steps.collect.outputs.count }} |" echo "| Sign in with GitHub | $SIGN_IN |" echo "| Report by email | $EMAIL |" + echo "| Terms and privacy policy | $LEGAL |" if [ "${{ steps.keystore.outputs.signed }}" = "true" ]; then echo "| Signing | your release keystore |" else diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 73342692..8e040639 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,3 +1,4 @@ +import java.net.URI import org.jetbrains.kotlin.gradle.dsl.JvmTarget /* @@ -114,6 +115,49 @@ val githubClientId = signingSecret("LESSONS_GITHUB_CLIENT_ID", "lessons.github.c // hides the button. val contactEmail = signingSecret("LESSONS_CONTACT_EMAIL", "lessons.contactEmail") ?: "" +/* + * Where the terms of use and the privacy policy are published: the https + * address of a folder holding terms.{ru,en}.md and privacy.{ru,en}.md. The app + * appends "/terms.ru.md" and the like, and opens the result in the browser when + * there is a network; otherwise it shows the copy bundled from docs/legal/. + * + * The default is docs/legal/ of the upstream repository on its default branch + * (GitHub resolves blob/HEAD/ to it), so a build from a fresh clone links a + * real, current document rather than nothing. `apk.yml` passes docs/legal/ of + * whichever repository it runs in, so a fork's APK links the fork's texts with + * nothing configured; a fork building by hand sets lessons.legal.baseUrl, or + * links the upstream operator's texts. Not a branch or a tag: an installed APK + * keeps its link for life, and a feature branch is deleted within a week. + * + * Refused rather than kept when it is not https or not a plain folder address. + * It is the first link of every install, a policy fetched over plain HTTP is + * one anybody on the café's network can rewrite before it is read, and + * buildConfigField splices the value into Java source, where a stray quote is a + * compile error minutes later instead of this sentence now. + */ +val defaultLegalBaseUrl = "https://github.com/lumenpearson/lessons/blob/HEAD/docs/legal" + +val legalBaseUrl: String = + (signingSecret("LESSONS_LEGAL_BASE_URL", "lessons.legal.baseUrl") ?: defaultLegalBaseUrl).let { raw -> + val candidate = raw.trim().trimEnd('/') + // URI refuses a quote, a backslash, a space and the other + // characters that would break the generated Java string. + runCatching { URI(candidate) }.getOrNull() + ?.takeIf { uri -> + uri.scheme == "https" && + !uri.host.isNullOrEmpty() && + uri.rawQuery == null && + uri.rawFragment == null + } + ?.let { candidate } + ?: throw GradleException( + "LESSONS_LEGAL_BASE_URL / lessons.legal.baseUrl is \"$raw\"; it must be the " + + "https:// address of a folder holding terms.ru.md, terms.en.md, " + + "privacy.ru.md and privacy.en.md, with no query and no fragment. " + + "See docs/build.md.", + ) + } + /* * Where this APK came from, for the about page's badges. * @@ -155,6 +199,18 @@ android { buildConfigField("String", "BUILD_COMMIT", "\"$buildCommit\"") buildConfigField("String", "BUILD_NUMBER", "\"$buildNumber\"") buildConfigField("String", "BUILD_TIME", "\"$buildTime\"") + buildConfigField("String", "LEGAL_BASE_URL", "\"$legalBaseUrl\"") + } + + sourceSets { + // The terms and the privacy policy the first screen's line opens when + // the browser is not an answer — offline, no browser, a captive portal. + // docs/legal/ itself is the asset folder, like docs/app/ is for the + // guide in :core:data, so the APK carries the one copy that is published + // rather than a second one kept level by hand. The names cannot collide + // with the guide's at the asset root: `legal.json`, not `manifest.json`, + // and LegalDocumentsTest holds that for every folder mounted there. + getByName("main").assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/legal")) } androidResources { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsBlocks.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsBlocks.kt new file mode 100644 index 00000000..7e118fd1 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsBlocks.kt @@ -0,0 +1,198 @@ +package com.lumenpearson.lessons.ui.docs + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Info +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withLink +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile +import com.lumenpearson.lessons.core.designsystem.component.AccentTile +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.text.MarkupStyles +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.model.DocsBlock +import com.lumenpearson.lessons.core.model.DocsSpan + +/* + * How one block of the app's Markdown is drawn, apart from the screen that pages + * through the guide. + * + * Its own file because the guide is no longer the only reader: the terms of use + * and the privacy policy are written in the same subset and drawn in a sheet by + * `ui/legal`. A second renderer for the same four blocks would draw a note one + * way in the guide and another in the policy, and the first reader to notice + * would be somebody wondering which of the two is the real document. Moved + * rather than rewritten: nothing here changed but where it lives, and only + * [DocsRun] is visible outside the file, because a run is the unit a reader + * draws. + */ + +/** One run: either a stack of steps in one container, or a single block. */ +@Composable +internal fun DocsRun(run: List, styles: MarkupStyles) { + if (run.size > 1 || run.first() is DocsBlock.Step) { + RoundedCardContainer { + run.forEachIndexed { index, block -> + val step = block as DocsBlock.Step + StepRow(step = step, tone = index, styles = styles) + } + } + return + } + + when (val block = run.first()) { + is DocsBlock.Paragraph -> DocsParagraph(block.spans, styles) + is DocsBlock.Points -> DocsPoints(block.items.map { it.spans }, styles) + is DocsBlock.Note -> DocsNote(block.spans, styles) + // Unreachable: a lone step took the branch above. + is DocsBlock.Step -> Unit + } +} + +/** + * Prose, on the page itself rather than in a container. + * + * A paragraph in a card reads as a row of a list, which is what every other + * container in this app is; the documentation is the one screen whose default + * content is text, and the text should look like text. The 8 dp inset is + * [ScreenHeader]'s own, so the first line of a paragraph starts under the first + * letter of the heading. + */ +@Composable +private fun DocsParagraph(spans: List, styles: MarkupStyles) { + Text( + text = annotated(spans, styles), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp), + ) +} + +/** Several peers, each on a row of the group, marked by a coloured dot. */ +@Composable +private fun DocsPoints(items: List>, styles: MarkupStyles) { + RoundedCardContainer { + items.forEachIndexed { index, spans -> + GroupRow(verticalAlignment = Alignment.Top) { + // A dot rather than the 40 dp icon tile every settings row has: + // the points of a list are not eight different things needing + // eight different glyphs, and a column of tiles would be the + // loudest part of a page made of sentences. The hue still + // walks the accent slots, which is what makes a point findable + // again after it has been read once. + AccentTile( + tone = accentTone(index), + size = DotSize, + modifier = Modifier.padding(top = DotOffset), + ) {} + Text( + text = annotated(spans, styles), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +/** + * The sentence a skimmer must not skim past. + * + * Given a container and a glyph precisely because the prose around it has + * neither: on a page of unadorned paragraphs, a card is the loudest thing + * available and costs nothing to read. + */ +@Composable +private fun DocsNote(spans: List, styles: MarkupStyles) { + RoundedCardContainer { + GroupRow( + container = MaterialTheme.colorScheme.surfaceContainerHigh, + verticalAlignment = Alignment.Top, + ) { + AccentIconTile(icon = Icons.Rounded.Info, tone = accentTone(5)) + Text( + text = annotated(spans, styles), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + } + } +} + +/** One numbered stage: the number on the tile, then its own title and prose. */ +@Composable +private fun StepRow(step: DocsBlock.Step, tone: Int, styles: MarkupStyles) { + GroupRow(verticalAlignment = Alignment.Top) { + AccentTile(tone = accentTone(tone)) { + Text( + text = step.number.toString(), + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), + color = accentTone(tone).content, + ) + } + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + if (step.title.isNotEmpty()) { + Text( + text = annotated(step.title, styles), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + Text( + text = annotated(step.text, styles), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** + * The parsed spans of one line, as text the screen can draw. + * + * Flat, like the release notes' renderer and for the same reason: a bold span + * is bold text, not a sub-document. A link is a `LinkAnnotation` rather than a + * click handler, so the platform opens it and a screen reader announces it as a + * link. + */ +private fun annotated(spans: List, styles: MarkupStyles): AnnotatedString = + buildAnnotatedString { + spans.forEach { span -> + when { + span.link != null -> withLink( + LinkAnnotation.Url(url = span.link!!, styles = styles.link), + ) { + append(span.text) + } + + span.code -> withStyle(styles.code) { append(span.text) } + span.bold -> withStyle(styles.bold) { append(span.text) } + else -> append(span.text) + } + } + } + +/** Diameter of a point's dot, and how far down the row it sits to meet the first line. */ +private val DotSize = 10.dp +private val DotOffset = 5.dp diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsScreen.kt index 26401155..ab1ce305 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/docs/DocsScreen.kt @@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed @@ -14,31 +13,22 @@ import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.CloudOff -import androidx.compose.material.icons.rounded.Info import androidx.compose.material.icons.rounded.MenuBook import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.LinkAnnotation -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.withLink -import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.R import com.lumenpearson.lessons.core.data.repository.DocsFailure import com.lumenpearson.lessons.core.data.repository.DocsState import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile -import com.lumenpearson.lessons.core.designsystem.component.AccentTile import com.lumenpearson.lessons.core.designsystem.component.GroupRow import com.lumenpearson.lessons.core.designsystem.component.LessonsPullToRefreshBox import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader import com.lumenpearson.lessons.core.designsystem.component.ToolbarItem -import com.lumenpearson.lessons.core.designsystem.text.MarkupStyles import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString import com.lumenpearson.lessons.core.designsystem.text.rememberMarkupStyles @@ -53,7 +43,6 @@ import com.lumenpearson.lessons.core.model.DocsBlock import com.lumenpearson.lessons.core.model.DocsGuidePage import com.lumenpearson.lessons.core.model.DocsOrigin import com.lumenpearson.lessons.core.model.DocsRelease -import com.lumenpearson.lessons.core.model.DocsSpan /** * The guide: every page in one pager, and one way out. @@ -288,162 +277,6 @@ internal fun docsContentType(run: List): String { } } -/** One run: either a stack of steps in one container, or a single block. */ -@Composable -private fun DocsRun(run: List, styles: MarkupStyles) { - if (run.size > 1 || run.first() is DocsBlock.Step) { - RoundedCardContainer { - run.forEachIndexed { index, block -> - val step = block as DocsBlock.Step - StepRow(step = step, tone = index, styles = styles) - } - } - return - } - - when (val block = run.first()) { - is DocsBlock.Paragraph -> DocsParagraph(block.spans, styles) - is DocsBlock.Points -> DocsPoints(block.items.map { it.spans }, styles) - is DocsBlock.Note -> DocsNote(block.spans, styles) - // Unreachable: a lone step took the branch above. - is DocsBlock.Step -> Unit - } -} - -/** - * Prose, on the page itself rather than in a container. - * - * A paragraph in a card reads as a row of a list, which is what every other - * container in this app is; the documentation is the one screen whose default - * content is text, and the text should look like text. The 8 dp inset is - * [ScreenHeader]'s own, so the first line of a paragraph starts under the first - * letter of the heading. - */ -@Composable -private fun DocsParagraph(spans: List, styles: MarkupStyles) { - Text( - text = annotated(spans, styles), - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 8.dp), - ) -} - -/** Several peers, each on a row of the group, marked by a coloured dot. */ -@Composable -private fun DocsPoints(items: List>, styles: MarkupStyles) { - RoundedCardContainer { - items.forEachIndexed { index, spans -> - GroupRow(verticalAlignment = Alignment.Top) { - // A dot rather than the 40 dp icon tile every settings row has: - // the points of a list are not eight different things needing - // eight different glyphs, and a column of tiles would be the - // loudest part of a page made of sentences. The hue still - // walks the accent slots, which is what makes a point findable - // again after it has been read once. - AccentTile( - tone = accentTone(index), - size = DotSize, - modifier = Modifier.padding(top = DotOffset), - ) {} - Text( - text = annotated(spans, styles), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.weight(1f), - ) - } - } - } -} - -/** - * The sentence a skimmer must not skim past. - * - * Given a container and a glyph precisely because the prose around it has - * neither: on a page of unadorned paragraphs, a card is the loudest thing - * available and costs nothing to read. - */ -@Composable -private fun DocsNote(spans: List, styles: MarkupStyles) { - RoundedCardContainer { - GroupRow( - container = MaterialTheme.colorScheme.surfaceContainerHigh, - verticalAlignment = Alignment.Top, - ) { - AccentIconTile(icon = Icons.Rounded.Info, tone = accentTone(5)) - Text( - text = annotated(spans, styles), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.weight(1f), - ) - } - } -} - -/** One numbered stage: the number on the tile, then its own title and prose. */ -@Composable -private fun StepRow(step: DocsBlock.Step, tone: Int, styles: MarkupStyles) { - GroupRow(verticalAlignment = Alignment.Top) { - AccentTile(tone = accentTone(tone)) { - Text( - text = step.number.toString(), - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), - color = accentTone(tone).content, - ) - } - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - if (step.title.isNotEmpty()) { - Text( - text = annotated(step.title, styles), - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - } - Text( - text = annotated(step.text, styles), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -/** - * The parsed spans of one line, as text the screen can draw. - * - * Flat, like the release notes' renderer and for the same reason: a bold span - * is bold text, not a sub-document. A link is a `LinkAnnotation` rather than a - * click handler, so the platform opens it and a screen reader announces it as a - * link. - */ -private fun annotated(spans: List, styles: MarkupStyles): AnnotatedString = - buildAnnotatedString { - spans.forEach { span -> - when { - span.link != null -> withLink( - LinkAnnotation.Url(url = span.link!!, styles = styles.link), - ) { - append(span.text) - } - - span.code -> withStyle(styles.code) { append(span.text) } - span.bold -> withStyle(styles.bold) { append(span.text) } - else -> append(span.text) - } - } - } - -/** Diameter of a point's dot, and how far down the row it sits to meet the first line. */ -private val DotSize = 10.dp -private val DotOffset = 5.dp - /** * Which toolbar item reads as current, or `-1` for none. * diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLine.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLine.kt new file mode 100644 index 00000000..a8f12481 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLine.kt @@ -0,0 +1,72 @@ +package com.lumenpearson.lessons.ui.legal + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextAlign +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.legal.LegalDocument +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.text.rememberMarkupStyles + +/** + * «Продолжая, вы принимаете Условия использования и Политику + * конфиденциальности» — the line under the first screen's button. + * + * **Always drawn**, whatever the build was told. A build with no address still + * carries both texts in its assets, so there is always something to open, and + * a line that came and went with a Gradle property would make what a reader + * accepted depend on who compiled their APK. + * + * Small and quiet on purpose, after GMS Flags Reborn's: it sits under the + * button rather than in a dialog in front of it, because nothing is recorded + * when somebody continues — there is no acceptance to collect, only a sentence + * to be told. The full-size way to the same two documents is «О приложении». + * + * Correction mode cannot reach it by a long press, the known limit it shares + * with the design credit: the lookup matches the whole drawn text, and this + * text is built from three strings. + * + * @param onOpen what a tap on a link does. Left `null` it opens the document + * the way [rememberLegalOpener] does — the browser when it can, the bundled + * copy when it cannot — which is what every caller but a test wants. + */ +@Composable +fun LegalAcceptanceLine( + modifier: Modifier = Modifier, + onOpen: ((LegalDocument) -> Unit)? = null, +) { + val opener = rememberLegalOpener() + // The listener lives inside an AnnotatedString that is remembered, so it + // must read the newest callback rather than the one it was built with. + val open by rememberUpdatedState(onOpen ?: opener::open) + val link = rememberMarkupStyles().link + + val template = correctedString(R.string.onboarding_legal_notice) + val terms = correctedString(R.string.onboarding_legal_terms) + val privacy = correctedString(R.string.onboarding_legal_privacy) + // The whole sentence as plain text, for the one case the links cannot be + // placed: a proofreader's correction that typed over a placeholder. The + // formatted read falls back to the shipped pattern when the corrected one + // will not format, and the reader is still told what continuing means; + // the two documents stay reachable from «О приложении». + val plain = correctedString(R.string.onboarding_legal_notice, terms, privacy) + + val text = remember(template, plain, terms, privacy, link) { + legalNoticeText(template, terms, privacy, link) { open(it) } ?: AnnotatedString(plain) + } + + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = modifier.fillMaxWidth(), + ) +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt new file mode 100644 index 00000000..f3695cb5 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt @@ -0,0 +1,174 @@ +package com.lumenpearson.lessons.ui.legal + +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.text.intl.Locale +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.legal.BundledLegal +import com.lumenpearson.lessons.core.data.legal.LegalDocument +import com.lumenpearson.lessons.core.data.legal.LegalText +import com.lumenpearson.lessons.core.designsystem.component.LessonsBottomSheet +import com.lumenpearson.lessons.core.designsystem.component.LessonsLoadingBox +import com.lumenpearson.lessons.core.designsystem.haptic.LessonsHaptics +import com.lumenpearson.lessons.core.designsystem.haptic.rememberHapticView +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.text.rememberMarkupStyles +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.ui.docs.DocsRun +import com.lumenpearson.lessons.ui.docs.docsRuns +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** What the sheet has to draw: nothing yet, nothing at all, or the document. */ +internal sealed interface LegalLoad { + data object Loading : LegalLoad + data object Missing : LegalLoad + data class Ready(val text: LegalText) : LegalLoad +} + +/** The heading a document is shown under, in the sheet and on «О приложении». */ +@StringRes +internal fun legalTitle(document: LegalDocument): Int = when (document) { + LegalDocument.TERMS -> R.string.legal_title_terms + LegalDocument.PRIVACY -> R.string.legal_title_privacy +} + +/** + * The copy of [document] the APK was built with, read from its assets. + * + * This is what makes the line on the first screen honest offline: the reader + * is told that continuing accepts two documents, and they can read both with no + * network and on a build that was given no address. Read on the IO dispatcher + * because an asset is a file, and the sheet opens with a loader rather than a + * frame's delay spent reading forty kilobytes on the main thread. + * + * @param url the current edition's address, when there is one. The sheet then + * says that it is showing the bundled copy and offers the link, because it + * only appears with an address when the browser could not be used. + */ +@Composable +internal fun LegalDocumentSheet( + document: LegalDocument, + url: String?, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + val language = Locale.current.language + val load by produceState(LegalLoad.Loading, document, language) { + val text = withContext(Dispatchers.IO) { BundledLegal.read(context, document, language) } + value = if (text != null) LegalLoad.Ready(text) else LegalLoad.Missing + } + LessonsBottomSheet( + onDismissRequest = onDismiss, + title = correctedString(legalTitle(document)), + ) { + LegalDocumentBody(load = load, url = url) + } +} + +/** + * The sheet's content, apart from the sheet, so a test can draw it without a + * window of its own. + */ +@Composable +internal fun LegalDocumentBody( + load: LegalLoad, + url: String?, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val view = rememberHapticView() + val styles = rememberMarkupStyles() + + Column( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = ScreenPadding) + .padding(bottom = ScreenPadding), + verticalArrangement = Arrangement.spacedBy(BlockGap), + ) { + when (load) { + LegalLoad.Loading -> LessonsLoadingBox(modifier = Modifier.fillMaxWidth()) + + LegalLoad.Missing -> Text( + text = correctedString(R.string.legal_missing), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + is LegalLoad.Ready -> { + load.text.edition?.let { edition -> + Text( + text = correctedString( + R.string.legal_edition, + edition.edition, + formatEffective(edition.effective), + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (url != null) { + Text( + text = correctedString(R.string.legal_bundled_note), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton( + onClick = { + LessonsHaptics.press(view) + openInBrowser(context, url) + }, + ) { + Text( + text = correctedString(R.string.legal_open_current), + style = MaterialTheme.typography.labelLarge, + ) + } + } + load.text.guide.pages.forEach { page -> + // Every section in one scroll rather than the guide's pager: + // a policy is read top to bottom, and a reader who is being + // asked to accept it should not have to find out that there + // are eleven more pages to swipe. + Text( + text = page.title, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 8.dp, start = 8.dp, end = 8.dp), + ) + val runs = remember(page) { docsRuns(page.blocks) } + runs.forEach { run -> DocsRun(run = run, styles = styles) } + } + } + } + } +} + +/** «25 сентября 2026 г.» — the date in the words of the language on screen. */ +@Composable +private fun formatEffective(date: LocalDate): String { + val locale = LocalResources.current.configuration.locales[0] ?: java.util.Locale.getDefault() + return remember(date, locale) { + DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(locale).format(date) + } +} + +private val BlockGap = 12.dp diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt new file mode 100644 index 00000000..5e531bf8 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt @@ -0,0 +1,116 @@ +package com.lumenpearson.lessons.ui.legal + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.intl.Locale +import androidx.core.net.toUri +import com.lumenpearson.lessons.BuildConfig +import com.lumenpearson.lessons.core.data.legal.LegalDocument +import com.lumenpearson.lessons.core.data.legal.legalUrl + +/** Where a tap on a legal link ends up. */ +internal sealed interface LegalTarget { + /** The current edition, in the reader's browser. */ + data class Web(val url: String) : LegalTarget + + /** The edition this APK was built with, in a sheet. */ + data object Bundled : LegalTarget +} + +/** + * The browser when there is an address and a network that reaches past its own + * router; the bundled copy otherwise. + * + * "Validated" rather than "connected" because the case worth catching is the + * school's Wi-Fi with a captive portal: connected, and every page it opens is + * the portal's sign-in, so the reader would be accepting a document they were + * never shown. Whether a browser exists is not decided here — it is only known + * by trying, and a failed try falls back to the same sheet. + */ +internal fun legalTarget(url: String?, online: Boolean): LegalTarget = + if (url != null && online) LegalTarget.Web(url) else LegalTarget.Bundled + +/** + * Opens the terms or the privacy policy, whichever way this phone can. + * + * Built by [rememberLegalOpener], which also hosts the sheet it falls back to. + * One opener for the first screen's line and for «О приложении», so the two + * cannot disagree about which copy a reader is shown. + */ +@Stable +class LegalOpener internal constructor( + private val context: Context, + private val baseUrl: String, + private val language: String, + private val showBundled: (LegalDocument) -> Unit, +) { + fun open(document: LegalDocument) { + when (val target = legalTarget(legalUrl(baseUrl, document, language), isOnline(context))) { + is LegalTarget.Web -> if (!openInBrowser(context, target.url)) showBundled(document) + LegalTarget.Bundled -> showBundled(document) + } + } +} + +/** + * A [LegalOpener], and the sheet it shows when the browser is not an answer. + * + * The sheet is composed here rather than by each caller so that a caller needs + * nothing but this one call: the first screen's line and the about card each + * get the whole behaviour, fallback included, and neither can forget it. Which + * document is open is saved state, so a rotation keeps the sheet up. + * + * @param baseUrl the build's legal folder; a parameter only so a test can hand + * in an address instead of the one this build was configured with. + */ +@Composable +fun rememberLegalOpener(baseUrl: String = BuildConfig.LEGAL_BASE_URL): LegalOpener { + val context = LocalContext.current + val language = Locale.current.language + val shown = rememberSaveable { mutableStateOf(null) } + val opener = remember(context, baseUrl, language) { + LegalOpener(context, baseUrl, language) { document -> shown.value = document } + } + shown.value?.let { document -> + LegalDocumentSheet( + document = document, + url = legalUrl(baseUrl, document, language), + onDismiss = { shown.value = null }, + ) + } + return opener +} + +/** Whether the active network has been checked to reach the internet. */ +internal fun isOnline(context: Context): Boolean { + val manager = context.getSystemService(ConnectivityManager::class.java) ?: return false + return runCatching { + val capabilities = manager.getNetworkCapabilities(manager.activeNetwork) + capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true + }.getOrDefault(false) +} + +/** + * `false` when nothing could open [url]. + * + * A work profile or a locked-down school phone may have no browser at all, and + * the about card's links already learned that an unguarded `startActivity` + * takes the app down on one. + */ +internal fun openInBrowser(context: Context, url: String): Boolean = try { + context.startActivity( + Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + true +} catch (_: ActivityNotFoundException) { + false +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LinkedSentence.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LinkedSentence.kt new file mode 100644 index 00000000..0bd8cde3 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LinkedSentence.kt @@ -0,0 +1,83 @@ +package com.lumenpearson.lessons.ui.legal + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.withLink +import com.lumenpearson.lessons.core.data.legal.LegalDocument + +/** `%1$s`, `%2$s` … — the only placeholder a linked sentence may carry. */ +private val PLACEHOLDER = Regex("%(\\d+)\\\$s") + +/** + * [template] with its `%N$s` placeholders replaced by the Nth label, each drawn + * as its link. `null` when the template does not use every label exactly once. + * + * A sentence with a link inside it used to be three strings — the words + * before, the link, the words after — and aapt2 trims the spaces at a string's + * edges, so the credit on «О приложении» shipped as «по мотивамEssentials» + * (#155). One template keeps the spaces where a translator typed them, lets a + * language put the links in its own order, and lets Russian inflect the words + * around them. + * + * `null` rather than a best effort because the template may be a reader's + * correction, and one that lost a placeholder would otherwise draw «%2$s» on + * the first screen or silently drop a link the reader is accepting. The caller + * then draws the formatted sentence as plain text, which `correctedString` + * already falls back to the shipped pattern for. + */ +internal fun linkedSentence( + template: String, + links: List>, +): AnnotatedString? { + val matches = PLACEHOLDER.findAll(template).toList() + val numbers = matches.map { it.groupValues[1].toIntOrNull() ?: return null } + if (numbers.sorted() != (1..links.size).toList()) return null + return buildAnnotatedString { + var at = 0 + for (match in matches) { + append(template.substring(at, match.range.first)) + val (label, link) = links[match.groupValues[1].toInt() - 1] + withLink(link) { append(label) } + at = match.range.last + 1 + } + append(template.substring(at)) + } +} + +/** + * «Продолжая, вы принимаете Условия использования и Политику + * конфиденциальности», with both documents as links. `null` as [linkedSentence]. + * + * Each link is a [LinkAnnotation.Clickable] handing its document to [onOpen], + * not a [LinkAnnotation.Url]. A URL goes straight to the platform's handler, + * and every tap here must be able to end at the copy bundled in the APK + * instead — offline, on a phone with no browser, on a build that knows no + * address. A clickable annotation is still announced as a link by a screen + * reader, which is the other half of why a plain click handler on the text was + * not used. + */ +internal fun legalNoticeText( + template: String, + termsLabel: String, + privacyLabel: String, + linkStyles: TextLinkStyles, + onOpen: (LegalDocument) -> Unit, +): AnnotatedString? = linkedSentence( + template = template, + links = listOf( + termsLabel to legalLink(LegalDocument.TERMS, linkStyles, onOpen), + privacyLabel to legalLink(LegalDocument.PRIVACY, linkStyles, onOpen), + ), +) + +private fun legalLink( + document: LegalDocument, + styles: TextLinkStyles, + onOpen: (LegalDocument) -> Unit, +): LinkAnnotation = LinkAnnotation.Clickable( + tag = document.slug, + styles = styles, + linkInteractionListener = { onOpen(document) }, +) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt index 0fad1745..6683a2c5 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/AboutCard.kt @@ -19,7 +19,9 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Code +import androidx.compose.material.icons.rounded.Gavel import androidx.compose.material.icons.rounded.Palette +import androidx.compose.material.icons.rounded.PrivacyTip import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton @@ -32,14 +34,13 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles -import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration -import androidx.compose.ui.text.withLink import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.lumenpearson.lessons.BuildConfig @@ -49,7 +50,12 @@ import com.lumenpearson.lessons.core.designsystem.haptic.LessonsHaptics import com.lumenpearson.lessons.core.designsystem.haptic.rememberHapticView import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.data.legal.LegalDocument import com.lumenpearson.lessons.core.data.repository.ServerStatus +import com.lumenpearson.lessons.ui.legal.LegalOpener +import com.lumenpearson.lessons.ui.legal.legalTitle +import com.lumenpearson.lessons.ui.legal.linkedSentence +import com.lumenpearson.lessons.ui.legal.rememberLegalOpener /** * The card at the very bottom of the about page: what this is, and who it is by. @@ -159,28 +165,33 @@ private fun AppMark() { } } -/** Where this came from, with the source repository as a link in the sentence. */ +/** + * Where this came from, with the source repository as a link in the sentence. + * + * One template with the link as its placeholder. It used to be the words + * before, the link and the words after as three strings, and aapt2 trims the + * space at the end of a string — so both languages shipped with the last word + * run into the link, «по мотивамEssentials» (#155). + */ @Composable private fun DesignCredit() { val label = correctedString(R.string.about_design_credit_link) - val credit = buildAnnotatedString { - append(correctedString(R.string.about_design_credit_before)) - withLink( - LinkAnnotation.Url( - url = EssentialsUrl, - styles = TextLinkStyles( - style = SpanStyle( - color = MaterialTheme.colorScheme.primary, - fontWeight = FontWeight.Medium, - textDecoration = TextDecoration.Underline, - ), - ), + val template = correctedString(R.string.about_design_credit) + val plain = correctedString(R.string.about_design_credit, label) + val link = LinkAnnotation.Url( + url = EssentialsUrl, + styles = TextLinkStyles( + style = SpanStyle( + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.Medium, + textDecoration = TextDecoration.Underline, ), - ) { - append(label) - } - append(correctedString(R.string.about_design_credit_after)) - } + ), + ) + // A proofreader's correction that typed over the placeholder has nowhere + // to put the link; the sentence is still drawn, as plain text, and the + // same repository is the «Essentials» row below. + val credit = linkedSentence(template, listOf(label to link)) ?: AnnotatedString(plain) // No onClick and no Intent: LinkAnnotation.Url is opened by the platform's // own UriHandler, which is also what makes the link reachable by a screen @@ -193,19 +204,43 @@ private fun DesignCredit() { ) } +/** + * Where a pill goes: a web page, or one of the two legal texts. + * + * The legal texts are not just two more URLs. They open in the browser only + * when there is a network to open them over and a browser to open them in, and + * otherwise as the copy bundled in the APK — the same [LegalOpener] the line on + * the first screen uses, so that the two ways to a document cannot show a + * reader two different ones. + */ +private sealed interface AboutTarget { + data class Web(val url: String) : AboutTarget + data class Legal(val document: LegalDocument) : AboutTarget +} + /** One outward link: an icon, a label, and somewhere to go. */ private data class AboutLink( val icon: ImageVector, @StringRes val label: Int, - val url: String, + val target: AboutTarget, ) private const val ProjectUrl = "https://github.com/lumenpearson/lessons" private const val EssentialsUrl = "https://github.com/sameerasw/essentials" private val Links = listOf( - AboutLink(Icons.Rounded.Code, R.string.about_link_source, ProjectUrl), - AboutLink(Icons.Rounded.Palette, R.string.about_link_essentials, EssentialsUrl), + AboutLink(Icons.Rounded.Code, R.string.about_link_source, AboutTarget.Web(ProjectUrl)), + AboutLink(Icons.Rounded.Palette, R.string.about_link_essentials, AboutTarget.Web(EssentialsUrl)), + AboutLink( + Icons.Rounded.Gavel, + legalTitle(LegalDocument.TERMS), + AboutTarget.Legal(LegalDocument.TERMS), + ), + AboutLink( + Icons.Rounded.PrivacyTip, + legalTitle(LegalDocument.PRIVACY), + AboutTarget.Legal(LegalDocument.PRIVACY), + ), ) /** @@ -224,12 +259,13 @@ private val Links = listOf( */ @Composable private fun LinkPills() { + val legal = rememberLegalOpener() Column( verticalArrangement = Arrangement.spacedBy(PillGap), modifier = Modifier.fillMaxWidth(), ) { Links.forEach { link -> - LinkPill(link = link, modifier = Modifier.fillMaxWidth()) + LinkPill(link = link, onLegal = legal::open, modifier = Modifier.fillMaxWidth()) } } } @@ -412,22 +448,31 @@ private fun open(context: android.content.Context, view: android.view.View, url: } @Composable -private fun LinkPill(link: AboutLink, modifier: Modifier = Modifier) { +private fun LinkPill( + link: AboutLink, + onLegal: (LegalDocument) -> Unit, + modifier: Modifier = Modifier, +) { val context = LocalContext.current val view = rememberHapticView() OutlinedButton( onClick = { LessonsHaptics.press(view) - val intent = Intent(Intent.ACTION_VIEW, link.url.toUri()) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - // A phone with no browser at all is rare; a work profile or a - // locked-down school device that cannot open one is not, and the - // reference crashes on both. - try { - context.startActivity(intent) - } catch (_: ActivityNotFoundException) { - LessonsHaptics.press(view) + when (val target = link.target) { + is AboutTarget.Legal -> onLegal(target.document) + is AboutTarget.Web -> { + val intent = Intent(Intent.ACTION_VIEW, target.url.toUri()) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + // A phone with no browser at all is rare; a work profile or + // a locked-down school device that cannot open one is not, + // and the reference crashes on both. + try { + context.startActivity(intent) + } catch (_: ActivityNotFoundException) { + LessonsHaptics.press(view) + } + } } }, modifier = modifier, diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt index 06b5bdec..7800e62c 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt @@ -163,7 +163,7 @@ internal object TranslationXml { private const val DefaultStringFile = "strings.xml" /** - * `:app`'s eight, in the order they are searched. + * `:app`'s nine, in the order they are searched. * * `strings.xml` first because it holds the most and is the only one every * other module has; the rest in any order, since a key is in exactly one @@ -177,6 +177,7 @@ internal object TranslationXml { "strings_diary.xml", "strings_docs.xml", "strings_github.xml", + "strings_legal.xml", "strings_telegram.xml", "strings_translate.xml", "strings_updates.xml", diff --git a/android/app/src/main/res/values-en/strings.xml b/android/app/src/main/res/values-en/strings.xml index 45a383f4..d3b592c5 100644 --- a/android/app/src/main/res/values-en/strings.xml +++ b/android/app/src/main/res/values-en/strings.xml @@ -377,10 +377,9 @@ The access key you were given and a copy of the timetable stay on the device, so A school diary with a widget on the home screen. It works offline: the timetable, the substitutions and the homework are kept on the device. Lessons v%1$s Built by lumenpearson - - Design language, font and components — after + + Design language, font and components — after %1$s, MIT licence. Essentials - , MIT licence. Source code Essentials Made for one school diff --git a/android/app/src/main/res/values-en/strings_legal.xml b/android/app/src/main/res/values-en/strings_legal.xml new file mode 100644 index 00000000..bb686de0 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_legal.xml @@ -0,0 +1,19 @@ + + + + + By continuing, you accept the %1$s and the %2$s + Terms of Use + Privacy Policy + + Terms of use + Privacy policy + + Edition %1$d of %2$s + This is the copy built into the app. The current edition is at the link. + Open the current edition + Could not open the document. + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 81871798..a4e030da 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -377,10 +377,9 @@ Школьный дневник с виджетом на главном экране. Работает офлайн: расписание, замены и домашние задания хранятся на устройстве. Дневник v%1$s Собрано lumenpearson - - Оформление, шрифт и компоненты — по мотивам + + Оформление, шрифт и компоненты — по мотивам %1$s, лицензия MIT. Essentials - , лицензия MIT. Исходный код Essentials Сделано для одной школы diff --git a/android/app/src/main/res/values/strings_legal.xml b/android/app/src/main/res/values/strings_legal.xml new file mode 100644 index 00000000..23bed435 --- /dev/null +++ b/android/app/src/main/res/values/strings_legal.xml @@ -0,0 +1,31 @@ + + + + + + Продолжая, вы принимаете %1$s и %2$s + Условия использования + Политику конфиденциальности + + + Условия использования + Политика конфиденциальности + + + Редакция %1$d от %2$s + Это копия, встроенная в приложение. Актуальная редакция — по ссылке. + Открыть актуальную редакцию + Не удалось открыть документ. + + diff --git a/android/app/src/main/res/xml/backup_rules.xml b/android/app/src/main/res/xml/backup_rules.xml index cf6fe8a4..f9171cf0 100644 --- a/android/app/src/main/res/xml/backup_rules.xml +++ b/android/app/src/main/res/xml/backup_rules.xml @@ -5,10 +5,19 @@ The Room cache is a copy of the server's answer and is refetched on first sync, and the device token is tied to a device that the user is replacing. Restoring either would show a stale timetable to someone who then has no idea - why it is wrong. Re-entering the six-character class code is cheaper. + why it is wrong. Re-entering the eight-character class code is cheaper. + + Crash reports are excluded for a different reason: the first run promises + that a report stays on the phone until its owner sends it, and a backup is + the phone sending it to Google (#156). CrashReporter writes them to + getExternalFilesDir("crash_reports") and, when there is no external storage, + to filesDir/crash_reports, so both domains are named. BackupRulesTest fails + if either is left out here or in data_extraction_rules.xml. --> + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml index 45e71434..db09134c 100644 --- a/android/app/src/main/res/xml/data_extraction_rules.xml +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -1,14 +1,21 @@ - + + + + + diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt new file mode 100644 index 00000000..ff699489 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt @@ -0,0 +1,115 @@ +package com.lumenpearson.lessons + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +/** + * Crash reports stay out of every copy the system makes of this app (#156). + * + * The first run tells a reader that a report «остаётся на телефоне» until they + * send it, and the privacy policy repeats the promise. A report holds the + * phone's model, versions, a stack trace and the latest log lines; Android's + * Auto Backup copies an app's files to Google by default, `external` domain + * included, unless the rules say otherwise — and until this test the rules + * excluded the databases and the preferences and said nothing about reports. + * + * There are two rule files because there are two formats: `backup_rules.xml` + * is read up to Android 11, `data_extraction_rules.xml` from Android 12, where + * the cloud and a transfer to a new phone are two lists. A report must be out + * of all three, and in both of the places `CrashReporter` may write it — the + * external files folder, and the internal one it falls back to when there is + * no external storage. + * + * The folder name is read out of `CrashReporter` itself rather than typed here, + * so renaming the folder there fails this instead of quietly letting the new + * folder into the backup. What this cannot say is whether a real phone obeys + * the rules: that needs a device and `bmgr`, and has not been done. + */ +class BackupRulesTest { + + private val xml = File("src/main/res/xml") + + private val reportsFolder: String by lazy { + val source = File( + "../core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/diagnostics/CrashReporter.kt", + ) + assertTrue("${source.path} is missing — the walk went wrong", source.isFile) + val text = source.readText() + val name = Regex("""REPORTS_DIR\s*=\s*"([^"]+)"""").find(text)?.groupValues?.get(1) + assertTrue( + "CrashReporter no longer declares REPORTS_DIR, so this test cannot tell " + + "where the reports are", + name != null, + ) + // Both places the reporter writes, so a third one added there is a + // question this test has to be taught rather than one it misses. + assertTrue( + "CrashReporter writes somewhere other than getExternalFilesDir and filesDir", + text.contains("getExternalFilesDir(REPORTS_DIR)") && + text.contains("File(context.filesDir, REPORTS_DIR)"), + ) + checkNotNull(name) + } + + /** Every `` under [parent] (or the whole file), as domain to path. */ + private fun excludes(file: String, parent: String?): Set> { + val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(File(xml, file)) + val scope = if (parent == null) { + document.documentElement + } else { + val nodes = document.getElementsByTagName(parent) + assertTrue("$file has no <$parent>", nodes.length == 1) + nodes.item(0) as Element + } + val found = scope.getElementsByTagName("exclude") + return (0 until found.length).map { index -> + val element = found.item(index) as Element + element.getAttribute("domain") to element.getAttribute("path").trimEnd('/') + }.toSet() + } + + private fun assertReportsExcluded(where: String, rules: Set>) { + listOf("external", "file").forEach { domain -> + assertTrue( + "$where lets crash reports under the «$domain» domain into the copy, " + + "although the app promises they stay on the phone: $rules", + (domain to reportsFolder) in rules, + ) + } + } + + @Test + fun `reports are out of the backup up to Android 11`() { + assertReportsExcluded("backup_rules.xml", excludes("backup_rules.xml", parent = null)) + } + + @Test + fun `reports are out of the cloud backup from Android 12`() { + assertReportsExcluded( + "data_extraction_rules.xml ", + excludes("data_extraction_rules.xml", parent = "cloud-backup"), + ) + } + + @Test + fun `reports are out of a transfer to a new phone from Android 12`() { + assertReportsExcluded( + "data_extraction_rules.xml ", + excludes("data_extraction_rules.xml", parent = "device-transfer"), + ) + } + + @Test + fun `the three lists exclude the same things`() { + // One reasoning, written once in backup_rules.xml: a list that drifts + // from the other two is a promise kept on some Android versions only. + val legacy = excludes("backup_rules.xml", parent = null) + val cloud = excludes("data_extraction_rules.xml", parent = "cloud-backup") + val transfer = excludes("data_extraction_rules.xml", parent = "device-transfer") + assertTrue("backup_rules.xml $legacy vs cloud $cloud", legacy == cloud) + assertTrue("cloud $cloud vs device transfer $transfer", cloud == transfer) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt new file mode 100644 index 00000000..b36b8bd1 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/LegalBuildPropertyTest.kt @@ -0,0 +1,97 @@ +package com.lumenpearson.lessons + +import java.io.File +import java.net.URI +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The legal address the build is given, and the wire that gives it. + * + * `BuildPropertyReachTest` already fails when `LESSONS_LEGAL_BASE_URL` is read + * by the build and set by no workflow. What it cannot see is the rest of this + * property's contract, each half of which would be invisible until somebody + * tapped the first link of a fresh install: that the workflow passes the value + * its own «Resolve legal documents» step worked out rather than some other + * expression, that the default a local build falls back to is an https address + * that ends where the four files are, and that the folder the APK bundles is + * the folder the address names. + */ +class LegalBuildPropertyTest { + + private val root: File by lazy { + var directory: File? = File("").absoluteFile + while (directory != null) { + if (File(directory, "settings.gradle.kts").isFile) return@lazy directory.parentFile ?: directory + directory = directory.parentFile + } + error("Could not find the Gradle root from ${File("").absolutePath}") + } + + private val buildScript by lazy { File(root, "android/app/build.gradle.kts").readText() } + private val workflow by lazy { File(root, ".github/workflows/apk.yml").readText() } + + @Test + fun `the build reads the property under both of its names`() { + assertTrue( + buildScript.contains("""signingSecret("LESSONS_LEGAL_BASE_URL", "lessons.legal.baseUrl")"""), + ) + assertTrue(buildScript.contains("""buildConfigField("String", "LEGAL_BASE_URL"""")) + } + + @Test + fun `the default is an https address of this repository's docs legal`() { + val default = Regex("""val defaultLegalBaseUrl = "([^"]+)"""").find(buildScript)?.groupValues?.get(1) + assertTrue("app/build.gradle.kts no longer names its default legal address", default != null) + val uri = URI(checkNotNull(default)) + assertEquals("https", uri.scheme) + // blob/HEAD rather than a branch: GitHub resolves HEAD to the default + // branch, and an installed APK keeps its link long after a named branch + // is deleted. + assertTrue("the default must follow the default branch: $default", "/blob/HEAD/" in uri.path) + val folder = uri.path.substringAfter("/blob/HEAD/") + assertEquals("docs/legal", folder) + } + + @Test + fun `a value that is not https is refused by the build, not kept`() { + // The check itself runs in Gradle, which a unit test cannot start; what + // this holds is that the refusal is there and is a failure rather than + // a fallback to the default. + assertTrue(buildScript.contains("""uri.scheme == "https"""")) + val start = buildScript.indexOf("val legalBaseUrl") + assertTrue("legalBaseUrl is not declared", start >= 0) + val block = buildScript.substring(start, buildScript.indexOf("\n\n", start)) + assertTrue("an unusable address must stop the build: $block", "throw GradleException" in block) + } + + @Test + fun `the workflow passes what its resolve step worked out`() { + assertTrue("apk.yml has no step with id: legal", Regex("""(?m)^\s+id: legal\s*$""").containsMatchIn(workflow)) + assertTrue( + "the build step must pass steps.legal.outputs.url, or the fork's own address never reaches the APK", + Regex("""(?m)^\s+LESSONS_LEGAL_BASE_URL: \$\{\{ steps\.legal\.outputs\.url }}\s*$""") + .containsMatchIn(workflow), + ) + // The step runs before anything is compiled, so a bad variable fails in + // seconds rather than at the end of the build. + assertTrue( + "the legal step must come before the build", + workflow.indexOf("id: legal") < workflow.indexOf("LESSONS_LEGAL_BASE_URL: \${{"), + ) + } + + @Test + fun `the folder the APK bundles is the folder the address names`() { + assertTrue( + "app/build.gradle.kts must mount docs/legal as an asset folder, or an " + + "offline reader is told the document could not be opened", + buildScript.contains("""assets.srcDirs(rootProject.layout.projectDirectory.dir("../docs/legal"))"""), + ) + val folder = File(root, "docs/legal") + listOf("terms.ru.md", "terms.en.md", "privacy.ru.md", "privacy.en.md", "legal.json").forEach { name -> + assertTrue("docs/legal/$name is missing; the address and the APK both name it", File(folder, name).isFile) + } + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/StringEdgeSpaceTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/StringEdgeSpaceTest.kt new file mode 100644 index 00000000..3f4b60b0 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/StringEdgeSpaceTest.kt @@ -0,0 +1,61 @@ +package com.lumenpearson.lessons + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +/** + * No string relies on a space at its edge, because the build throws it away. + * + * aapt2 trims the leading and trailing whitespace of a `` unless it is + * quoted or escaped, so a sentence assembled from pieces with spaces at their + * joins ships with the words run together. That is how the about card said + * «по мотивамEssentials» in Russian and "afterEssentials" in English for as + * long as it existed (#155): the source looked right, every test that read the + * source agreed, and only the compiled APK was wrong. The answer is one + * template with a placeholder, which keeps the space inside the text where aapt2 + * leaves it alone; this holds that nobody reaches for the pieces again. + * + * Every module that ships strings, in every language folder, discovered rather + * than listed — the way `ResourceTranslationTest` finds them. + */ +class StringEdgeSpaceTest { + + @Test + fun `no string starts or ends with a plain space`() { + val folders = File("..").canonicalFile.walkTopDown() + .onEnter { it.name != "build" && !it.name.startsWith(".") } + .filter { it.isDirectory && it.name.matches(Regex("values(-[a-zA-Z-]+)?")) } + .filter { it.parentFile?.name == "res" && "/src/main/" in it.invariantSeparatorsPath } + .toList() + assertTrue("found no values folders from ${File("..").absolutePath}", folders.size >= 4) + + val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() + val offenders = folders.flatMap { folder -> + folder.listFiles().orEmpty().filter { it.name.endsWith(".xml") }.flatMap { file -> + val nodes = builder.parse(file).getElementsByTagName("string") + (0 until nodes.length).mapNotNull { index -> + val element = nodes.item(index) as Element + val text = element.textContent + // A quoted string keeps its spaces, so only a bare one counts. + val quoted = text.length >= 2 && text.startsWith('"') && text.endsWith('"') + val edged = text.startsWith(' ') || text.endsWith(' ') + if (edged && !quoted) { + "${folder.parentFile.parentFile.parentFile.parentFile.name}/" + + "${folder.name}/${file.name}: ${element.getAttribute("name")} = «$text»" + } else { + null + } + } + } + } + assertTrue( + "aapt2 trims these spaces, so the words either side of the join run " + + "together in the APK — use one template with a %1\$s placeholder:\n" + + offenders.joinToString("\n"), + offenders.isEmpty(), + ) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLineTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLineTest.kt new file mode 100644 index 00000000..d7c89fa6 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalAcceptanceLineTest.kt @@ -0,0 +1,125 @@ +package com.lumenpearson.lessons.ui.legal + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.TextLinkStyles +import androidx.test.core.app.ApplicationProvider +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.legal.LegalDocument +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The line under the first screen's button, as it ships. + * + * What it has to get right is small and entirely visible: the sentence a reader + * is told, word for word, with exactly the two document names as links, each + * opening its own document. The words are read from the shipped resources + * rather than typed here, so a translation that dropped a placeholder or a + * space fails in the language it broke. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp") +class LegalAcceptanceLineTest { + + @get:Rule val compose = createComposeRule() + + private val context get() = ApplicationProvider.getApplicationContext() + + private fun notice(onOpen: (LegalDocument) -> Unit = {}): AnnotatedString? = legalNoticeText( + template = context.getString(R.string.onboarding_legal_notice), + termsLabel = context.getString(R.string.onboarding_legal_terms), + privacyLabel = context.getString(R.string.onboarding_legal_privacy), + linkStyles = TextLinkStyles(), + onOpen = onOpen, + ) + + @Test + fun `the Russian sentence is the one the design gives`() { + assertEquals( + "Продолжая, вы принимаете Условия использования и Политику конфиденциальности", + notice()?.text, + ) + } + + @Test + @Config(qualifiers = "en-w411dp") + fun `the English sentence keeps its spaces and both links`() { + val text = checkNotNull(notice()) + assertEquals("By continuing, you accept the Terms of Use and the Privacy Policy", text.text) + assertEquals(listOf("Terms of Use", "Privacy Policy"), linkedWords(text)) + } + + @Test + fun `exactly the two document names are links`() { + val text = checkNotNull(notice()) + assertEquals(listOf("Условия использования", "Политику конфиденциальности"), linkedWords(text)) + } + + @Test + fun `each link opens its own document`() { + val opened = mutableListOf() + val text = checkNotNull(notice { opened += it }) + text.getLinkAnnotations(0, text.length).forEach { range -> + val link = range.item as LinkAnnotation.Clickable + checkNotNull(link.linkInteractionListener).onClick(link) + } + assertEquals(listOf(LegalDocument.TERMS, LegalDocument.PRIVACY), opened) + } + + @Test + fun `a template that lost a placeholder is refused rather than drawn half-linked`() { + // The template may be a reader's correction. One that dropped «%2$s» + // would otherwise tell somebody they accept a policy with no way to + // open it. + assertNull(legalNoticeText("Продолжая, вы принимаете %1\$s", "a", "b", TextLinkStyles()) {}) + assertNull(legalNoticeText("%1\$s и %1\$s", "a", "b", TextLinkStyles()) {}) + assertNull(legalNoticeText("%1\$s и %3\$s", "a", "b", TextLinkStyles()) {}) + } + + @Test + fun `a language may put the links in its own order`() { + val text = checkNotNull(legalNoticeText("%2\$s, then %1\$s", "terms", "privacy", TextLinkStyles()) {}) + assertEquals("privacy, then terms", text.text) + assertEquals(listOf("privacy", "terms"), linkedWords(text)) + } + + @Test + fun `the line is drawn, and says the whole sentence`() { + compose.setContent { + LessonsTheme { + LegalAcceptanceLine(onOpen = {}) + } + } + compose.onNodeWithText( + "Продолжая, вы принимаете Условия использования и Политику конфиденциальности", + ).assertIsDisplayed() + } + + @Test + fun `the design credit on the about card no longer runs into its link`() { + // #155: «по мотивам » lost its trailing space to aapt2 and the card said + // «по мотивамEssentials». One template keeps the space where it was typed. + val link = LinkAnnotation.Url("https://example.org") + val credit = linkedSentence( + context.getString(R.string.about_design_credit), + listOf(context.getString(R.string.about_design_credit_link) to link), + ) + assertEquals( + "Оформление, шрифт и компоненты — по мотивам Essentials, лицензия MIT.", + credit?.text, + ) + } + + private fun linkedWords(text: AnnotatedString): List = + text.getLinkAnnotations(0, text.length).map { text.text.substring(it.start, it.end) } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheetTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheetTest.kt new file mode 100644 index 00000000..6adc7ccf --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheetTest.kt @@ -0,0 +1,154 @@ +package com.lumenpearson.lessons.ui.legal + +import android.content.Context +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.test.core.app.ApplicationProvider +import com.lumenpearson.lessons.core.data.legal.BundledLegal +import com.lumenpearson.lessons.core.data.legal.LegalDocument +import com.lumenpearson.lessons.core.data.legal.LegalEdition +import com.lumenpearson.lessons.core.data.legal.LegalText +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.core.model.DocsBlock +import com.lumenpearson.lessons.core.model.DocsGuide +import com.lumenpearson.lessons.core.model.DocsGuidePage +import com.lumenpearson.lessons.core.model.DocsSpan +import java.time.LocalDate +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The copy of the terms and the policy the APK carries, and the sheet that + * shows it when the browser is not an answer. + * + * The first two tests are about the build rather than the screen: they read + * the documents through the app's own asset manager, which only works when + * `app/build.gradle.kts` really mounts `docs/legal/` — so an offline reader is + * never shown «не удалось открыть документ» because a source set was dropped. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp-h3000dp") +class LegalDocumentSheetTest { + + @get:Rule val compose = createComposeRule() + + private val context: Context get() = ApplicationProvider.getApplicationContext() + + @Before + fun holdTheClock() { + // The loader in the sheet is a perpetual animation; see AboutCardTest. + compose.mainClock.autoAdvance = false + } + + @Test + fun `the APK carries both documents in both languages`() { + LegalDocument.entries.forEach { document -> + listOf("ru", "en").forEach { language -> + val text = BundledLegal.read(context, document, language) + assertTrue("${document.slug}.$language.md is not in the APK's assets", text != null) + assertTrue( + "${document.slug}.$language.md parsed to too few sections", + (text?.guide?.pages?.size ?: 0) >= 5, + ) + } + } + } + + @Test + fun `the bundled copy names the edition it is`() { + val edition = BundledLegal.read(context, LegalDocument.PRIVACY, "ru")?.edition + assertTrue("legal.json is not in the APK's assets, or names no edition", edition != null) + assertTrue("an edition starts at 1", (edition?.edition ?: 0) >= 1) + } + + private val sample = LegalText( + guide = DocsGuide( + title = "Условия", + language = "ru", + pages = listOf( + DocsGuidePage( + id = "SCOPE", + title = "О чём этот документ", + label = "Охват", + summary = "", + blocks = listOf(DocsBlock.Paragraph(listOf(DocsSpan("Первый абзац.")))), + ), + DocsGuidePage( + id = "CONTACT", + title = "Контакты", + label = "Контакты", + summary = "", + blocks = listOf(DocsBlock.Paragraph(listOf(DocsSpan("Второй абзац.")))), + ), + ), + ), + edition = LegalEdition(1, LocalDate.of(2026, 9, 25)), + ) + + private fun show(load: LegalLoad, url: String?) { + compose.setContent { + LessonsTheme { + LegalDocumentBody(load = load, url = url) + } + } + repeat(4) { compose.mainClock.advanceTimeByFrame() } + } + + @Test + fun `every section is on one page, under its heading`() { + // A policy is read top to bottom; the guide's pager would hide eleven + // sections behind a swipe from somebody being asked to accept them. + show(LegalLoad.Ready(sample), url = null) + + compose.onNodeWithText("О чём этот документ").assertIsDisplayed() + compose.onNodeWithText("Первый абзац.").assertIsDisplayed() + compose.onNodeWithText("Контакты").assertIsDisplayed() + compose.onNodeWithText("Второй абзац.").assertIsDisplayed() + } + + @Test + fun `the edition and its date are said above the text`() { + show(LegalLoad.Ready(sample), url = null) + + compose.onNodeWithText("Редакция 1 от 25 сентября 2026", substring = true).assertIsDisplayed() + } + + @Test + fun `a sheet shown in place of the browser says so and offers the link`() { + show(LegalLoad.Ready(sample), url = "https://example.org/terms.ru.md") + + compose.onNodeWithText("Открыть актуальную редакцию").assertIsDisplayed() + compose.onNodeWithText("Это копия, встроенная в приложение", substring = true).assertIsDisplayed() + } + + @Test + fun `a build with no address does not offer a link it does not have`() { + show(LegalLoad.Ready(sample), url = null) + + compose.onAllNodesWithText("Открыть актуальную редакцию").assertCountEquals(0) + } + + @Test + fun `a missing document says so rather than drawing an empty policy`() { + show(LegalLoad.Missing, url = null) + + compose.onNodeWithText("Не удалось открыть документ.").assertIsDisplayed() + } + + @Test + fun `the browser is used only with an address and a network that reaches past the router`() { + assertEquals(LegalTarget.Web("https://a/b"), legalTarget("https://a/b", online = true)) + assertEquals(LegalTarget.Bundled, legalTarget("https://a/b", online = false)) + assertEquals(LegalTarget.Bundled, legalTarget(null, online = true)) + assertEquals(LegalTarget.Bundled, legalTarget(null, online = false)) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt index d8410b8c..7a167303 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/AboutCardTest.kt @@ -118,6 +118,25 @@ class AboutCardTest { assertShows("Essentials") } + @Test + fun `the terms and the privacy policy each have a row of their own`() { + // The full-size way to the two documents the first screen's small line + // links, for anybody who wants to read them again after onboarding. + show(ServerStatus.Ok(apiVersion = 1, schema = "0014")) + + assertShows("Условия использования") + assertShows("Политика конфиденциальности") + } + + @Test + fun `the design credit keeps the space before its link`() { + // #155: the words before the link were their own string, aapt2 trimmed + // its trailing space, and the card said «по мотивамEssentials». + show(ServerStatus.Ok(apiVersion = 1, schema = "0014")) + + assertShows("Оформление, шрифт и компоненты — по мотивам Essentials, лицензия MIT.") + } + @Test fun `a healthy server says so, and names what it is`() { show(ServerStatus.Ok(apiVersion = 1, schema = "0014")) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsLanguage.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsLanguage.kt new file mode 100644 index 00000000..f3411304 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsLanguage.kt @@ -0,0 +1,13 @@ +package com.lumenpearson.lessons.core.data.docs + +/** + * `ru` or `en`: a phone in any other language reads the English text. + * + * One rule for every document the app ships in two languages — the guide and + * the terms and privacy policy. It used to be private to the guide's + * repository, and a second copy of it for the legal texts would have been two + * rules the day a third language reached one of them: a reader would get the + * guide in one language and the policy they accepted in the other. + */ +internal fun docsLanguage(language: String): String = + if (language.lowercase().startsWith("ru")) "ru" else "en" diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsRepositoryImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsRepositoryImpl.kt index 597662e1..81d26412 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsRepositoryImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/docs/DocsRepositoryImpl.kt @@ -60,7 +60,7 @@ internal class DocsRepositoryImpl( private val gate = Mutex() override suspend fun load(language: String) { - val wanted = normalise(language) + val wanted = docsLanguage(language) gate.withLock { val current = mutableState.value.library if (current != null && current.guide.language == wanted) return @@ -72,7 +72,7 @@ internal class DocsRepositoryImpl( } override suspend fun refresh(language: String) { - val wanted = normalise(language) + val wanted = docsLanguage(language) gate.withLock { mutableState.value = mutableState.value.copy(refreshing = true) val outcome = withContext(Dispatchers.IO) { fetch(wanted) } @@ -206,10 +206,6 @@ internal class DocsRepositoryImpl( Log.w(TAG, "The documentation manifest did not parse", failure) }.getOrNull() - /** `ru` or `en`; a phone in any other language reads the English guide. */ - private fun normalise(language: String): String = - if (language.lowercase().startsWith("ru")) "ru" else "en" - private sealed interface Outcome { data object Unchanged : Outcome data class Fetched(val library: DocsLibrary) : Outcome diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocuments.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocuments.kt new file mode 100644 index 00000000..a5b19c6e --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocuments.kt @@ -0,0 +1,153 @@ +package com.lumenpearson.lessons.core.data.legal + +import android.content.Context +import android.util.Log +import com.lumenpearson.lessons.core.data.docs.DocsMarkdown +import com.lumenpearson.lessons.core.data.docs.docsLanguage +import com.lumenpearson.lessons.core.data.github.GithubApi +import com.lumenpearson.lessons.core.model.DocsGuide +import java.time.LocalDate +import kotlinx.serialization.Serializable + +/** + * The two texts a reader accepts by continuing past the first screen. + * + * @property slug the file's stem in `docs/legal/` and at the build's legal + * address — `terms.ru.md`, `privacy.en.md`. It is a file name rather than a + * label, so it is never translated. + */ +enum class LegalDocument(val slug: String) { + TERMS("terms"), + PRIVACY("privacy"), +} + +/** + * Which edition of the texts this APK carries, and from when it applies. + * + * Shown above the bundled copy because that copy may be older than the one at + * the link: an installed APK keeps the edition it was built with for as long as + * nobody updates it, and a reader comparing the two needs a number to compare. + */ +data class LegalEdition(val edition: Int, val effective: LocalDate) + +/** A bundled document, parsed, with the edition it belongs to when the manifest could say. */ +data class LegalText(val guide: DocsGuide, val edition: LegalEdition?) + +/** + * The address of [document] in [language] under the build's legal folder, or + * `null` when there is none worth opening. + * + * `null` for a blank folder and for anything but https. The Gradle build + * already refuses a non-https value, so the second check only matters to a + * caller that got [base] from somewhere else — and a policy opened over plain + * HTTP is a policy anybody on the café's network can rewrite before it is read. + */ +fun legalUrl(base: String, document: LegalDocument, language: String): String? { + val folder = base.trim().trimEnd('/') + if (!folder.startsWith("https://") || folder.length <= "https://".length) return null + return "$folder/${document.slug}.${docsLanguage(language)}.md" +} + +/** + * The shape of `docs/legal/legal.json`. + * + * Its own name rather than `manifest.json` because `docs/app/` and `docs/legal/` + * both land at the root of the APK's assets, and `DocsStore` opens + * `manifest.json` there for the guide: two files of one name in one folder is a + * build that ships whichever the merger happened to keep. + */ +@Serializable +internal data class LegalManifest( + val edition: Int = 0, + val effective: String = "", + val files: Map> = emptyMap(), +) + +/** `null` when [text] is not the manifest, or names no usable edition or date. */ +internal fun parseLegalManifest(text: String?): LegalManifest? { + if (text.isNullOrBlank()) return null + return runCatching { GithubApi.json.decodeFromString(text) }.getOrNull() +} + +/** + * The edition a manifest names, or `null` when it does not name a real one. + * + * A zero edition or an unreadable date is dropped rather than drawn, because the + * line it would produce — «Редакция 0 от …» — is a claim about a document that + * nobody made. + */ +internal fun LegalManifest.toEdition(): LegalEdition? { + if (edition < 1) return null + val date = runCatching { LocalDate.parse(effective) }.getOrNull() ?: return null + return LegalEdition(edition, date) +} + +/** + * The file [document] is in for [language]: the manifest's word when it has one, + * the convention when it does not. + * + * The convention is the same one [legalUrl] builds its address from, so the + * bundled copy and the published one cannot be two different files by accident. + */ +internal fun legalFileName(manifest: LegalManifest?, document: LegalDocument, language: String): String { + val lang = docsLanguage(language) + return manifest?.files?.get(document.slug)?.get(lang)?.takeIf { it.isNotBlank() } + ?: "${document.slug}.$lang.md" +} + +/** + * Reads a bundled legal text through [open], which answers a file's contents + * by name or `null`. + * + * `null` when the file is missing or parses to no sections: a sheet titled + * «Политика конфиденциальности» over an empty page would read as a policy that + * says nothing, which is worse than saying the document could not be opened. + */ +internal fun readLegal(open: (String) -> String?, document: LegalDocument, language: String): LegalText? { + val manifest = parseLegalManifest(open(MANIFEST)) + val lang = docsLanguage(language) + val markdown = open(legalFileName(manifest, document, lang))?.takeIf { it.isNotBlank() } ?: return null + val guide = DocsMarkdown.parse(markdown, lang) + if (guide.pages.isEmpty()) return null + return LegalText(guide = guide, edition = manifest?.toEdition()) +} + +/** + * The terms and the privacy policy as the APK carries them. + * + * An object with no state, like `DocsStore.bundledGuide` which it mirrors: an + * asset is read whole, once per opening of a sheet, and there is nothing to + * cache between two readers that a second read would not answer as quickly. + * Not a member of the container for the same reason — nothing here outlives a + * call. + * + * The files are `docs/legal/` itself, mounted as an asset folder by `:app`'s + * build, so there is one copy of each text in the repository and the APK's is + * that copy. + */ +object BundledLegal { + + /** Blocking; call it off the main thread. */ + fun read(context: Context, document: LegalDocument, language: String): LegalText? { + val assets = context.applicationContext.assets + return readLegal( + open = { name -> + runCatching { + assets.open(name).use { stream -> stream.readBytes().decodeToString() } + }.onFailure { failure -> + // Not fatal and not silent: it means the build stopped + // shipping docs/legal/, which the reader then sees as + // «не удалось открыть документ» and nothing else reports. + Log.w(TAG, "The APK carries no $name", failure) + }.getOrNull() + }, + document = document, + language = language, + ) + } + + private const val TAG = "Lessons" +} + +/** The manifest's name inside `docs/legal/` and at the asset root. */ +internal const val MANIFEST = "legal.json" diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocumentsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocumentsTest.kt new file mode 100644 index 00000000..32e22cd4 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalDocumentsTest.kt @@ -0,0 +1,254 @@ +package com.lumenpearson.lessons.core.data.legal + +import com.lumenpearson.lessons.core.data.docs.DocsMarkdown +import com.lumenpearson.lessons.core.model.DocsBlock +import com.lumenpearson.lessons.core.model.DocsGuide +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The terms of use and the privacy policy, read out of the repository. + * + * `DocsGuideParityTest`'s job for the second pair of texts the app ships: the + * files in `docs/legal/` are the bytes the APK carries and the pages the + * published link opens, so a fixture would pass while the shipped text was + * broken. What is at stake is worse than a guide page in one language only — + * the line on the first screen tells a reader they accept these two texts, and + * a section that exists in Russian and not in English is a policy that says + * different things depending on the phone's language. + */ +class LegalDocumentsTest { + + private val folder: File = repositoryRoot().resolve("docs/legal") + + private fun read(document: LegalDocument, language: String): DocsGuide { + val file = folder.resolve("${document.slug}.$language.md") + assertTrue("${file.path} is missing — the app ships it", file.isFile) + return DocsMarkdown.parse(file.readText(), language) + } + + private val all: List>> by lazy { + LegalDocument.entries.map { it to (read(it, "ru") to read(it, "en")) } + } + + @Test + fun `every document exists in both languages and parses into sections`() { + // A silent pass here would make every test below vacuous: two empty + // documents agree about everything. + all.forEach { (document, pair) -> + val (ru, en) = pair + assertTrue("${document.slug}.ru.md has too few sections", ru.pages.size >= 5) + assertTrue("${document.slug}.ru.md has no title", ru.title.isNotBlank()) + assertTrue("${document.slug}.en.md has no title", en.title.isNotBlank()) + } + } + + @Test + fun `the sections are the same, in the same order`() { + all.forEach { (document, pair) -> + val (ru, en) = pair + assertEquals( + "${document.slug}: section ids are not translated, and a section " + + "one language has and the other lacks is a different policy", + ru.pages.map { it.id }, + en.pages.map { it.id }, + ) + } + } + + @Test + fun `every section id is written in the file rather than guessed from its heading`() { + // A section with no metadata comment directly under its heading gets + // the heading upper-cased as its id, which differs between the + // languages. Read from the raw lines, because the parsed id cannot tell + // a written «AVAILABILITY» from one guessed from «Availability». + LegalDocument.entries.forEach { document -> + listOf("ru", "en").forEach { lang -> + val lines = folder.resolve("${document.slug}.$lang.md").readLines() + lines.forEachIndexed { index, line -> + if (!line.startsWith("## ")) return@forEachIndexed + val next = lines.getOrNull(index + 1).orEmpty().trim() + assertTrue( + "${document.slug}.$lang.md: «$line» is not followed by ``", + next.startsWith(""), + ) + } + } + } + } + + @Test + fun `every section says something in both languages`() { + val empty = all.flatMap { (document, pair) -> + (pair.first.pages + pair.second.pages) + .filter { it.title.isBlank() || it.blocks.isEmpty() } + .map { "${document.slug}: ${it.id}" } + } + assertTrue("sections with no heading or no text: $empty", empty.isEmpty()) + } + + @Test + fun `the two languages are built from the same blocks`() { + all.forEach { (document, pair) -> + pair.first.pages.zip(pair.second.pages).forEach { (ru, en) -> + assertEquals( + "${document.slug} «${ru.id}» is built differently in the two languages", + ru.blocks.map(::shapeOf), + en.blocks.map(::shapeOf), + ) + } + } + } + + @Test + fun `no document smuggles markdown the parser does not understand`() { + // The same marks DocsGuideParityTest refuses for the guide, for the same + // reason: what is not understood is drawn as its characters — a table + // of the data the server keeps would arrive as a wall of pipes. + val unsupported = listOf("![", " unsupported.any(line::contains) } + assertTrue( + "the parser understands paragraphs, lists, steps, notes, bold, code and " + + "links, and nothing else:\n" + offenders.joinToString("\n"), + offenders.isEmpty(), + ) + } + + @Test + fun `every link is absolute https`() { + // A relative link works on GitHub and is dead in the copy the APK + // carries, which is the copy an offline reader is shown. + val links = all.flatMap { (document, pair) -> + (pair.first.pages + pair.second.pages).flatMap { page -> + page.blocks.flatMap(::spansOf).mapNotNull { it.link }.map { document.slug to it } + } + } + assertTrue("the documents link nothing, so this test proves nothing", links.isNotEmpty()) + val bad = links.filterNot { (_, link) -> link.startsWith("https://") } + assertTrue("links a reader cannot follow from the app: $bad", bad.isEmpty()) + } + + @Test + fun `no template marker is left`() { + // A fork fills these in; a marker left behind is drawn on screen, + // inside the text a reader is told they accept. + val markers = listOf("{{", "TODO", "⟨", "[заполн", "{OPERATOR}", "{CONTACT}") + val raw = LegalDocument.entries.flatMap { document -> + listOf("ru", "en").map { lang -> + val name = "${document.slug}.$lang.md" + name to folder.resolve(name).readText() + } + } + val left = raw.flatMap { (name, text) -> + // Comments are for whoever opens the file and are not drawn; the + // FORK notes in them may name the fields a fork fills. + val drawn = text.replace(Regex("(?s)"), "") + markers.filter(drawn::contains).map { "$name: $it" } + } + assertTrue("template markers in the shipped text: $left", left.isEmpty()) + } + + @Test + fun `the manifest names every file and an edition and an effective date`() { + val file = folder.resolve(MANIFEST) + assertTrue("${file.path} is missing", file.isFile) + val manifest = checkNotNull(parseLegalManifest(file.readText())) { "legal.json does not parse" } + val edition = manifest.toEdition() + assertTrue("the manifest names no usable edition and date: $manifest", edition != null) + LegalDocument.entries.forEach { document -> + listOf("ru", "en").forEach { lang -> + val name = manifest.files[document.slug]?.get(lang) + assertEquals( + "the manifest must name ${document.slug}.$lang.md — the build's " + + "address is built from that convention, so a different name " + + "would publish one file and bundle another", + "${document.slug}.$lang.md", + name, + ) + } + } + } + + @Test + fun `the reader opens every bundled document the way the app does`() { + LegalDocument.entries.forEach { document -> + listOf("ru-RU", "en", "uk").forEach { language -> + val text = readLegal( + open = { name -> folder.resolve(name).takeIf { it.isFile }?.readText() }, + document = document, + language = language, + ) + assertTrue("${document.slug} in $language did not open", text != null) + assertTrue("${document.slug} in $language has no edition", text?.edition != null) + } + } + } + + /** + * Every folder mounted at the root of the APK's assets, with no name in + * two of them. + * + * `docs/app/` (the guide, from `:core:data`), `docs/legal/` (from `:app`) + * and the region catalog all land in one flat folder, and `DocsStore` opens + * `manifest.json` there. Whichever of two same-named files the merger kept, + * one reader would be handed the other's file — which is why this folder's + * manifest is `legal.json`. + */ + @Test + fun `no file in docs legal has the name of one in another asset folder`() { + val root = repositoryRoot() + val folders = listOf("docs/app", "docs/legal", "server/app/catalog/data") + .map(root::resolve) + .filter(File::isDirectory) + assertTrue("docs/app and docs/legal must both exist", folders.size >= 2) + val owners = mutableMapOf() + val clashes = mutableListOf() + folders.forEach { dir -> + dir.listFiles().orEmpty().filter(File::isFile).forEach { file -> + val previous = owners.put(file.name, dir.path) + if (previous != null) clashes += "${file.name}: $previous and ${dir.path}" + } + } + assertTrue("two asset folders ship a file of one name: $clashes", clashes.isEmpty()) + } + + private fun lines(): List> = all.flatMap { (document, pair) -> + (pair.first.pages + pair.second.pages).flatMap { page -> + page.blocks.flatMap(::textOf).map { "${document.slug}/${page.id}" to it } + } + } + + private fun shapeOf(block: DocsBlock): String = when (block) { + is DocsBlock.Paragraph -> "paragraph" + is DocsBlock.Points -> "points(${block.items.size})" + is DocsBlock.Note -> "note" + is DocsBlock.Step -> "step(${block.number})" + } + + private fun spansOf(block: DocsBlock) = when (block) { + is DocsBlock.Paragraph -> block.spans + is DocsBlock.Note -> block.spans + is DocsBlock.Points -> block.items.flatMap { it.spans } + is DocsBlock.Step -> block.title + block.text + } + + private fun textOf(block: DocsBlock): List = when (block) { + is DocsBlock.Paragraph -> listOf(block.spans.joinToString("") { it.text }) + is DocsBlock.Note -> listOf(block.spans.joinToString("") { it.text }) + is DocsBlock.Points -> block.items.map { line -> line.spans.joinToString("") { it.text } } + is DocsBlock.Step -> listOf( + block.title.joinToString("") { it.text }, + block.text.joinToString("") { it.text }, + ) + } + + /** The repository root: the parent of the Gradle root, found by climbing. */ + private fun repositoryRoot(): File { + val start = File(".").absoluteFile + val gradleRoot: File? = generateSequence(start) { it.parentFile } + .firstOrNull { File(it, "settings.gradle.kts").isFile } + return checkNotNull(gradleRoot?.parentFile) { "no settings.gradle.kts above ${start.path}" } + } +} diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalLinksTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalLinksTest.kt new file mode 100644 index 00000000..6904c606 --- /dev/null +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/legal/LegalLinksTest.kt @@ -0,0 +1,105 @@ +package com.lumenpearson.lessons.core.data.legal + +import java.time.LocalDate +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * Where a legal link goes, and what the bundled reader makes of what it finds. + * + * The address is built from two things nobody on the phone chose — the build's + * folder and the phone's language — so every way the two can be odd is asked + * here rather than discovered on the first screen of an install. + */ +class LegalLinksTest { + + private val base = "https://github.com/lumenpearson/lessons/blob/HEAD/docs/legal" + + @Test + fun `a build with no folder links nothing`() { + assertNull(legalUrl("", LegalDocument.TERMS, "ru")) + assertNull(legalUrl(" ", LegalDocument.PRIVACY, "en")) + } + + @Test + fun `a folder that is not https links nothing`() { + // Gradle refuses one already; this is for a caller that got the folder + // from anywhere else. A policy fetched in the clear is one the café's + // network can rewrite before it is read. + assertNull(legalUrl("http://example.org/legal", LegalDocument.TERMS, "ru")) + assertNull(legalUrl("https://", LegalDocument.TERMS, "ru")) + } + + @Test + fun `a trailing slash does not become a double one`() { + assertEquals("$base/terms.ru.md", legalUrl("$base/", LegalDocument.TERMS, "ru")) + } + + @Test + fun `the slug and the language name the file`() { + assertEquals("$base/terms.ru.md", legalUrl(base, LegalDocument.TERMS, "ru-RU")) + assertEquals("$base/privacy.en.md", legalUrl(base, LegalDocument.PRIVACY, "en")) + } + + @Test + fun `a language with no text of its own reads the English one`() { + // Ukrainian is the case worth naming: close enough to Russian that a + // guess might pick it, and not the language the phone asked for. + assertEquals("$base/privacy.en.md", legalUrl(base, LegalDocument.PRIVACY, "uk")) + assertEquals("$base/terms.ru.md", legalUrl(base, LegalDocument.TERMS, "RU")) + } + + @Test + fun `a manifest that does not parse is no manifest`() { + assertNull(parseLegalManifest(null)) + assertNull(parseLegalManifest("")) + assertNull(parseLegalManifest("not json")) + } + + @Test + fun `an edition of zero or an unreadable date is not drawn`() { + // «Редакция 0 от …» would be a claim about a document nobody made. + assertNull(LegalManifest(edition = 0, effective = "2026-09-25").toEdition()) + assertNull(LegalManifest(edition = 1, effective = "25.09.2026").toEdition()) + assertEquals( + LegalEdition(2, LocalDate.of(2026, 9, 25)), + LegalManifest(edition = 2, effective = "2026-09-25").toEdition(), + ) + } + + @Test + fun `a file the manifest does not name falls back to the convention the link uses`() { + assertEquals("terms.ru.md", legalFileName(null, LegalDocument.TERMS, "ru")) + val renamed = LegalManifest(files = mapOf("privacy" to mapOf("en" to "policy.en.md"))) + assertEquals("policy.en.md", legalFileName(renamed, LegalDocument.PRIVACY, "en-GB")) + assertEquals("privacy.ru.md", legalFileName(renamed, LegalDocument.PRIVACY, "ru")) + } + + @Test + fun `a missing document is missing rather than an empty page`() { + assertNull(readLegal(open = { null }, document = LegalDocument.TERMS, language = "ru")) + // Text that parses to no sections: a sheet titled «Условия + // использования» over nothing would read as terms that say nothing. + assertNull( + readLegal( + open = { name -> if (name == MANIFEST) null else "# Только заголовок\n\nи ни одного раздела" }, + document = LegalDocument.TERMS, + language = "ru", + ), + ) + } + + @Test + fun `a document opens without its manifest, with no edition to show`() { + val text = readLegal( + open = { name -> + if (name == "privacy.en.md") "# Privacy\n\n## Who\n\n\nUs." else null + }, + document = LegalDocument.PRIVACY, + language = "en", + ) + assertEquals(listOf("WHO"), text?.guide?.pages?.map { it.id }) + assertNull(text?.edition) + } +} diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index 6c6123c0..0faa8f23 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -33,7 +33,7 @@ This text describes what the app Lessons («Дневник» in Russian), its se You type the server's address into the app yourself. If it leads to a server somebody else started, whoever started it is responsible for the data on that server and in its bot, and their own policy should describe it. ## What is kept on the phone - + - For each class you have joined: an access key, and the names of the class and the school. - A copy of the class timetable, events and homework, teachers' names included, so that the app and the widget work offline. @@ -41,7 +41,7 @@ You type the server's address into the app yourself. If it leads to a server som - The server's address, the app's settings and, if you signed in to GitHub from the app, the GitHub key and your account name there. - Crash reports, only if you turned them on: up to five files with the phone's model, the Android and app versions, a description of the error and the app's latest log lines. -The keys, the login and the settings sit in the app's settings files **unencrypted**. The databases and the settings files are excluded from Google backup and from transfer to a new phone. Crash reports are not excluded: if you turned them on, they may end up in the phone's backup (this has not been checked on a device). +The keys, the login and the settings sit in the app's settings files **unencrypted**. The databases, the settings files and the crash reports are excluded from Google backup and from transfer to a new phone: a report stays on this phone until you send it yourself. That crash reports really are kept out of the backup has not yet been checked on a device. The phone never stores the diary password. The session the diary hands out after sign-in is held only in memory, never written down, and forgotten as soon as the phone has handed it to the server or the sign-in is abandoned. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index 1abe6ffe..55e1a72c 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -54,7 +54,7 @@ Адрес сервера вы вводите в приложении сами. Если он ведёт на сервер, который запустил кто-то другой, за данные на том сервере и в его боте отвечает тот, кто его запустил, и описывать их должна его политика. ## Что хранится на телефоне - + - Для каждого класса, к которому вы подключились, — ключ доступа, название класса и школы. - Копия расписания класса, событий и заданий, включая имена учителей, — чтобы приложение и виджет работали без сети. @@ -62,7 +62,7 @@ - Адрес сервера, настройки приложения и, если вы входили в GitHub из приложения, ключ GitHub и имя вашей учётной записи там. - Отчёты о сбоях — только если вы их включили: до пяти файлов с моделью телефона, версиями Android и приложения, описанием ошибки и последними записями о работе приложения. -Ключи, логин и настройки лежат в файлах настроек приложения **без шифрования**. Базы данных и файлы настроек исключены из резервной копии Google и из переноса на новый телефон. Отчёты о сбоях не исключены: если вы их включили, они могут попасть в резервную копию телефона (на устройстве это не проверялось). +Ключи, логин и настройки лежат в файлах настроек приложения **без шифрования**. Базы данных, файлы настроек и отчёты о сбоях исключены из резервной копии Google и из переноса на новый телефон: отчёт остаётся на этом телефоне, пока вы сами его не отправите. Что отчёты о сбоях действительно не попадают в копию, на устройстве пока не проверялось. Пароль от дневника телефон не сохраняет нигде. Сессию, которую дневник выдаёт после входа, телефон держит только в памяти, не записывая, и забывает, как только передал её серверу или вход отменён. From ba9170cf69abbf8cec13c2755621f319bed86db9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 18:11:00 +0000 Subject: [PATCH 17/30] Run each CI job whenever a file its tests read changes, not only its own folder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "What changed" filter decides which halves run from the paths a push touched, and four server tests already on main read documents outside `server/`: `docs/deploy.md` is compared with the settings by test_deployment_config, test_database_url and test_roles, and `docs/build.md` with `.env.example` by test_env_example. A commit touching only one of those documents ran nothing and came back green (#159) — the failure `docs/app/` once had, which the Android case already carries a comment about. This branch widened the gap. `docs/diaries.md` and `docs/diaries/*` feed test_region_catalog and test_netschool_mapper; `:app` bundles `docs/legal/`; and the region catalog and the protocol vectors live under `server/` but are Android inputs — the catalog is the phone's allow-list of diary hosts, bundled in place, the vectors are DiaryProtocolVectorsTest's resource — so an edit to either ran the server job alone. Both cases now name every file their tests read, with the reason beside them. Closes #159 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .github/workflows/ci.yml | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1d2ae75..d28672c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,10 +86,25 @@ jobs: # — which is how the Russian guide grows a page the English one # does not have, and an English reader gets a toolbar with a # different number of buttons and nothing logged. - android/*|docs/app/*|.github/workflows/*) android=true ;; + # `docs/legal/` is the same case: `:app` packages it as assets + # and `LegalDocumentsTest` holds the two languages level. The + # region catalog and the protocol vectors live under `server/` + # but are Android inputs too — the catalog is the phone's + # allow-list of diary hosts, bundled in place, and the vectors + # are `DiaryProtocolVectorsTest`'s resource — so an edit to + # either must run both halves, not only the server's. + android/*|docs/app/*|docs/legal/*|server/app/catalog/data/*|server/tests/vectors/*|.github/workflows/*) android=true ;; esac case "$file" in - server/*|api/*|requirements.txt|.github/workflows/*) server=true ;; + # Server tests read documents too, and a commit touching only one + # of them used to run nothing (#159): `docs/deploy.md` and + # `docs/build.md` are compared with the settings and `.env.example` + # (test_deployment_config, test_database_url, test_roles, + # test_env_example), `docs/diaries/regions.md` is the region + # catalog's input and `docs/diaries.md` its table + # (test_region_catalog), `docs/diaries/netschool.md` is quoted by + # test_netschool_mapper. + server/*|api/*|requirements.txt|docs/deploy.md|docs/build.md|docs/diaries.md|docs/diaries/*|.github/workflows/*) server=true ;; esac done <<< "$files" From c032ff2193cbc0550542730c4eee0de6007709d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 19:25:06 +0000 Subject: [PATCH 18/30] Let a family in through its own school's diary at the first run, and give a diary-only phone a home of its own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The screen half of #141, on top of the data layer in b19e6b2. The first run (ui/onboarding): - «Продолжить» on the first screen, with «Продолжая, вы принимаете Условия использования и Политику конфиденциальности» under it, always drawn. - After the introduction and the permissions, two ways in: the class code, as today (the real JoinScreen), or your own school's diary. That path is REGION (all 89 regions searched on every keystroke from the bundled catalog; a school name asks the server's directory after a pause and answers with the regions it may be in; «Школа № 5» is too common and asks for the region instead) → SCHOOL (for «Сетевой город», searched on the region's own server) → PROVIDER (the region's systems, the recommended one highlighted, with «Почему?» keyed by the catalog's reason codes; ТОР and the three Госуслуги-only regions open the official site; a system the app cannot read says so and offers the class code) → SIGN_IN (a card names the host the password goes to; the password lives only in the form, the diary's session only in a plain field of the step, never in SavedStateHandle) → IMPORT (an animated wavy progress bar over the import's weighted phases, a pupil chooser, resume from the phase that failed) → SUMMARY (the main settings, the class if any, the pupil). - The flow is a saved path of steps (OnboardingFlow, pure functions); the shell is held on the flow through a join or a registration and released on finish. - The server address is asked where it is first needed; no default server is promised any more — the join screen, settings and ServerUrlSheet no longer say «По умолчанию — сервер класса» (#154, app half), and the comments describe the flow as it is (#157, code half). The shell (navigation, settings, ui/diary): - A pure gate over the shell mode: no class and no diary → the first run; a class → the timetable home; a diary and no class → the diary as the home, with settings that keep «Дневник» and «Выйти из дневника» (#151). A cold start settles the mode once before the gate first reads. - Periodic class sync is armed only in class mode (#152): LessonsApplication collects the shell mode's arming instead of scheduling on every settings emission. - Every diary failure has its own words through one mapping, DiaryProblemText: too many attempts, a switched-off diary, a diary that refuses our server, a timeout, each naming the host where it has one; «Повторить» only where a retry can help (#153, screen half). - The diary draws what the phone saved first, keeps it when the diary cannot be reached and says when it was saved; the one unprompted diary read is the refresh when the app comes to the foreground in diary mode. - The sign-in texts no longer say the password reaches our server or travels in the clear over an http:// server — with native sign-in it goes over https to the diary only; the network-security comment says what does cross an http server (the session and the bearers). - LessonsWavyProgress is public in :core:designsystem; DiaryZone is gone and every diary date is taken in the diary's own zone. Two things r11 had listed were checked against main before this commit and do not reproduce there (the first-run acknowledgement's promise, and the motion setting during the introduction); the new flow honours LocalMotion anyway. Gates: `./gradlew test` 1350 JVM tests (1236 before), `assembleDebug` and `assembleRelease` green; no new Russian in Kotlin. Not covered: nothing composes LessonsApp in a test, so the gate, the hold through a join, the swap to the right home and the resume after process death are covered by the pure rules and the view models only. Nothing has run on a device or against a live diary: not the handoffs, not the import with real timings, not TalkBack. The in-app guide and docs/design.md still describe the old first run; they are the documentation's to fix, and #154 and #157 stay open until they are. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .../lessons/LessonsApplication.kt | 68 ++- .../com/lumenpearson/lessons/MainActivity.kt | 2 +- .../lessons/navigation/LessonsApp.kt | 212 +++++-- .../lessons/navigation/RootGate.kt | 40 ++ .../lessons/navigation/ShellHome.kt | 34 ++ .../lessons/ui/AppShellViewModel.kt | 76 ++- .../lessons/ui/common/OpenLink.kt | 27 + .../lessons/ui/common/ServerUrlSheet.kt | 21 +- .../lessons/ui/diary/DiaryAccountPage.kt | 172 ++++++ .../lessons/ui/diary/DiaryCatalog.kt | 169 ++++++ .../lessons/ui/diary/DiaryCredentialFields.kt | 166 ++++++ .../lessons/ui/diary/DiaryPickerPage.kt | 459 +++++++++++++++ .../lessons/ui/diary/DiaryPresentation.kt | 71 +-- .../lessons/ui/diary/DiaryProblemText.kt | 148 +++++ .../lessons/ui/diary/DiaryScreen.kt | 173 ++++-- .../lessons/ui/diary/DiarySignInScreen.kt | 236 ++++---- .../lessons/ui/diary/DiaryViewModel.kt | 513 +++++++++++++---- .../lessons/ui/join/JoinScreen.kt | 41 +- .../lessons/ui/join/JoinViewModel.kt | 43 +- .../lessons/ui/legal/LegalDocumentSheet.kt | 1 + .../lessons/ui/legal/LegalOpener.kt | 19 +- .../lessons/ui/onboarding/ImportPage.kt | 226 ++++++++ .../lessons/ui/onboarding/ImportRunner.kt | 181 ++++++ .../ui/onboarding/OnboardingCatalog.kt | 394 +++++++++++++ .../lessons/ui/onboarding/OnboardingFlow.kt | 396 +++++++++++++ .../lessons/ui/onboarding/OnboardingHero.kt | 226 +++++--- .../lessons/ui/onboarding/OnboardingParts.kt | 128 +++-- .../lessons/ui/onboarding/OnboardingRows.kt | 178 ++++++ .../lessons/ui/onboarding/OnboardingScreen.kt | 244 ++++---- .../ui/onboarding/OnboardingViewModel.kt | 543 ++++++++++++++++++ .../lessons/ui/onboarding/ProviderStep.kt | 401 +++++++++++++ .../lessons/ui/onboarding/RegionFinder.kt | 159 +++++ .../lessons/ui/onboarding/RegionStep.kt | 326 +++++++++++ .../lessons/ui/onboarding/SchoolFinder.kt | 95 +++ .../lessons/ui/onboarding/SignInPage.kt | 262 +++++++++ .../lessons/ui/onboarding/SignInStep.kt | 186 ++++++ .../lessons/ui/onboarding/SummaryPage.kt | 176 ++++++ .../lessons/ui/onboarding/WayInStep.kt | 144 +++++ .../lessons/ui/settings/SettingsScreen.kt | 172 ++++-- .../lessons/ui/settings/SettingsViewModel.kt | 10 - .../lessons/ui/translate/TranslationXml.kt | 1 + .../app/src/main/res/values-en/strings.xml | 13 +- .../src/main/res/values-en/strings_diary.xml | 78 ++- .../main/res/values-en/strings_onboarding.xml | 179 ++++++ android/app/src/main/res/values/strings.xml | 13 +- .../app/src/main/res/values/strings_diary.xml | 84 ++- .../main/res/values/strings_onboarding.xml | 218 +++++++ .../main/res/xml/network_security_config.xml | 34 +- .../lumenpearson/lessons/DeviceClockTest.kt | 6 +- .../lumenpearson/lessons/SyncArmingTest.kt | 98 ++++ .../lessons/navigation/RootGateTest.kt | 69 +++ .../lessons/ui/AppShellLanguageTest.kt | 13 +- .../lessons/ui/AppShellViewModelTest.kt | 119 ++++ .../lessons/ui/diary/DiaryCatalogTest.kt | 96 ++++ .../lessons/ui/diary/DiaryHomeScreenTest.kt | 138 +++++ .../lessons/ui/diary/DiaryOfflineSeedTest.kt | 249 ++++++++ .../ui/diary/DiaryPickerViewModelTest.kt | 132 +++++ .../lessons/ui/diary/DiaryPresentationTest.kt | 29 +- .../lessons/ui/diary/DiaryProblemTextTest.kt | 148 +++++ .../ui/diary/DiarySignInOutcomeTest.kt | 77 ++- .../lessons/ui/diary/FakeDiaryCache.kt | 69 +++ .../lessons/ui/diary/FakeDiaryRepository.kt | 25 +- .../lessons/ui/join/JoinErrorTest.kt | 18 + .../lessons/ui/join/JoinErrorTextTest.kt | 9 + .../ui/onboarding/OnboardingCatalogTest.kt | 190 ++++++ .../ui/onboarding/OnboardingFlowTest.kt | 194 +++++++ .../ui/onboarding/OnboardingPromisesTest.kt | 112 ++++ .../ui/onboarding/OnboardingStepsTest.kt | 203 +++++++ .../ui/onboarding/OnboardingTestSupport.kt | 191 ++++++ .../ui/onboarding/OnboardingTextTest.kt | 127 ++++ .../ui/onboarding/OnboardingViewModelTest.kt | 339 +++++++++++ .../ui/settings/SettingsSectionListingTest.kt | 78 +++ .../lessons/core/data/di/SessionEffects.kt | 25 +- .../designsystem/component/StateHeroCard.kt | 28 +- .../designsystem/component/WavyProgress.kt | 97 ++++ 75 files changed, 9759 insertions(+), 878 deletions(-) create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/RootGate.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellHome.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/OpenLink.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalog.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlow.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingRows.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt create mode 100644 android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/WayInStep.kt create mode 100644 android/app/src/main/res/values-en/strings_onboarding.xml create mode 100644 android/app/src/main/res/values/strings_onboarding.xml create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/SyncArmingTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/RootGateTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellViewModelTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalogTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOfflineSeedTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerViewModelTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryCache.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlowTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSectionListingTest.kt create mode 100644 android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/WavyProgress.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt index 9c41468d..719b2251 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt @@ -3,12 +3,12 @@ package com.lumenpearson.lessons import android.app.Application import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.notifications.SchoolAlerts +import com.lumenpearson.lessons.core.data.repository.SyncArming import com.lumenpearson.lessons.core.data.sync.SyncScheduler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch /** @@ -20,17 +20,23 @@ import kotlinx.coroutines.launch * no Hilt in this project — the widget and the sync worker are woken by the * system with no injection point of their own, so a plain object graph that * any entry point can read is simpler and honest about its lifetime. - * 2. Background sync has to be (re)scheduled from a place that runs on every - * cold start, otherwise a user who changes the interval and never opens the - * settings screen again keeps the old cadence forever. The notification - * alarm is re-armed here for the same reason, and because a missed boot - * broadcast should cost one launch rather than a reinstall. + * 2. Background sync has to be armed or disarmed from a place that runs on + * every cold start, otherwise a user who changes the interval and never + * opens the settings screen again keeps the old cadence forever. The + * notification alarm is re-armed here for the same reason, and because a + * missed boot broadcast should cost one launch rather than a reinstall. + * + * What it does **not** do is read the diary. The diary is refreshed only while + * somebody is looking at it — `HomeShell`'s start effect, in the diary mode — + * and a refresh from here would run on every widget update and every alarm + * that wakes the process, which is a phone reading a child's marks with nobody + * holding it, and on the server an activity that keeps a session alive for ever. */ class LessonsApplication : Application() { /** * Process-scoped scope. It is never cancelled because the only thing running - * in it is the settings observer below, which must live exactly as long as + * in it is the arming collector below, which must live exactly as long as * the process does. */ private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) @@ -38,7 +44,7 @@ class LessonsApplication : Application() { override fun onCreate() { super.onCreate() Graph.init(this, githubClientId = BuildConfig.GITHUB_CLIENT_ID) - observeSyncInterval() + observeSyncArming() // Off the main thread: it reads the cached timetable to work out what to // arm for, and Application.onCreate is on the critical path of every // cold start, including the one a widget update triggers. @@ -46,21 +52,49 @@ class LessonsApplication : Application() { } /** - * Keeps the WorkManager cadence in step with the user's preference. + * Keeps the WorkManager cadence in step with the stored mode and interval. + * + * It used to follow the interval alone, and so it armed the worker on the + * first emission of every cold start whatever was stored: a phone that had + * left its last class — whose sign-out had just cancelled the worker — was + * woken every fifteen minutes again from its next launch on, for a run that + * found no class and returned (#152). `shellMode.syncArming` is the mode and + * the interval read from one preferences emission, so the answer here is the + * same rule `SessionEffects` acts on when a session changes, and the two + * cannot disagree about a phone in no class. * * Collecting instead of reading once means the settings screen only has to * write the new interval; rescheduling is this class's job, which keeps * [com.lumenpearson.lessons.ui.settings.SettingsViewModel] free of any * Android scheduling concern. */ - private fun observeSyncInterval() { + private fun observeSyncArming() { applicationScope.launch { - Graph.container.settingsRepository.settings - .map { it.syncIntervalMinutes } - .distinctUntilChanged() - .collect { intervalMinutes -> - SyncScheduler.schedulePeriodic(this@LessonsApplication, intervalMinutes) - } + Graph.container.shellMode.syncArming.driveSyncScheduler( + schedule = { minutes -> SyncScheduler.schedulePeriodic(this@LessonsApplication, minutes) }, + cancel = { SyncScheduler.cancelPeriodic(this@LessonsApplication) }, + ) + } + } +} + +/** + * Carries each [SyncArming] out, one call per emission: armed installs the + * periodic worker at its interval, disarmed cancels it. + * + * Cancelling on every disarmed emission rather than only on a change is + * deliberate — `cancelPeriodic` on nothing is a no-op, and the one emission + * that matters most is the first after a cold start, where there is no + * «before» to compare with. + */ +internal suspend fun Flow.driveSyncScheduler( + schedule: (intervalMinutes: Int) -> Unit, + cancel: () -> Unit, +) { + collect { arming -> + when (arming) { + is SyncArming.Armed -> schedule(arming.intervalMinutes) + SyncArming.Disarmed -> cancel() } } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/MainActivity.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/MainActivity.kt index 977a64db..69f65891 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/MainActivity.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/MainActivity.kt @@ -199,7 +199,7 @@ class MainActivity : ComponentActivity() { // block a proofreader cannot fix. CorrectionHost { LessonsApp( - signedIn = shell.signedIn, + shell = shell.shell, settings = shell.settings, openDate = openDate, onDateOpened = { pendingDate.value = null }, diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt index 989510e8..9651db1a 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/LessonsApp.kt @@ -38,6 +38,7 @@ import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -59,10 +60,14 @@ import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.compose.ui.text.intl.Locale +import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellState import com.lumenpearson.lessons.core.designsystem.component.LessonsFloatingToolbar import com.lumenpearson.lessons.core.designsystem.component.LessonsLoadingIndicator import com.lumenpearson.lessons.core.designsystem.component.ToolbarAction @@ -91,12 +96,16 @@ import com.lumenpearson.lessons.core.designsystem.theme.appSlideMotionBlur import com.lumenpearson.lessons.core.model.HomeTab import com.lumenpearson.lessons.ui.admin.isClassManager import com.lumenpearson.lessons.ui.debug.DebugSheet +import com.lumenpearson.lessons.ui.diary.DiaryScreen +import com.lumenpearson.lessons.ui.diary.DiaryTab +import com.lumenpearson.lessons.ui.diary.DiaryViewModel +import com.lumenpearson.lessons.ui.diary.icon +import com.lumenpearson.lessons.ui.diary.labelRes import com.lumenpearson.lessons.ui.docs.DocsScreen import com.lumenpearson.lessons.ui.docs.DocsViewModel import com.lumenpearson.lessons.ui.docs.docsToolbarItems import com.lumenpearson.lessons.ui.docs.docsToolbarSelection import com.lumenpearson.lessons.ui.homework.HomeworkScreen -import com.lumenpearson.lessons.ui.join.JoinScreen import com.lumenpearson.lessons.ui.onboarding.OnboardingScreen import com.lumenpearson.lessons.ui.settings.SettingsRootScreen import com.lumenpearson.lessons.ui.settings.SettingsSection @@ -123,15 +132,17 @@ import kotlinx.coroutines.launch * gesture between them is a swipe. A graph would give the same three screens * without the swipe, and the swipe is half of what the floating toolbar is for. * - * @param signedIn `null` while the stored session is still being read — the - * splash is shown for that moment rather than guessing a destination and then - * yanking the user somewhere else a frame later. + * @param shell the stored mode and hold, `null` while they are still being + * read — the splash is shown for that moment rather than guessing a + * destination and then yanking the user somewhere else a frame later. + * [rootScreen] decides between the way in and a home, and [shellHome] which + * home. * @param openDate a day the widget asked for; the shell moves to the calendar * and selects it, then calls [onDateOpened] so the request is acted on once. */ @Composable fun LessonsApp( - signedIn: Boolean?, + shell: ShellState?, settings: AppSettings, modifier: Modifier = Modifier, openDate: LocalDate? = null, @@ -175,35 +186,47 @@ fun LessonsApp( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer, ) { - when (signedIn) { - null -> SplashShell(modifier = modifier) - - false -> { - // Latched on the first composition of this branch rather than - // read live. The introduction records itself as seen the moment - // it reaches its last step, and re-reading the flag there would - // swap the whole screen for a bare join page halfway through the - // slide that was carrying the user to it. + when (rootScreen(shell)) { + RootScreen.SPLASH -> SplashShell(modifier = modifier) + + RootScreen.ONBOARDING -> { + // One flow whichever way the phone arrives: a fresh install + // opens at the welcome, and one that has seen the + // introduction — which is what leaving the last class makes + // of it — at the chooser, where both ways in are. There is + // no bare join screen any more; it could reach neither the + // diary nor its sign-out. // - // Safe to latch because settings are real by the time this - // branch exists at all: the shell's state combines the settings - // flow with the session, so nothing is emitted — and the splash - // above stays — until preferences have actually been read from - // disk. - val introduce = rememberSaveable { !settings.onboardingDone } - if (introduce) { - OnboardingScreen(modifier = modifier) - } else { - JoinScreen(modifier = modifier) - } + // Latched on the first composition of this branch rather + // than read live: the flow records the introduction as seen + // on reaching the chooser, and a live read would restart it + // under the finger. Safe to latch because settings are real + // by the time this branch exists at all — the shell's state + // combines the settings flow with the mode, so nothing is + // emitted, and the splash stays, until preferences have been + // read from disk. + val introduced = rememberSaveable { settings.onboardingDone } + OnboardingScreen(introduced = introduced, modifier = modifier) } - true -> HomeShell( - settings = settings, - openDate = openDate, - onDateOpened = onDateOpened, - modifier = modifier, - ) + RootScreen.HOME -> { + // Never null here — the gate sends NONE to the way in — but + // a class home is the least surprising answer if it were. + val home = shell?.mode?.let(::shellHome) ?: ShellHome.TIMETABLE + // Keyed, so moving between the class and the diary resets + // the shell's hoisted state: the settings layer closes, and + // the phone lands on the new home rather than in a section + // of the old one — or on a pager index the diary has none of. + key(home) { + HomeShell( + home = home, + settings = settings, + openDate = openDate, + onDateOpened = onDateOpened, + modifier = modifier, + ) + } + } } } } @@ -249,9 +272,17 @@ private const val TabsStateKey = "home-tabs" * halo, because that padding is sized for a row of items and not for one. * Destinations that are always present and always reachable — by a screen reader * too — beat an animation nobody asked for. + * + * The same shell draws both homes ([home]). On the diary home the tabs' pager is + * replaced by the diary itself and the toolbar carries its two halves instead + * of the class tabs; everything else — the settings layers, the guide, back, + * the update host — is shared, because a second shell would be a second copy of + * the rules `ShellBackTest` holds. The diary's halves are not swiped between + * and not rearranged: their order is the diary's, and there are two. */ @Composable private fun HomeShell( + home: ShellHome, settings: AppSettings, openDate: LocalDate?, onDateOpened: () -> Unit, @@ -307,9 +338,33 @@ private fun HomeShell( // the screens below can keep their own default and nothing is passed down. val settingsViewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory) // Hoisted for the same reason: a day chip on the widget has to be able to - // put a date into the calendar before the calendar has been composed. - val calendarViewModel: WeekViewModel = viewModel(factory = WeekViewModel.Factory) + // put a date into the calendar before the calendar has been composed. Only + // on the class home — the diary home has no calendar, and building one + // would start a timetable load for a class this phone is not in. The + // branch is stable for the life of this composition: the shell is keyed + // on [home]. + val calendarViewModel: WeekViewModel? = + if (home == ShellHome.TIMETABLE) viewModel(factory = WeekViewModel.Factory) else null + // The diary's, on the diary home: the toolbar switches its tabs and back + // reads which one is open, so the shell holds it — the activity's store + // hands the settings page the same instance. + val diaryViewModel: DiaryViewModel? = + if (home == ShellHome.DIARY) viewModel(factory = DiaryViewModel.Factory) else null + val diaryTab = diaryViewModel?.uiState?.collectAsStateWithLifecycle()?.value?.tab val settingsState by settingsViewModel.uiState.collectAsStateWithLifecycle() + val shellMode = if (home == ShellHome.DIARY) ShellMode.DIARY else ShellMode.CLASS + + // The one refresh of the diary that nobody pressed for: each time the diary + // home comes to the front, the week is read again if the saved copy is + // stale. Here and nowhere else — not in the application, a receiver or the + // worker — because a read is what keeps the server's copy of the session + // alive, and that has to mean somebody opened the app (G4). + if (diaryViewModel != null) { + LifecycleStartEffect(diaryViewModel) { + diaryViewModel.refreshOnStart { Graph.container.diaryImport.refreshIfStale() } + onStopOrDispose { } + } + } var settingsOpen by rememberSaveable { mutableStateOf(false) } var showDebugSheet by rememberSaveable { mutableStateOf(false) } @@ -391,6 +446,7 @@ private fun HomeShell( // the scroll depth of the one that left, and the top fade would start // halfway down a list that is at the top. val pageOffsets = remember { HomeTab.entries.associateWith { ScrollOffsetHolder() } } + val diaryOffset = remember { ScrollOffsetHolder() } /** The holder belonging to whatever tab sits at [page] of the pager. */ fun offsetOf(page: Int): ScrollOffsetHolder = @@ -437,9 +493,15 @@ private fun HomeShell( // A deep link is somebody arriving with a question, and a bar that is // still being arranged is in the way of answering it. arranging = null - calendarViewModel.select(date) - calendarViewModel.setView(ScheduleView.DAY) - pagerState.goToPage(motion, tabs.indexOf(HomeTab.WEEK).coerceAtLeast(0)) + // Only a widget tap from before the phone left its class can reach the + // diary home — the widget draws nothing to tap in the diary mode — and + // the nearest answer to «this day» there is the diary's week holding it. + diaryViewModel?.showWeekOf(date) + calendarViewModel?.let { calendar -> + calendar.select(date) + calendar.setView(ScheduleView.DAY) + pagerState.goToPage(motion, tabs.indexOf(HomeTab.WEEK).coerceAtLeast(0)) + } onDateOpened() } @@ -563,7 +625,13 @@ private fun HomeShell( docsOpen = docsOpen, sectionOpen = openSection != null, settingsOpen = settingsOpen, - onHomePage = pagerState.currentPage == homePage, + // The diary's home page is its timetable, as the class's is the + // default tab: back from the marks goes there before it leaves. + onHomePage = if (home == ShellHome.DIARY) { + diaryTab == null || diaryTab == DiaryTab.SCHEDULE + } else { + pagerState.currentPage == homePage + }, ) BackHandler(enabled = back == ShellBack.LEAVE_ARRANGING) { stopArranging() } BackHandler(enabled = back == ShellBack.CLOSE_DOCS) { docsBack() } @@ -574,7 +642,11 @@ private fun HomeShell( PredictiveBackHandler(enabled = back == ShellBack.HOME) { events -> try { events.collect { event -> backProgress.snapTo(event.progress) } - scope.launch { pagerState.goToPage(motion, homePage) } + if (diaryViewModel != null) { + diaryViewModel.setTab(DiaryTab.SCHEDULE) + } else { + scope.launch { pagerState.goToPage(motion, homePage) } + } scope.launch { backProgress.animateTo(0f, tween(BackReturnMillis)) } } catch (_: CancellationException) { scope.launch { backProgress.animateTo(0f, tween(BackSettleMillis)) } @@ -618,7 +690,7 @@ private fun HomeShell( edgeBlur = settings.edgeBlur, statusBarHeightPx = statusBarHeightPx, offset = when (page) { - ShellPage.Tabs -> offsetOf(pagerState.currentPage) + ShellPage.Tabs -> if (home == ShellHome.DIARY) diaryOffset else offsetOf(pagerState.currentPage) ShellPage.SettingsRoot -> settingsOffset is ShellPage.Section -> sectionOffset ShellPage.Docs -> docsOffsets.getOrElse(docsPagerState.currentPage) { docsOffset } @@ -638,8 +710,12 @@ private fun HomeShell( // are the same one outside the arranging mode, and // inside it the bar's is a frame behind the stored // one on purpose. - ShellPage.Tabs -> tabs.getOrNull(pagerState.currentPage) - ?.let(barTabs::indexOf) ?: -1 + ShellPage.Tabs -> if (home == ShellHome.DIARY) { + diaryTab?.ordinal ?: 0 + } else { + tabs.getOrNull(pagerState.currentPage) + ?.let(barTabs::indexOf) ?: -1 + } ShellPage.Docs -> docsToolbarSelection( docsPagerState.currentPage, @@ -654,7 +730,16 @@ private fun HomeShell( // order coming back out of storage, and a tap in // that window has to reach the screen the icon is // of. - ShellPage.Tabs -> barTabs.map { tab -> + // The diary's own halves, in the diary's order. + ShellPage.Tabs -> if (diaryViewModel != null) { + DiaryTab.entries.map { tab -> + ToolbarItem( + icon = tab.icon, + label = correctedString(tab.labelRes()), + onClick = { diaryViewModel.setTab(tab) }, + ) + } + } else barTabs.map { tab -> ToolbarItem( icon = tab.icon, label = correctedString(tab.labelRes), @@ -683,12 +768,12 @@ private fun HomeShell( // than the reader's: a mode that opened there would let // somebody rearrange a table of contents into one the // text no longer matches. - reorderable = page == ShellPage.Tabs, + reorderable = page == ShellPage.Tabs && home == ShellHome.TIMETABLE, // Read against the page for the same reason everything // else here is: both bars are composed at once while a // slide runs, and the one leaving must not start // jiggling on its way out. - reordering = reordering && page == ShellPage.Tabs, + reordering = reordering && page == ShellPage.Tabs && home == ShellHome.TIMETABLE, onReorderingChange = { on -> arranging = if (on) tabs else null }, @@ -710,8 +795,10 @@ private fun HomeShell( action = shellAction( destination = page.destination, // The shortcut exists for the people who have the - // page it shortcuts to. - manager = isClassManager(settingsState.deviceLink.role), + // page it shortcuts to — never on the diary home, + // where there is no class to manage. + manager = home == ShellHome.TIMETABLE && + isClassManager(settingsState.deviceLink.role), onOpenSettings = { settingsOpen = true stopArranging() @@ -726,7 +813,22 @@ private fun HomeShell( }, ) { when (page) { - ShellPage.Tabs -> tabStates.SaveableStateProvider(TabsStateKey) { + ShellPage.Tabs -> if (diaryViewModel != null) { + tabStates.SaveableStateProvider(TabsStateKey) { + CompositionLocalProvider(LocalScrollOffset provides diaryOffset) { + DiaryScreen( + asHome = true, + insecureServer = isInsecure(settings.baseUrl), + viewModel = diaryViewModel, + modifier = Modifier.graphicsLayer { + val scale = 1f - backProgress.value * BackScaleDepth + scaleX = scale + scaleY = scale + }, + ) + } + } + } else tabStates.SaveableStateProvider(TabsStateKey) { HorizontalPager( state = pagerState, userScrollEnabled = settings.swipeTabs, @@ -768,7 +870,11 @@ private fun HomeShell( }, ) - HomeTab.WEEK -> WeekScreen(viewModel = calendarViewModel) + HomeTab.WEEK -> WeekScreen( + viewModel = checkNotNull(calendarViewModel) { + "the class home always has its calendar" + }, + ) HomeTab.HOMEWORK -> HomeworkScreen() } } @@ -779,6 +885,7 @@ private fun HomeShell( LocalScrollOffset provides settingsOffset, ) { SettingsRootScreen( + mode = shellMode, viewModel = settingsViewModel, onOpenSection = { section -> openSectionName = section.name }, ) @@ -792,6 +899,7 @@ private fun HomeShell( // replaces existed to paper over. SettingsSectionScreen( section = page.section, + mode = shellMode, onOpenSection = { next -> openSectionName = next.name }, onOpenDocs = ::openDocs, viewModel = settingsViewModel, @@ -1062,6 +1170,14 @@ private suspend fun PagerState.goToPage(motion: MotionSettings, page: Int) { */ private const val LayerTravelDivisor = 3 +/** + * Whether [address] is plain `http://` — what the diary's sign-in warns about. + * A blank address is not «insecure», it is «not configured»: nothing can be + * sent at all, so the warning would be about a request that never happens. + */ +internal fun isInsecure(address: String): Boolean = + address.isNotBlank() && !address.startsWith("https://", ignoreCase = true) + /** * Shown only while the session is being read. It is a deliberate blank with a * spinner: anything richer would flash for 30 ms and read as a glitch. diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/RootGate.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/RootGate.kt new file mode 100644 index 00000000..3ce622c8 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/RootGate.kt @@ -0,0 +1,40 @@ +package com.lumenpearson.lessons.navigation + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellState + +/** The three things the app can draw below the theme. */ +enum class RootScreen { + /** The stored state has not been read yet. */ + SPLASH, + + /** The way in: the introduction, or a way into a class or a diary. */ + ONBOARDING, + + /** A home — the class's or the diary's; see [shellHome]. */ + HOME, +} + +/** + * Which of the three [shell] asks for, as one rule the shell only carries out. + * + * * Nothing read yet is the splash, rather than a guessed destination and a + * jump a frame later. + * * A hold keeps the way in on screen whatever the mode says. The class-code + * step joins and the sign-in step registers before the flow is finished — + * each flips the mode away from [ShellMode.NONE] while an import or a + * summary is still to come — and the flow, not the credential, decides when + * onboarding ends (K3). The hold is persisted, so a process death between + * the write and the summary brings the flow back. + * * No class and no diary is the way in. + * * Otherwise a home: a phone with a diary and no class has one now. It used + * to be `signedIn = session != null`, and such a phone — which is what + * leaving the last class makes of a family signed in to their diary — was + * sent to the join screen, where neither the diary nor its sign-out could be + * reached (#151). + */ +fun rootScreen(shell: ShellState?): RootScreen = when { + shell == null -> RootScreen.SPLASH + shell.held || shell.mode == ShellMode.NONE -> RootScreen.ONBOARDING + else -> RootScreen.HOME +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellHome.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellHome.kt new file mode 100644 index 00000000..3c151c8a --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/navigation/ShellHome.kt @@ -0,0 +1,34 @@ +package com.lumenpearson.lessons.navigation + +import com.lumenpearson.lessons.core.data.repository.ShellMode + +/** + * Which home [HomeShell][LessonsApp] draws: the class's tabs, or the diary. + * + * One shell for both, branching in the few places the two differ — the pages, + * the toolbar's items, where back goes, what a widget's date does — rather + * than a second shell, which would be a second copy of the layer and back rules + * that `ShellBackTest` holds. + */ +enum class ShellHome { + /** Today, Week and Homework: a phone in a class. */ + TIMETABLE, + + /** The diary itself: a phone whose only account is a diary. */ + DIARY, +} + +/** + * The home for [mode], or `null` when there is none to draw — [ShellMode.NONE], + * which the root gate sends to the way in before this is ever asked. + * + * The shell is keyed on the answer, so a change of home — joining a class from + * the diary, or leaving the last class with a diary signed in — resets its + * hoisted state: the settings layer closes and the phone lands on the new home + * rather than inside a section of the old one. + */ +fun shellHome(mode: ShellMode): ShellHome? = when (mode) { + ShellMode.CLASS -> ShellHome.TIMETABLE + ShellMode.DIARY -> ShellHome.DIARY + ShellMode.NONE -> null +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/AppShellViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/AppShellViewModel.kt index e0904ed9..8d53223d 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/AppShellViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/AppShellViewModel.kt @@ -7,8 +7,9 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.repository.AppSettings -import com.lumenpearson.lessons.core.data.repository.SessionRepository import com.lumenpearson.lessons.core.data.repository.SettingsRepository +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.repository.ShellState import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.ui.common.DefaultAppSettings import kotlinx.coroutines.flow.MutableStateFlow @@ -17,14 +18,18 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock /** * The two facts the app shell needs before it can draw anything: * * @property settings theme preferences, applied by `LessonsTheme`. - * @property signedIn `null` while the session is still being read from disk, - * which is the signal to show the splash instead of guessing a start - * destination and then yanking the user somewhere else a frame later. + * @property shell which home the phone has and whether onboarding holds the + * screen — `null` while it is still being read from disk, which is the signal + * to show the splash instead of guessing a start destination and then + * yanking the user somewhere else a frame later. `RootGate.rootScreen` and + * `ShellHome.shellHome` turn it into a screen. * @property settingsLoaded whether [settings] is what is stored or the * placeholder this state is constructed with. False for exactly one value — * the `initialValue` below — because the combine that builds every other one @@ -35,7 +40,7 @@ import kotlinx.coroutines.launch */ data class AppShellUiState( val settings: AppSettings = DefaultAppSettings, - val signedIn: Boolean? = null, + val shell: ShellState? = null, val settingsLoaded: Boolean = false, ) { @@ -59,32 +64,39 @@ data class AppShellUiState( } /** - * Owns the state that outlives any single screen: theme preferences and whether - * a class session exists. + * Owns the state that outlives any single screen: theme preferences and which + * home the phone has. * * Keeping it here rather than in the settings screen means signing out anywhere - * in the app is enough to bounce the user back to the join screen — navigation - * reacts to the session, no callback plumbing required. + * in the app is enough to move the user on — to the way in, or from the class + * to the diary home when a diary is still signed in — with no callback + * plumbing: navigation reacts to the stored mode. + * + * Before the first read, the hold a previous process may have left behind is + * settled ([ShellModeSource.settleColdStart]) — once per process, through + * [coldStart], because this view model is rebuilt with every activity while the + * hold a *running* onboarding just set must not be dropped by the rebuild. */ class AppShellViewModel( - private val sessionRepository: SessionRepository, + private val shellMode: ShellModeSource, settingsRepository: SettingsRepository, + private val coldStart: ColdStart = ColdStart.Process, ) : ViewModel() { /** - * Tri-state sign-in flag. Seeded from [SessionRepository.current] so the very - * first value is authoritative, then kept live by the session flow. + * The shell's state. Seeded from the settled cold start so the very first + * value is authoritative, then kept live by the mode's flow. */ - private val signedIn = MutableStateFlow(null) + private val shell = MutableStateFlow(null) val uiState: StateFlow = - combine(settingsRepository.settings, signedIn) { settings, session -> + combine(settingsRepository.settings, shell) { settings, shell -> // `settingsLoaded = true` unconditionally, and that is sound rather // than optimistic: combine emits nothing until every source has, so // reaching this line is itself the proof that the settings flow has // answered. The one state that never comes through here is the // initialValue below. - AppShellUiState(settings = settings, signedIn = session, settingsLoaded = true) + AppShellUiState(settings = settings, shell = shell, settingsLoaded = true) }.stateIn( scope = viewModelScope, // Eagerly: the theme must be ready before the first frame, and this @@ -95,8 +107,36 @@ class AppShellViewModel( init { viewModelScope.launch { - signedIn.value = sessionRepository.current() != null - sessionRepository.session.collect { session -> signedIn.value = session != null } + shell.value = coldStart.settle(shellMode) + shellMode.state.collect { shell.value = it } + } + } + + /** + * «Once per process», as a thing that can be handed to the constructor: the + * app passes [Process], which is shared by every view model the process + * builds, and a test passes a fresh one so its cases do not share a process. + */ + class ColdStart { + + private val lock = Mutex() + private var settled = false + + /** + * The first call settles the stored hold and answers with the state + * after it; every later call only reads. + */ + suspend fun settle(source: ShellModeSource): ShellState = lock.withLock { + if (settled) { + source.current() + } else { + source.settleColdStart().also { settled = true } + } + } + + companion object { + /** The one this process uses. */ + val Process = ColdStart() } } @@ -110,7 +150,7 @@ class AppShellViewModel( val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { AppShellViewModel( - sessionRepository = Graph.container.sessionRepository, + shellMode = Graph.container.shellMode, settingsRepository = Graph.container.settingsRepository, ) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/OpenLink.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/OpenLink.kt new file mode 100644 index 00000000..ad811dd8 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/OpenLink.kt @@ -0,0 +1,27 @@ +package com.lumenpearson.lessons.ui.common + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import androidx.core.net.toUri + +/** + * Opens [url] in whatever the phone picks for it; `false` when nothing could. + * + * One function for every external link the app opens — the legal documents, + * the diary's own site, a Госуслуги handoff — because each of them has the same + * two obligations. It is always `ACTION_VIEW` on the address and never an app + * named by its package: which app takes a Госуслуги page is the phone's + * decision, and nothing comes back from it. And it is guarded: a work profile + * or a locked-down school phone may have no browser at all, and the about + * card's links already learned that an unguarded `startActivity` takes the app + * down on one. + */ +internal fun openInBrowser(context: Context, url: String): Boolean = try { + context.startActivity( + Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + true +} catch (_: ActivityNotFoundException) { + false +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt index 3ad1c9b3..e8244847 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/common/ServerUrlSheet.kt @@ -42,10 +42,18 @@ import com.lumenpearson.lessons.core.designsystem.theme.emphasised * sheet is anchored to the same edge the keyboard comes from. Essentials puts * every input of this kind in a sheet for the same reason. * + * There is no default to fall back to: the APK carries no server address + * (`AppSettings.DEFAULT_BASE_URL` is empty, on purpose — no address is right + * for a second user), so the sheet never says «change this only if…». It used + * to, and a pupil who took that at its word pressed «Подключиться» on a blank + * address and was shown an English exception message (#154). + * * @param initialUrl current address; the field starts from it rather than empty * so a small typo is a small edit. - * @param onConfirm called with the trimmed value; the caller decides whether an - * empty string means "use the default". + * @param description the sentence above the field. The first run passes its + * own where it asks for the address because the diary's sign-in needs one. + * @param onConfirm called with the trimmed value; an empty string clears the + * address, and the app then has no server until one is set. */ @Composable fun ServerUrlSheet( @@ -53,6 +61,7 @@ fun ServerUrlSheet( onDismiss: () -> Unit, onConfirm: (String) -> Unit, modifier: Modifier = Modifier, + description: String = correctedString(R.string.server_dialog_description), ) { var url by rememberSaveable(initialUrl) { mutableStateOf(initialUrl) } val trimmed = remember(url) { url.trim() } @@ -67,7 +76,7 @@ fun ServerUrlSheet( title = correctedString(R.string.server_dialog_title), ) { Text( - text = correctedString(R.string.server_dialog_description), + text = description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = ScreenPadding), @@ -101,9 +110,9 @@ fun ServerUrlSheet( TextButton(onClick = onDismiss) { Text(text = correctedString(R.string.action_cancel)) } - // Enabled on an empty field too: the callers treat "" as "use the - // default", and with the button disabled there was no way to undo a - // mistyped address short of reinstalling. + // Enabled on an empty field too: "" clears the address, and with + // the button disabled there was no way to undo a mistyped address + // short of reinstalling. Button(onClick = { onConfirm(trimmed) }) { Text(text = correctedString(R.string.action_save)) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt new file mode 100644 index 00000000..6a19f03e --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt @@ -0,0 +1,172 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.Logout +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import androidx.compose.material.icons.rounded.GroupAdd +import androidx.compose.material.icons.rounded.Map +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material.icons.rounded.School +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.GroupItem +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.designsystem.theme.errorTone +import com.lumenpearson.lessons.ui.settings.AddClassSheet + +/** + * Settings → «Дневник» on a phone whose only account is the diary: the pupil, + * the account, the way to a class, and the way out. + * + * Not a second `DiaryScreen`. On this phone the diary already *is* the home, + * and a section that drew it again would be the same week twice, one of them + * behind a back gesture. What the home cannot hold is what this page is for — + * which account this is and where it signs in, and «Выйти из дневника», which + * on the home would be one tap from the first screen somebody sees and here is + * where the other account pages keep their exits. + * + * The class row is the whole of the path from here to everything the diary + * mode does not have — the class timetable, the widget, the bell reminders — + * and it is offered, not pressed: a class code comes from a school that has set + * one up, which most families reaching this page have not been given. + * + * It reads the view model the home uses (the activity's), so the pupil chosen + * here is the pupil the home shows. + */ +@Composable +fun DiaryAccountPage( + modifier: Modifier = Modifier, + viewModel: DiaryViewModel = viewModel(factory = DiaryViewModel.Factory), +) { + val state by viewModel.uiState.collectAsStateWithLifecycle() + var confirmSignOut by rememberSaveable { mutableStateOf(false) } + var addingClass by rememberSaveable { mutableStateOf(false) } + + if (confirmSignOut) { + DiarySignOutSheet( + leavesTheApp = true, + onDismiss = { confirmSignOut = false }, + onConfirm = { + confirmSignOut = false + viewModel.signOut() + }, + ) + } + if (addingClass) { + AddClassSheet(onDismiss = { addingClass = false }) + } + + val target = state.session?.target ?: state.signInTarget + val place = state.place + + DiaryPage(modifier) { + item(key = "header") { + ScreenHeader( + title = state.student?.fullName ?: correctedString(R.string.diary_title), + subtitle = state.student?.let { student -> + listOfNotNull(student.className, student.school).joinToString(" · ").ifBlank { null } + } ?: correctedString(R.string.diary_signed_in_as, target.login), + ) + } + + if (state.showStudentPicker) { + item(key = "students") { + DiaryStudentPicker( + students = state.students, + selectedId = state.selectedStudentId, + onSelect = viewModel::selectStudent, + ) + } + } + + item(key = "account") { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.diary_title)) + RoundedCardContainer { + place?.systemName()?.let { system -> + GroupItem( + title = correctedString(R.string.diary_account_system), + subtitle = system, + icon = Icons.AutoMirrored.Rounded.MenuBook, + tone = accentTone(4), + ) + } + place?.regionName()?.let { region -> + GroupItem( + title = correctedString(R.string.diary_account_region), + subtitle = region, + icon = Icons.Rounded.Map, + tone = accentTone(0), + ) + } + target.schoolName?.takeIf { it.isNotBlank() }?.let { school -> + GroupItem( + title = correctedString(R.string.diary_account_school), + subtitle = school, + icon = Icons.Rounded.School, + tone = accentTone(1), + ) + } + target.login.takeIf { it.isNotBlank() }?.let { login -> + GroupItem( + title = correctedString(R.string.diary_login_label), + subtitle = login, + icon = Icons.Rounded.Person, + tone = accentTone(2), + ) + } + } + } + } + + item(key = "class") { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.settings_class)) + RoundedCardContainer { + GroupLinkItem( + title = correctedString(R.string.diary_account_join_class), + icon = Icons.Rounded.GroupAdd, + tone = accentTone(3), + onClick = { addingClass = true }, + ) + GroupRow { + Text( + text = correctedString(R.string.diary_account_class_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + + item(key = "sign-out") { + RoundedCardContainer { + GroupItem( + title = correctedString(R.string.diary_sign_out), + tone = errorTone(), + icon = Icons.AutoMirrored.Rounded.Logout, + enabled = !state.signingOut, + onClick = { confirmSignOut = true }, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalog.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalog.kt new file mode 100644 index 00000000..41c5533d --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalog.kt @@ -0,0 +1,169 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.catalog.CatalogRegion +import com.lumenpearson.lessons.core.data.catalog.CatalogSystem +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.net.URI + +/** + * What the screens say about a diary target, read out of the bundled catalog: + * the region's name, the system's name, and the host a password would go to. + * + * A plain `:app` value rather than the catalog's own types, which live in + * `:core:data` and are deliberately not promised stable to the Compose compiler + * (`compose-stability.conf`): a screen holding a `CatalogRegion` would recompose + * on every frame of a state it never changed. + * + * Both languages are carried, because the catalog is where region names live + * (not string resources — K16) and which one to show is the composition's + * question, not the view model's. + * + * @property host where the password goes — the origin the sign-in is allowed + * to send to, from the same allow-list `OriginGuard` enforces. `null` when + * the catalog cannot place the target, and then the form names no host + * rather than guessing one. + */ +@Immutable +data class DiaryPlace( + val regionRu: String?, + val regionEn: String?, + val systemRu: String?, + val systemEn: String?, + val host: String?, +) + +/** + * [target] as the catalog knows it. + * + * The host is read from the same two fields the sign-in's allow-list is built + * from (`CatalogUpstreamDirectory`: Petersburg's platform origin, a region's + * «Сетевой город» row) and refused by the same rule — an origin that is not + * plain `https` with nothing after the authority names no host here, exactly + * as it is dropped there. So the form never names a host the password could + * not be sent to. The directory's own type is not reused because its origins + * are OkHttp's, which `:core:data` keeps to itself. + */ +fun diaryPlaceOf(catalog: RegionCatalog, target: DiaryTarget): DiaryPlace = + when (target.provider) { + DiaryProviderKey.PETERSBURG -> { + val platform = catalog.platforms.values.firstOrNull { it.provider == target.provider.wire } + val region = catalog.regions.firstOrNull { region -> + region.systems.any { it.platform == PETERSBURG_PLATFORM && it.action == ACTION_SIGN_IN } + } + DiaryPlace( + regionRu = region?.nameRu, + regionEn = region?.nameEn, + systemRu = platform?.nameRu, + systemEn = platform?.nameEn, + host = platform?.origin?.let(::httpsHostOf), + ) + } + DiaryProviderKey.NETSCHOOL -> { + val region = catalog.regions.firstOrNull { region -> + region.systems.any { it.netschool?.region == target.region } + } + // The first row for the key, as the directory keeps it. + val row = catalog.regions.asSequence() + .flatMap { it.systems.asSequence() } + .mapNotNull { it.netschool } + .firstOrNull { it.region == target.region } + val platform = catalog.platforms[NETSCHOOL_PLATFORM] + DiaryPlace( + regionRu = region?.nameRu, + regionEn = region?.nameEn, + systemRu = platform?.nameRu, + systemEn = platform?.nameEn, + host = row?.origin?.let(::httpsHostOf), + ) + } + } + +/** + * The host (and port, when it is not the default) of an origin the allow-list + * would keep; `null` for one it would drop. + */ +internal fun httpsHostOf(origin: String): String? { + val uri = runCatching { URI(origin) }.getOrNull() ?: return null + val host = uri.host?.takeIf { it.isNotBlank() } ?: return null + val bare = uri.scheme.equals("https", ignoreCase = true) && + uri.rawUserInfo == null && + uri.rawPath.isNullOrEmpty() && + uri.rawQuery == null && + uri.rawFragment == null + if (!bare) return null + return if (uri.port == -1 || uri.port == HttpsPort) host else "$host:${uri.port}" +} + +private const val HttpsPort = 443 + +/** + * What the app can do about a region's diary, read from the generator's own + * answers (`recommended`, `action`) and never re-derived (K18). + */ +sealed interface DiaryRegionChoice { + + /** Petersburg: the account decides the school, so the next step is the form. */ + data object Petersburg : DiaryRegionChoice + + /** A «Сетевой город» region that takes a password: a school has to be picked. */ + data class NetSchool(val regionKey: String, val zone: String) : DiaryRegionChoice + + /** + * The region's diary lets nobody in with a password here — Госуслуги, or a + * system the app does not speak. [url] is where the browser can go, or + * `null` when there is nowhere. + */ + data class Elsewhere(val url: String?, val gosuslugi: Boolean) : DiaryRegionChoice +} + +/** + * The choice for [region]: its recommended system if that is one the app signs + * in to, else the first system it can sign in to, else where to send somebody. + * + * A signable system that is not the recommended one still wins over a handoff + * — the recommendation is advice about the region, and a family whose school + * is on the second system is better served by a form than by a website. + */ +fun diaryChoiceOf(region: CatalogRegion): DiaryRegionChoice { + val recommended = region.recommended?.system?.let(region.systems::getOrNull) + val signable = listOfNotNull(recommended) + region.systems + signable.firstOrNull { it.action == ACTION_SIGN_IN }?.let { system -> + signInChoice(region, system)?.let { return it } + } + val handoff = listOfNotNull(recommended).plus(region.systems) + .firstOrNull { it.action == ACTION_HANDOFF } + val url = (handoff ?: recommended)?.let { it.handoffUrl ?: it.webUrl } + ?.takeIf { it.startsWith("https://") } + return DiaryRegionChoice.Elsewhere( + url = url, + gosuslugi = region.recommended?.modifiers?.contains(MODIFIER_ESIA_ONLY) == true || + handoff?.netschool?.password == false, + ) +} + +private fun signInChoice(region: CatalogRegion, system: CatalogSystem): DiaryRegionChoice? = + when (system.platform) { + PETERSBURG_PLATFORM -> DiaryRegionChoice.Petersburg + NETSCHOOL_PLATFORM -> system.netschool + ?.takeIf { it.password } + ?.let { DiaryRegionChoice.NetSchool(it.region, it.zone.ifBlank { region.zone }) } + else -> null + } + +/** The catalog's platform key for Petersburg's diary. */ +private const val PETERSBURG_PLATFORM = "petersburg" + +/** The catalog's platform key for «Сетевой город». */ +private const val NETSCHOOL_PLATFORM = "netschool" + +/** A system the app's own form signs in to. */ +private const val ACTION_SIGN_IN = "signin" + +/** A system the browser is sent to, and nothing comes back. */ +private const val ACTION_HANDOFF = "handoff" + +/** The generator's modifier for a region whose diary takes Госуслуги only. */ +private const val MODIFIER_ESIA_ONLY = "esia_only" diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt new file mode 100644 index 00000000..acc37b8f --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt @@ -0,0 +1,166 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.Login +import androidx.compose.material.icons.rounded.Visibility +import androidx.compose.material.icons.rounded.VisibilityOff +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString + +/** + * The login, the password and the button that sends them — the one diary + * sign-in form in the app, used by Settings → «Дневник», by the re-sign-in on + * the diary home and by the onboarding's sign-in step. + * + * One form, because the promises it keeps are about the form and not about the + * screen around it: the password lives in this composable's `remember` and + * nowhere else — not `rememberSaveable`, whose bundle the system writes to + * disk, not a view model, not a callback's closure that outlives the press — + * and it leaves only as the argument of [onSubmit]. A second copy of the form + * would be a second place that promise has to be kept by hand. The cost is that + * a rotation mid-typing clears the password, which is the right trade for the + * one field in this app that is a secret. + * + * The login is hoisted ([login], [onLoginChange]) because it is not a secret + * and the caller may want it to survive a recreation, which the onboarding does. + * + * @param login the login shown; trimmed as it is typed. + * @param loginEditable `false` on a re-authentication, where the login is known + * and a field that could be changed invites signing in as somebody else. + * @param busy a sign-in is in flight: both fields and the button are held. + * @param failed the last attempt was refused — the fields go red. What went + * wrong is the caller's pop-up to say (`DiaryProblemText`): a line under the + * button is under the keyboard on a phone. + * @param onSubmit the button, or «Готово» on the keyboard, with the login and + * the password. Called only when both are filled and nothing is in flight. + * @param onEdited any keystroke, so the caller can clear [failed]. + * @param loginLabel «Логин» by default; the onboarding says «Электронная почта» + * for Petersburg, whose logins are addresses. + * @param loginKeyboard the keyboard for the login. + * @param submitLabel «Войти» by default. + */ +@Composable +fun DiaryCredentialFields( + login: String, + onLoginChange: (String) -> Unit, + onSubmit: (login: String, password: String) -> Unit, + modifier: Modifier = Modifier, + loginEditable: Boolean = true, + busy: Boolean = false, + failed: Boolean = false, + onEdited: () -> Unit = {}, + loginLabel: String = correctedString(R.string.diary_login_label), + loginKeyboard: KeyboardType = KeyboardType.Email, + submitLabel: String = correctedString(R.string.diary_sign_in_action), +) { + var password by remember { mutableStateOf("") } + var revealed by remember { mutableStateOf(false) } + + val canSubmit = password.isNotBlank() && login.isNotBlank() && !busy + fun submit() { + if (canSubmit) onSubmit(login, password) + } + + RoundedCardContainer(modifier = modifier) { + GroupRow { + OutlinedTextField( + value = login, + onValueChange = { + onLoginChange(it.trim()) + onEdited() + }, + modifier = Modifier + .fillMaxWidth() + .testTag(LoginFieldTag), + label = { Text(loginLabel) }, + singleLine = true, + enabled = loginEditable && !busy, + isError = failed, + keyboardOptions = KeyboardOptions( + keyboardType = loginKeyboard, + imeAction = ImeAction.Next, + ), + ) + } + + GroupRow { + OutlinedTextField( + value = password, + onValueChange = { + password = it + onEdited() + }, + modifier = Modifier + .fillMaxWidth() + .testTag(PasswordFieldTag), + label = { Text(correctedString(R.string.diary_password_label)) }, + singleLine = true, + enabled = !busy, + isError = failed, + visualTransformation = if (revealed) { + VisualTransformation.None + } else { + PasswordVisualTransformation() + }, + trailingIcon = { + IconButton(onClick = { revealed = !revealed }) { + Icon( + imageVector = if (revealed) { + Icons.Rounded.VisibilityOff + } else { + Icons.Rounded.Visibility + }, + contentDescription = correctedString( + if (revealed) { + R.string.diary_password_hide + } else { + R.string.diary_password_reveal + }, + ), + ) + } + }, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Password, + imeAction = ImeAction.Done, + ), + keyboardActions = KeyboardActions(onDone = { submit() }), + ) + } + + GroupActionItem( + label = submitLabel, + icon = Icons.AutoMirrored.Rounded.Login, + enabled = canSubmit, + busy = busy, + onClick = ::submit, + ) + } +} + +/** Test tags for the two fields, so a test can type into each without reading labels. */ +const val LoginFieldTag = "diary-login" + +/** @see LoginFieldTag */ +const val PasswordFieldTag = "diary-password" diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt new file mode 100644 index 00000000..397f9adf --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerPage.kt @@ -0,0 +1,459 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.OpenInNew +import androidx.compose.material.icons.rounded.Map +import androidx.compose.material.icons.rounded.School +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.catalog.CatalogRegion +import com.lumenpearson.lessons.core.data.di.Graph +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import com.lumenpearson.lessons.core.designsystem.component.EmptyState +import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem +import com.lumenpearson.lessons.core.designsystem.component.GroupItem +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader +import com.lumenpearson.lessons.core.designsystem.component.SkeletonGroup +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace +import com.lumenpearson.lessons.core.designsystem.theme.ReportScrollOffset +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur +import com.lumenpearson.lessons.core.designsystem.theme.statusBarSpace +import com.lumenpearson.lessons.ui.common.openInBrowser +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * «Which diary?», answered as region, then school: the page a phone that knows + * no diary yet uses to say which one to sign in to. + * + * Settings → «Дневник» opens it on a phone in a class whose join named no + * diary (r11, gap 2); the onboarding's own region and school steps are richer + * — the smart search, the «почему» of a recommendation — and may host this + * page or build on its view model. Either way the rule for what a region + * offers is [diaryChoiceOf]: the catalog's own answer, never a second + * derivation of it. + * + * It asks nobody anything but the region's own diary: regions are searched in + * the bundled catalog, and schools straight from the phone to the region's + * server ([DiarySchoolSearch]), which is the server the password will go to + * next and so the honest early warning that it cannot be reached. + * + * @param onPicked the diary to sign in to, with a blank login — the form that + * follows ([DiaryCredentialFields]) is where the login is typed. + * @param onCancel back from the region list; back from the school step returns + * to the regions instead. + */ +@Composable +fun DiaryPickerPage( + onPicked: (DiaryTarget) -> Unit, + onCancel: () -> Unit, + modifier: Modifier = Modifier, + viewModel: DiaryPickerViewModel = viewModel(factory = DiaryPickerViewModel.Factory), +) { + val state by viewModel.state.collectAsStateWithLifecycle() + val context = LocalContext.current + val picked by rememberUpdatedState(onPicked) + + // The picker's answer arrives as state rather than as a return value, so a + // Petersburg tap — which needs no second step — and a school tap reach the + // caller the same way, once. + LaunchedEffect(state.picked) { + val target = state.picked ?: return@LaunchedEffect + viewModel.consumePicked() + picked(target) + } + + BackHandler { + if (state.region != null) viewModel.clearRegion() else onCancel() + } + + val listState = rememberLazyListState() + ReportScrollOffset(listState) + + Box(modifier = modifier.fillMaxSize()) { + LazyColumn( + state = listState, + modifier = Modifier + .fillMaxSize() + .imePadding() + .appScrollMotionBlur(listState), + contentPadding = PaddingValues( + start = ScreenPadding, + end = ScreenPadding, + top = statusBarSpace() + 8.dp, + bottom = LocalBottomBarSpace.current, + ), + verticalArrangement = Arrangement.spacedBy(GroupSpacing), + ) { + item(key = "header") { + ScreenHeader( + title = correctedString(R.string.diary_pick_title), + subtitle = correctedString(R.string.diary_pick_subtitle), + ) + } + + val region = state.region + if (region == null) { + item(key = "region-search") { + SearchField( + value = state.regionQuery, + onValueChange = viewModel::searchRegions, + label = correctedString(R.string.diary_pick_region_search), + ) + } + if (state.regions.isEmpty() && state.regionQuery.isNotBlank()) { + item(key = "regions-empty") { + PickerNote(correctedString(R.string.diary_pick_regions_empty)) + } + } else { + item(key = "regions") { + RoundedCardContainer { + state.regions.forEach { row -> + GroupItem( + title = localized(row.nameRu, row.nameEn).orEmpty(), + subtitle = row.code.takeIf { it.isNotBlank() }, + icon = Icons.Rounded.Map, + tone = accentTone(0), + onClick = { viewModel.pickRegion(row) }, + ) + } + } + } + } + } else { + item(key = "region") { + RoundedCardContainer { + GroupLinkItem( + title = localized(region.nameRu, region.nameEn).orEmpty(), + icon = Icons.Rounded.Map, + tone = accentTone(0), + value = correctedString(R.string.diary_pick_change), + onClick = viewModel::clearRegion, + ) + } + } + when (val choice = region.choice) { + // Picked the moment the region was; nothing more to draw. + DiaryRegionChoice.Petersburg -> Unit + is DiaryRegionChoice.NetSchool -> schoolStep(state, viewModel) + is DiaryRegionChoice.Elsewhere -> item(key = "elsewhere") { + RoundedCardContainer { + GroupRow { + Text( + text = correctedString( + if (choice.url != null) { + R.string.diary_pick_handoff + } else { + R.string.diary_pick_unsupported + }, + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + // Always the browser, never an app named by + // package: which app takes the link is the + // phone's decision, and nothing comes back. + choice.url?.let { url -> + GroupActionItem( + label = correctedString(R.string.diary_pick_open_site), + icon = Icons.AutoMirrored.Rounded.OpenInNew, + onClick = { openInBrowser(context, url) }, + ) + } + } + } + } + } + } + } +} + +private fun androidx.compose.foundation.lazy.LazyListScope.schoolStep( + state: DiaryPickerState, + viewModel: DiaryPickerViewModel, +) { + item(key = "school-search") { + SearchField( + value = state.schoolQuery, + onValueChange = viewModel::searchSchools, + label = correctedString(R.string.diary_pick_school_search), + ) + } + when { + state.searching -> item(key = "schools-loading") { SkeletonGroup(rows = 3) } + + state.problem != null -> item(key = "schools-problem") { + EmptyState( + title = correctedString(R.string.diary_failure_title), + description = state.problem.asText(), + actionLabel = correctedString(R.string.diary_retry).takeIf { state.problem.offersRetry }, + onActionClick = viewModel::retrySchools.takeIf { state.problem.offersRetry }, + ) + } + + state.schoolQuery.trim().length < DiarySchoolSearch.MIN_QUERY_LENGTH -> item(key = "schools-hint") { + PickerNote(correctedString(R.string.diary_pick_school_hint)) + } + + state.schools.isEmpty() -> item(key = "schools-empty") { + PickerNote(correctedString(R.string.diary_pick_schools_empty)) + } + + else -> item(key = "schools") { + RoundedCardContainer { + state.schools.forEach { school -> + GroupItem( + title = school.name, + subtitle = school.address, + icon = Icons.Rounded.School, + tone = accentTone(1), + onClick = { viewModel.pickSchool(school) }, + ) + } + } + } + } +} + +/** A sentence in place of a list: nothing found, or what to type first. */ +@Composable +private fun PickerNote(text: String) { + RoundedCardContainer { + GroupRow { + Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +@Composable +private fun SearchField( + value: String, + onValueChange: (String) -> Unit, + label: String, +) { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = Modifier.fillMaxWidth(), + label = { Text(label) }, + leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + ) +} + +/** A region as the picker draws it; see [DiaryPlace] for why not the catalog's type. */ +@Immutable +data class DiaryRegionRow( + val key: String, + val nameRu: String, + val nameEn: String, + val code: String, + val choice: DiaryRegionChoice, +) + +/** A school as the picker draws it. */ +@Immutable +data class DiarySchoolRow(val id: Long, val name: String, val address: String?) + +/** + * @property picked the answer, waiting to be handed to the caller once. + * @property problem why the school search failed — `DiaryProblemText`'s to say, + * since it is the same region server the sign-in will talk to. + */ +data class DiaryPickerState( + val regionQuery: String = "", + val regions: List = emptyList(), + val region: DiaryRegionRow? = null, + val schoolQuery: String = "", + val schools: List = emptyList(), + val searching: Boolean = false, + val problem: DiarySignInProblem? = null, + val picked: DiaryTarget? = null, +) + +/** + * The picker's state holder. + * + * @param regions the catalog's regions for a query, best first; every region + * in order for a blank one. No request is behind it. + * @param schools the region server's schools for a query — `DiarySchoolSearch`. + */ +class DiaryPickerViewModel( + private val regions: suspend (query: String) -> List, + private val schools: suspend (regionKey: String, query: String) -> Result>, +) : ViewModel() { + + private val mutable = MutableStateFlow(DiaryPickerState()) + val state: StateFlow = mutable.asStateFlow() + + private var regionJob: Job? = null + private var schoolJob: Job? = null + + init { + searchRegions("") + } + + fun searchRegions(query: String) { + mutable.update { it.copy(regionQuery = query) } + regionJob?.cancel() + regionJob = viewModelScope.launch { + val found = runCatching { regions(query) }.getOrDefault(emptyList()) + mutable.update { it.copy(regions = found.map(::rowOf)) } + } + } + + /** + * A region tapped. Petersburg is answered at once — its account decides the + * school, so there is nothing more to ask; a «Сетевой город» region goes on + * to its schools; anywhere else stays on the page to say why not. + */ + fun pickRegion(row: DiaryRegionRow) { + schoolJob?.cancel() + mutable.update { + it.copy(region = row, schoolQuery = "", schools = emptyList(), searching = false, problem = null) + } + if (row.choice == DiaryRegionChoice.Petersburg) { + mutable.update { it.copy(picked = DiaryTarget.petersburg(login = "")) } + } + } + + fun clearRegion() { + schoolJob?.cancel() + mutable.update { + it.copy(region = null, schoolQuery = "", schools = emptyList(), searching = false, problem = null) + } + } + + /** + * Asks the region's server after the typing stops + * ([DiarySchoolSearch.DEBOUNCE_MILLIS]), so it sees one person typing and + * not one request per letter. + */ + fun searchSchools(query: String) { + mutable.update { it.copy(schoolQuery = query) } + search(query, debounce = true) + } + + fun retrySchools() = search(mutable.value.schoolQuery, debounce = false) + + private fun search(query: String, debounce: Boolean) { + val choice = mutable.value.region?.choice as? DiaryRegionChoice.NetSchool ?: return + schoolJob?.cancel() + if (query.trim().length < DiarySchoolSearch.MIN_QUERY_LENGTH) { + mutable.update { it.copy(schools = emptyList(), searching = false, problem = null) } + return + } + schoolJob = viewModelScope.launch { + if (debounce) delay(DiarySchoolSearch.DEBOUNCE_MILLIS) + mutable.update { it.copy(searching = true, problem = null) } + schools(choice.regionKey, query).fold( + onSuccess = { found -> + mutable.update { + it.copy( + searching = false, + schools = found.map { school -> DiarySchoolRow(school.id, school.name, school.address) }, + ) + } + }, + onFailure = { failure -> + mutable.update { + it.copy(searching = false, schools = emptyList(), problem = DiarySignInProblem.of(failure)) + } + }, + ) + } + } + + fun pickSchool(school: DiarySchoolRow) { + val region = mutable.value.region ?: return + val choice = region.choice as? DiaryRegionChoice.NetSchool ?: return + mutable.update { + it.copy( + picked = DiaryTarget.netschool( + region = choice.regionKey, + schoolId = school.id, + schoolName = school.name, + login = "", + zone = choice.zone, + ), + ) + } + } + + /** The caller has the answer; the next visit starts at the regions. */ + fun consumePicked() { + mutable.update { DiaryPickerState(regionQuery = "", regions = it.regions) } + searchRegions("") + } + + private fun rowOf(region: CatalogRegion) = DiaryRegionRow( + key = region.key, + nameRu = region.nameRu, + nameEn = region.nameEn, + code = region.code, + choice = diaryChoiceOf(region), + ) + + companion object { + val Factory: ViewModelProvider.Factory = viewModelFactory { + initializer { + val container = Graph.container + DiaryPickerViewModel( + regions = { query -> container.regionLookup.byName(query).map { it.region } }, + schools = { region, query -> container.diarySchoolSearch.search(region, query) }, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentation.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentation.kt index a397d3f0..b63a5237 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentation.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentation.kt @@ -2,6 +2,8 @@ package com.lumenpearson.lessons.ui.diary import androidx.annotation.StringRes import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.diary.DiaryDateRange +import com.lumenpearson.lessons.core.data.diary.DiaryWindows import com.lumenpearson.lessons.core.data.repository.DiaryEdit import com.lumenpearson.lessons.core.data.repository.DiaryField import com.lumenpearson.lessons.core.data.repository.DiaryHomework @@ -11,11 +13,8 @@ import com.lumenpearson.lessons.core.data.repository.DiaryMarkKind import com.lumenpearson.lessons.core.data.repository.DiaryPeriod import com.lumenpearson.lessons.core.data.repository.DiaryRepository import java.time.Clock -import java.time.DayOfWeek import java.time.LocalDate -import java.time.LocalDateTime import java.time.ZoneId -import java.time.temporal.TemporalAdjusters /** * Everything the diary screens decide, with nothing on screen. @@ -64,29 +63,22 @@ internal val DiaryLesson.correctable: Boolean get() = target.isNotBlank() internal val DiaryHomework.correctable: Boolean get() = target.isNotBlank() /** - * The zone the diary's own days are cut at. + * The date it is where the diary is. * - * Every other date in this app comes from the class's zone, because the project - * serves schools across eleven of them. The diary has no class behind it and - * needs none: it is one city's service, and that city keeps Moscow time. The - * server cuts the same boundary in `providers/petersburg`, and the two have to - * agree - a phone that highlighted a different day as today than the server - * served the week for would look like the diary had lost a day. - */ -val DiaryZone: ZoneId = ZoneId.of("Europe/Moscow") - -/** - * The date it is in the city whose diary this is. + * [zone] is the session's — `DiaryTarget.zoneId()`, which is the zone the server + * told this phone at registration and cuts the diary's days at. It used to be + * Moscow for every diary, which was true while the only diary was Petersburg's; + * a «Сетевой город» pupil in Tomsk would have opened on yesterday for four + * hours every evening. Not `LocalDate.now()` either: a pupil travelling, or a + * phone left on another zone, would open on a day the diary has not reached. * - * Not `LocalDate.now()`: a pupil travelling east, or a phone left on another - * zone, would otherwise open the diary on a day the diary has not reached. + * [DiaryWindows.today] is the rule; this is the name the screens read it by. */ -fun diaryToday(clock: Clock = Clock.systemUTC()): LocalDate = - LocalDateTime.ofInstant(clock.instant(), DiaryZone).toLocalDate() +fun diaryToday(zone: ZoneId, clock: Clock = Clock.systemUTC()): LocalDate = + DiaryWindows.today(zone, clock) -/** Monday of the week [date] falls in; the week view's anchor. */ -fun diaryWeekStart(date: LocalDate): LocalDate = - date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) +/** Monday of the week [date] falls in; the week view's anchor, and the cache's key. */ +fun diaryWeekStart(date: LocalDate): LocalDate = DiaryWindows.weekStart(date) /** * Groups a week's worth of lessons and homework into days. @@ -206,31 +198,22 @@ fun DiaryMarkKind.toneIndex(): Int = when (this) { } /** - * The window the marks screen asks for, as [from] to [to] inclusive. - * - * The server refuses anything wider than - * [DiaryRepository.MAX_RANGE_DAYS] with a 422, and a school quarter is - * routinely longer than that, so the term cannot simply be passed through. The - * rule, in order: + * The window the marks screen asks for, [from][DiaryDateRange.from] to + * [to][DiaryDateRange.to] inclusive. * - * * end at today, or at the end of the term when the term is already over — - * asking for marks that have not been given yet returns nothing and says - * nothing; - * * start at the beginning of the term, when that fits; - * * otherwise start as far back as the limit allows, so what is shown is the - * most recent 62 days of the term rather than its first 62. + * The same type the import fills the cache with, because the two have to be + * the same range: a window worked out twice is a window that will one day be + * worked out differently, and a cache that is never hit says nothing about it. */ -data class DiaryRange(val from: LocalDate, val to: LocalDate) +typealias DiaryRange = DiaryDateRange -/** @see DiaryRange */ -fun diaryGradeRange(today: LocalDate, period: DiaryPeriod? = null): DiaryRange { - val limit = DiaryRepository.MAX_RANGE_DAYS - val end = period?.endsOn?.takeIf { it.isBefore(today) } ?: today - val widest = end.minusDays(limit) - val start = period?.startsOn?.takeIf { it.isAfter(widest) } ?: widest - // A term whose start is somehow after its end cannot narrow anything. - return DiaryRange(from = minOf(start, end), to = end) -} +/** + * The current term, cut to what the server will serve — [DiaryWindows.gradeWindow], + * which says how. The server refuses anything wider than + * [DiaryRepository.MAX_RANGE_DAYS], and a school quarter is routinely longer. + */ +fun diaryGradeRange(today: LocalDate, period: DiaryPeriod? = null): DiaryRange = + DiaryWindows.gradeWindow(today, period) /** * One row's correctable fields, as the sheet needs them. diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt new file mode 100644 index 00000000..b0ee992e --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt @@ -0,0 +1,148 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.pluralStringResource +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.designsystem.text.correctedString + +/** + * The one place a [DiarySignInProblem] becomes words. + * + * Every screen that can fail to get somebody into their diary — the sign-in + * form in settings, the diary home, and the onboarding's school search, sign-in + * and import — switches on the same type and says what this file says. Two + * mappings were how «слишком много попыток» came to read «Не получилось: 429» + * and a diary switched off on the server read «дневник не отвечает, попробуйте + * позже», which no amount of waiting fixes (#153). + * + * The sentence is picked here as a value ([DiaryProblemMessage]) and only then + * read out of the resources, so which sentence a problem gets is a JVM test + * rather than a screenshot, and every `diary_problem_*` name is referenced from + * a `when` that the compiler holds exhaustive. + * + * Where a problem carries the diary's host, the sentence names it: «не + * отвечает» about a named server is something a family can repeat to the + * school, and «не отвечает» alone is not. + */ +sealed interface DiaryProblemMessage { + + /** A plain string, with its format arguments. */ + data class Line(@param:StringRes val id: Int, val args: List = emptyList()) : + DiaryProblemMessage + + /** A sentence with a count in it; [count] is also its only argument. */ + data class Counted(@param:PluralsRes val id: Int, val count: Int) : DiaryProblemMessage + + /** + * [main], then what the diary itself said, when it said something. + * The diary's words are shown, never interpreted: they are the one part of + * a refusal that can say «учётная запись заблокирована» rather than + * «неверный пароль». + */ + data class WithUpstream(val main: DiaryProblemMessage, val upstream: String) : + DiaryProblemMessage +} + +/** Which sentence [problem] gets. Pure, so a test can hold every case of it. */ +fun diaryProblemMessage(problem: DiarySignInProblem): DiaryProblemMessage = when (problem) { + is DiarySignInProblem.WrongPassword -> { + val main = DiaryProblemMessage.Line(R.string.diary_problem_wrong_password) + val said = problem.upstreamMessage?.trim()?.take(UpstreamMessageMax) + if (said.isNullOrEmpty()) main else DiaryProblemMessage.WithUpstream(main, said) + } + is DiarySignInProblem.GosuslugiOnly -> line(R.string.diary_problem_gosuslugi_only) + is DiarySignInProblem.ProviderUnavailable -> + hosted(problem.host, R.string.diary_problem_host_down, R.string.diary_problem_unavailable) + is DiarySignInProblem.ProviderRefusesPhone -> + hosted(problem.host, R.string.diary_problem_host_refuses_phone, R.string.diary_problem_refuses_phone) + is DiarySignInProblem.ProviderUntrusted -> + hosted(problem.host, R.string.diary_problem_host_untrusted, R.string.diary_problem_untrusted) + // Without a host this is our server's 502: the diary answered it, not the + // phone, and the sentence that says so already exists. + is DiarySignInProblem.ProviderUnreadable -> + hosted(problem.host, R.string.diary_problem_host_unreadable, R.string.diary_problem_unreadable) + is DiarySignInProblem.ProviderOffline -> + hosted(problem.host, R.string.diary_problem_host_offline, R.string.diary_problem_offline_upstream) + is DiarySignInProblem.Timeout -> + hosted(problem.host, R.string.diary_problem_host_timeout, R.string.diary_problem_timeout) + DiarySignInProblem.Offline -> line(R.string.diary_problem_offline) + DiarySignInProblem.RegisterUnreachable -> line(R.string.diary_problem_register_unreachable) + DiarySignInProblem.ServerMissing -> line(R.string.diary_problem_server_missing) + DiarySignInProblem.ServerTooOld -> line(R.string.diary_problem_server_too_old) + DiarySignInProblem.ServerDisabled -> line(R.string.diary_problem_server_disabled) + DiarySignInProblem.RegionNotServed -> line(R.string.diary_problem_region_not_served) + DiarySignInProblem.ServerRefusedSession -> line(R.string.diary_problem_server_refused_session) + DiarySignInProblem.ServerAddressRefused -> line(R.string.diary_problem_server_address_refused) + DiarySignInProblem.NoStudent -> line(R.string.diary_problem_no_student) + is DiarySignInProblem.TooManyAttempts -> problem.retryAfterSeconds + ?.takeIf { it > 0 } + // Rounded up: «через 0 минут» for a wait of forty seconds is a promise + // the next attempt will break. + ?.let { seconds -> DiaryProblemMessage.Counted(R.plurals.diary_problem_too_many_wait, minutesFor(seconds)) } + ?: line(R.string.diary_problem_too_many) + DiarySignInProblem.SessionAgedOut -> line(R.string.diary_problem_session_aged_out) + DiarySignInProblem.LoginTooShort -> line(R.string.diary_problem_login_too_short) + DiarySignInProblem.ReauthRequired -> line(R.string.diary_problem_reauth) + DiarySignInProblem.SignInRequired -> line(R.string.diary_problem_signed_out) + is DiarySignInProblem.Unexpected -> DiaryProblemMessage.Line( + R.string.diary_problem_unknown, + listOf(problem.detail?.takeIf { it.isNotBlank() } ?: problem.message.orEmpty()), + ) +} + +/** + * Whether the card or dialog showing [this] offers «Повторить». + * + * The data layer already decided what helps next ([DiarySignInProblem.action]); + * a screen that re-derived it would offer a retry for a diary switched off on + * the server, which answers the same way every time. + */ +val DiarySignInProblem.offersRetry: Boolean + get() = action == DiarySignInProblem.Action.RETRY + +/** [diaryProblemMessage], read out of the resources — through correction mode. */ +@Composable +fun DiarySignInProblem.asText(): String = diaryProblemMessage(this).asText() + +@Composable +private fun DiaryProblemMessage.asText(): String = when (this) { + is DiaryProblemMessage.Line -> + if (args.isEmpty()) correctedString(id) else correctedString(id, *args.toTypedArray()) + // Plurals are not correctable: correction mode keys by string resource, + // and `ManagementSheets` makes the same trade for the same reason. + is DiaryProblemMessage.Counted -> pluralStringResource(id, count, count) + is DiaryProblemMessage.WithUpstream -> + main.asText() + " " + correctedString(R.string.diary_problem_upstream_said, upstream) +} + +/** + * The problem a failed diary **read** is, for the cases that have one; `null` + * for the three that are about what this app asked rather than about getting + * in, which keep sentences of their own. + */ +fun DiaryFailure.asProblem(): DiarySignInProblem? = when (this) { + DiaryFailure.UnknownStudent, DiaryFailure.BadRange, DiaryFailure.Rejected -> null + else -> DiarySignInProblem.of(this) +} + +private fun line(@StringRes id: Int) = DiaryProblemMessage.Line(id) + +private fun hosted(host: String?, @StringRes withHost: Int, @StringRes without: Int) = + host?.takeIf { it.isNotBlank() } + ?.let { DiaryProblemMessage.Line(withHost, listOf(it)) } + ?: DiaryProblemMessage.Line(without) + +private fun minutesFor(seconds: Long): Int = + ((seconds + SecondsPerMinute - 1) / SecondsPerMinute).coerceIn(1, Int.MAX_VALUE.toLong()).toInt() + +private const val SecondsPerMinute = 60L + +/** + * Enough for any sentence a diary writes about a refusal; past it the text is + * a page somebody's server sent by mistake, and a dialog is not where to read it. + */ +private const val UpstreamMessageMax = 200 diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt index 605d2adb..01a1f52f 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt @@ -15,6 +15,9 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.Logout +import androidx.compose.material.icons.rounded.CalendarViewWeek +import androidx.compose.material.icons.rounded.CloudOff +import androidx.compose.material.icons.rounded.Grade import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme @@ -26,13 +29,17 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile import com.lumenpearson.lessons.core.designsystem.component.EmptyState +import com.lumenpearson.lessons.core.designsystem.component.GroupRow import com.lumenpearson.lessons.core.designsystem.component.GroupItem import com.lumenpearson.lessons.core.designsystem.component.LessonsBottomSheet import com.lumenpearson.lessons.core.designsystem.component.PillChip @@ -51,34 +58,44 @@ import com.lumenpearson.lessons.core.designsystem.theme.LocalBottomBarSpace import com.lumenpearson.lessons.core.designsystem.theme.ReportScrollOffset import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur +import com.lumenpearson.lessons.core.designsystem.theme.accentTone import com.lumenpearson.lessons.core.designsystem.theme.errorTone import com.lumenpearson.lessons.core.designsystem.theme.rowContainer import com.lumenpearson.lessons.core.designsystem.theme.statusBarSpace import androidx.compose.ui.draw.clip +import com.lumenpearson.lessons.ui.common.syncedAtLabel /** - * The Petersburg diary, as one page of the settings tree. + * The diary: a page of the settings tree on a phone in a class, and the home + * itself on a phone in none. * - * Why here and not as a fourth tab: the tabs are the class timetable, which - * every install has the moment it joins a class. The diary is a second account - * in a foreign service that most users of this app will never have, and a tab - * for it would put a sign-in wall in the bottom bar of everybody who does not — - * permanently, because the toolbar does not hide destinations. `HomeTab` also - * lives in `:core:model`, where the widget and the "default tab" preference + * In a class it is a section reached from the settings root, not a fourth tab: + * the tabs are the class timetable, which every install has the moment it joins + * a class, and a tab for a second account in a foreign service would put a + * sign-in wall in the bottom bar of everybody who does not have one. `HomeTab` + * also lives in `:core:model`, where the widget and the "default tab" preference * read it, so a fourth entry there would appear in two more places that have - * nothing to do with a diary. A section reached from the settings root costs - * one row on a page people already visit, and it comes with the shell's title, - * its back gesture and its slide for free. + * nothing to do with a diary. + * + * On a phone whose only account is the diary ([asHome]), there is no timetable + * to be a tab beside, and the diary is what the app is: the shell draws this + * page where the tabs would be and carries the diary's own two halves in its + * toolbar, so the in-page picker goes; and the sign-out moves to the account + * page in settings, next to the rest of what the account is, because on the + * home it would be one tap from the first screen somebody sees. * * The page is a `LazyColumn` of the same shape as every settings section — same * padding, same status-bar inset, same scroll report for the top fade — rather * than a screen with a scaffold of its own. + * + * @param asHome drawn as the home of the diary mode rather than as a section. */ @Composable fun DiaryScreen( /** Whether the server address is plain `http://`; see `DiarySignInScreen`. */ insecureServer: Boolean = false, modifier: Modifier = Modifier, + asHome: Boolean = false, viewModel: DiaryViewModel = viewModel(factory = DiaryViewModel.Factory), ) { val state by viewModel.uiState.collectAsStateWithLifecycle() @@ -100,6 +117,7 @@ fun DiaryScreen( if (confirmSignOut) { DiarySignOutSheet( + leavesTheApp = asHome, onDismiss = { confirmSignOut = false }, onConfirm = { confirmSignOut = false @@ -125,14 +143,25 @@ fun DiaryScreen( item(key = "loading") { SkeletonGroup(rows = 4) } } + // Choosing which diary, before a form for it: a phone whose class named + // none, or somebody who is not in Petersburg (r11, gap 2). + state.picking && state.session == null -> DiaryPickerPage( + onPicked = viewModel::choose, + onCancel = viewModel::cancelPicking, + modifier = modifier, + ) + state.session == null || state.reauth -> DiarySignInScreen( reauth = state.reauth, - knownLogin = state.session?.login.orEmpty(), + knownLogin = state.knownLogin, insecureServer = insecureServer, busy = state.signingIn, failed = state.signInError != null, onSignIn = viewModel::signIn, onEdited = viewModel::clearSignInError, + place = state.place, + schoolName = state.signInTarget.schoolName, + onChangeDiary = viewModel::startPicking, modifier = modifier, ) @@ -150,6 +179,20 @@ fun DiaryScreen( ) } + // The rows below are what the phone saved, not what the diary said + // just now — said once, above them, with when they were saved, in + // the diary's zone rather than the phone's. + state.savedAt?.let { savedAt -> + item(key = "saved-at") { + DiarySavedAtNote( + text = correctedString( + R.string.diary_offline_saved_at, + syncedAtLabel(savedAt.toEpochMilli(), state.zone), + ), + ) + } + } + if (state.showStudentPicker) { item(key = "students") { DiaryStudentPicker( @@ -160,7 +203,9 @@ fun DiaryScreen( } } - item(key = "tabs") { + // On the home the toolbar carries the two halves; a second switch + // for the same thing under the header would be one too many. + if (!asHome) item(key = "tabs") { SegmentedPicker( items = DiaryTab.entries, selectedItem = state.tab, @@ -191,7 +236,7 @@ fun DiaryScreen( else -> diaryGrades(state, viewModel) } - item(key = "sign-out") { + if (!asHome) item(key = "sign-out") { RoundedCardContainer { GroupItem( title = correctedString(R.string.diary_sign_out), @@ -215,7 +260,7 @@ fun DiaryScreen( * which is where a retry button belongs. */ @Composable -private fun DiaryPage( +internal fun DiaryPage( modifier: Modifier = Modifier, content: LazyListScope.() -> Unit, ) { @@ -247,7 +292,7 @@ private fun DiaryPage( * with one option is a control that can only ever be pressed to no effect. */ @Composable -private fun DiaryStudentPicker( +internal fun DiaryStudentPicker( students: List, selectedId: Long?, onSelect: (Long) -> Unit, @@ -281,57 +326,53 @@ internal fun DiaryFailureCard( modifier: Modifier = Modifier, ) { if (failure == null) return + // Only the answers worth pressing a button about get one — the data layer's + // own verdict (`DiarySignInProblem.action`). A diary switched off on the + // server, or a request this app got wrong, answers the same way twice. + val retry = failure.asProblem()?.offersRetry == true EmptyState( title = correctedString(R.string.diary_failure_title), description = failure.asText(), modifier = modifier, - // Only the answers worth pressing a button about get one. A 502 means - // the server has to be fixed and a 422 means this app asked wrongly; - // pressing "повторить" would produce the same answer, twice. - actionLabel = correctedString(R.string.diary_retry).takeIf { failure.isRetryable }, - onActionClick = onRetry.takeIf { failure.isRetryable }, + actionLabel = correctedString(R.string.diary_retry).takeIf { retry }, + onActionClick = onRetry.takeIf { retry }, ) } -/** Whether pressing a button again could plausibly give a different answer. */ -private val DiaryFailure.isRetryable: Boolean - get() = this is DiaryFailure.Unavailable || - this is DiaryFailure.Offline || - this is DiaryFailure.Unexpected - /** - * Every failure this section can show, as one sentence each. + * Every failure a diary read can end in, as one sentence each. * - * [DiaryFailure.SignInRequired] reads as "sign in again" here; on the sign-in - * form itself the same failure means the credentials were refused, which is - * why that screen overrides this one case and no other. + * Three are about what this app asked — a pupil the account does not have, a + * range the server refuses, a correction it will not file — and keep their own + * sentences. Everything else is a way of not getting into the diary, and is + * said by `DiaryProblemText`, the one mapping there is: a 429 as too many + * attempts, a diary switched off on the server as switched off, a refused + * server address as the diary refusing our server (#153). */ @Composable internal fun DiaryFailure.asText(): String = when (this) { - DiaryFailure.SignInRequired -> correctedString(R.string.diary_error_signed_out) - // Shown only if it ever leaks into a card: the state holder turns it into - // the password prompt long before a screen could render it. - DiaryFailure.ReauthRequired -> correctedString(R.string.diary_reauth_title) DiaryFailure.UnknownStudent -> correctedString(R.string.diary_error_student) DiaryFailure.BadRange -> correctedString(R.string.diary_error_range) - DiaryFailure.Unreadable -> correctedString(R.string.diary_error_unreadable) - DiaryFailure.Unavailable -> correctedString(R.string.diary_error_unavailable) - // Stand-ins until `DiaryProblemText` gives each its own sentence. «Try - // later» is right for a throttle and only half right for the other two — - // a diary switched off on the server, or one refusing its address, will - // not come back by waiting — so the screen half of #153 is not done here. - DiaryFailure.Disabled, - DiaryFailure.ServerAddressRefused, - is DiaryFailure.Throttled, - -> correctedString(R.string.diary_error_unavailable) // The server refusing a correction it could never apply. Its own message, // because "не получилось: 422" is not something to put in front of anybody. DiaryFailure.Rejected -> correctedString(R.string.diary_error_rejected) - is DiaryFailure.Offline -> correctedString(R.string.diary_error_offline) - is DiaryFailure.Unexpected -> correctedString( - R.string.diary_error_unknown, - reason.message?.takeIf { it.isNotBlank() } ?: message.orEmpty(), - ) + else -> DiarySignInProblem.of(this).asText() +} + +/** The line above the rows when they are what the phone saved. */ +@Composable +private fun DiarySavedAtNote(text: String) { + RoundedCardContainer { + GroupRow { + AccentIconTile(icon = Icons.Rounded.CloudOff, tone = accentTone(3)) + Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + } + } } /** @@ -365,31 +406,39 @@ private fun DiarySignInOutcomeDialog( is DiarySignInOutcome.Failed -> LessonsDialog( title = correctedString(R.string.diary_sign_in_failed_title), - // `asSignInText`, not `asText`: on this one call a 401 means "the - // diary refused these credentials", and everywhere else it means - // "your session is gone". Saying the second here would send - // somebody to sign in again on the screen they are already on. - message = outcome.failure.asSignInText(), + // The one mapping, which knows a refused password from a diary + // that is down, a throttle and a server that is switched off. + message = outcome.problem.asText(), confirmLabel = correctedString(R.string.diary_dialog_dismiss), onDismiss = onDismiss, ) } } -/** The label of a tab in the segmented picker. */ -private fun DiaryTab.labelRes(): Int = when (this) { +/** The label of a tab — in the segmented picker, and in the toolbar on the home. */ +internal fun DiaryTab.labelRes(): Int = when (this) { DiaryTab.SCHEDULE -> R.string.diary_tab_schedule DiaryTab.GRADES -> R.string.diary_tab_grades } +/** The glyph of a tab in the toolbar, on the diary home. */ +internal val DiaryTab.icon: ImageVector + get() = when (this) { + DiaryTab.SCHEDULE -> Icons.Rounded.CalendarViewWeek + DiaryTab.GRADES -> Icons.Rounded.Grade + } + /** - * The confirmation, which exists to say what signing out does *not* do. + * The confirmation, which exists to say what signing out does *not* do — and, + * when the diary is the phone's only account ([leavesTheApp]), what it does: + * the phone goes back to the start, and what was saved on it goes. * - * The two accounts are separate and nothing on screen says so until the moment - * somebody is about to leave one of them. + * In a class the two accounts are separate and nothing on screen says so until + * the moment somebody is about to leave one of them. */ @Composable -private fun DiarySignOutSheet( +internal fun DiarySignOutSheet( + leavesTheApp: Boolean, onDismiss: () -> Unit, onConfirm: () -> Unit, ) { @@ -398,7 +447,9 @@ private fun DiarySignOutSheet( title = correctedString(R.string.diary_sign_out_title), ) { Text( - text = correctedString(R.string.diary_sign_out_message), + text = correctedString( + if (leavesTheApp) R.string.diary_sign_out_home_text else R.string.diary_sign_out_message, + ), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = ScreenPadding), diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt index fb16d9e7..a33b87d2 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInScreen.kt @@ -3,22 +3,14 @@ package com.lumenpearson.lessons.ui.diary import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.Login +import androidx.compose.material.icons.automirrored.rounded.MenuBook import androidx.compose.material.icons.rounded.Lock -import androidx.compose.material.icons.rounded.Visibility -import androidx.compose.material.icons.rounded.VisibilityOff -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -26,15 +18,12 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.R -import com.lumenpearson.lessons.core.data.repository.DiaryFailure import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile -import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem +import com.lumenpearson.lessons.core.designsystem.component.GroupItem +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem import com.lumenpearson.lessons.core.designsystem.component.GroupRow import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer import com.lumenpearson.lessons.core.designsystem.component.ScreenHeader @@ -53,15 +42,22 @@ import com.lumenpearson.lessons.core.designsystem.theme.statusBarSpace * They are one because they differ by exactly two things — the heading, and * whether the login field can be edited — and because the second one has to * arrive with the login already filled in. Splitting them would have been two - * forms to keep in step for the sake of a heading. + * forms to keep in step for the sake of a heading. The fields themselves are + * [DiaryCredentialFields], which the onboarding's sign-in uses too. * - * Neither the login nor the password is `rememberSaveable`: saved state is - * written to the process's saved-instance bundle, and a password does not - * belong there. The cost is that a rotation mid-typing clears the field, which - * is the right trade for the one field in this app that is a secret. + * The form says, before anything is typed, which diary it signs in to and the + * one host the password will go to ([place]) — the privacy policy promises + * exactly that, and it is the one thing about this integration a family has a + * right to be suspicious about. * * @param reauth true when the session died upstream and only the password is * being asked for; [knownLogin] is then shown rather than typed. + * @param place what the catalog says about the diary this form signs in to; + * `null` until it has been read, and then no host is named rather than a + * guessed one. + * @param schoolName the school, when the target carries one («Сетевой город»). + * @param onChangeDiary opens the diary picker; `null` hides the way to it — + * on a re-authentication, which is to the same account by definition. * @param failed whether the last attempt was refused — the fields go red and * nothing else. *What* went wrong is said by the pop-up the caller hosts, not * here: a line of text below two fields and above a button is under the @@ -80,15 +76,11 @@ fun DiarySignInScreen( onSignIn: (login: String, password: String) -> Unit, modifier: Modifier = Modifier, onEdited: () -> Unit = {}, + place: DiaryPlace? = null, + schoolName: String? = null, + onChangeDiary: (() -> Unit)? = null, ) { var login by remember(knownLogin) { mutableStateOf(knownLogin) } - var password by remember { mutableStateOf("") } - var revealed by remember { mutableStateOf(false) } - - val canSubmit = password.isNotBlank() && login.isNotBlank() && !busy - fun submit() { - if (canSubmit) onSignIn(login, password) - } Column( modifier = modifier @@ -116,17 +108,22 @@ fun DiarySignInScreen( }, ) + DiaryWhereRow( + place = place, + schoolName = schoolName, + onChange = onChangeDiary.takeUnless { reauth || busy }, + ) + // Said before the password is typed, not after it has been sent. // // `network_security_config.xml` permits cleartext for every host on // purpose — the realistic deployment is uvicorn on a machine in the // school, reached by LAN address, and no public CA issues a - // certificate for one of those. That bargain was struck when the only - // thing crossing the wire was a timetable. This screen is where it - // stopped being true: the password below is a parent's password for - // dnevnik2.petersburgedu.ru, a third party's service, and it goes to - // whatever address was typed in settings through the same client as - // everything else. On http:// anybody on the same Wi-Fi reads it. + // certificate for one of those. The password is not what that + // costs: it goes over https to the diary's own origin and nowhere + // else. What crosses an http:// server is what the diary hands back — + // the session this form registers with our server, and the key to it + // — and on http:// anybody on the same Wi-Fi can take either. if (insecureServer) { RoundedCardContainer { GroupRow { @@ -139,107 +136,98 @@ fun DiarySignInScreen( } } - RoundedCardContainer { - GroupRow { - OutlinedTextField( - value = login, - onValueChange = { - login = it.trim() - onEdited() - }, - modifier = Modifier.fillMaxWidth(), - label = { Text(correctedString(R.string.diary_login_label)) }, - singleLine = true, - // The login is not asked for again on a re-auth: it is - // already known, and a field that can be changed there - // invites signing in as somebody else by accident. - enabled = !reauth && !busy, - isError = failed, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Email, - imeAction = ImeAction.Next, - ), - ) - } - - GroupRow { - OutlinedTextField( - value = password, - onValueChange = { - password = it - onEdited() - }, - modifier = Modifier.fillMaxWidth(), - label = { Text(correctedString(R.string.diary_password_label)) }, - singleLine = true, - enabled = !busy, - isError = failed, - visualTransformation = if (revealed) { - VisualTransformation.None - } else { - PasswordVisualTransformation() - }, - trailingIcon = { - IconButton(onClick = { revealed = !revealed }) { - Icon( - imageVector = if (revealed) { - Icons.Rounded.VisibilityOff - } else { - Icons.Rounded.Visibility - }, - contentDescription = correctedString( - if (revealed) { - R.string.diary_password_hide - } else { - R.string.diary_password_reveal - }, - ), - ) - } - }, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Password, - imeAction = ImeAction.Done, - ), - keyboardActions = KeyboardActions(onDone = { submit() }), - ) - } - - GroupActionItem( - label = correctedString(R.string.diary_sign_in_action), - icon = Icons.AutoMirrored.Rounded.Login, - enabled = canSubmit, - busy = busy, - onClick = ::submit, - ) - } + DiaryCredentialFields( + login = login, + onLoginChange = { login = it }, + onSubmit = onSignIn, + loginEditable = !reauth, + busy = busy, + failed = failed, + onEdited = onEdited, + ) - // The promise the server actually keeps, said where it matters: on the - // screen that is asking for the password. It is the one thing about - // this integration a user has a right to be suspicious about. + // The promise the app actually keeps, said where it matters: on the + // screen that is asking for the password, with the one host it goes to. RoundedCardContainer { GroupRow(verticalAlignment = Alignment.Top) { AccentIconTile(icon = Icons.Rounded.Lock, tone = accentTone(1)) - Text( - text = correctedString(R.string.diary_password_notice), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + place?.host?.let { host -> + Text( + text = correctedString(R.string.diary_password_destination, host), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + Text( + text = correctedString(R.string.diary_password_notice), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } } } /** - * What a failure says about a sign-in attempt. - * - * [DiaryFailure.SignInRequired] means "the diary refused these credentials" - * *here* and "your session is gone" everywhere else, which is the one place the - * two readings of a 401 differ — and the reason this is its own function rather - * than one shared sentence. + * Which diary the form signs in to — the system, then the region and the + * school — with the way to another when there is one. */ @Composable -internal fun DiaryFailure.asSignInText(): String = when (this) { - DiaryFailure.SignInRequired -> correctedString(R.string.diary_error_credentials) - else -> asText() +private fun DiaryWhereRow( + place: DiaryPlace?, + schoolName: String?, + onChange: (() -> Unit)?, +) { + val system = place?.systemName() + val detail = listOfNotNull(place?.regionName(), schoolName?.takeIf { it.isNotBlank() }) + .joinToString(" · ") + .ifBlank { null } + // Nothing to name and nothing to change: the row would be a blank card. + if (system == null && onChange == null) return + val title = system?.let { correctedString(R.string.diary_sign_in_where, it) } + ?: correctedString(R.string.diary_pick_title) + RoundedCardContainer { + if (onChange != null) { + GroupLinkItem( + title = title, + subtitle = detail, + icon = Icons.AutoMirrored.Rounded.MenuBook, + tone = accentTone(4), + value = correctedString(R.string.diary_pick_change), + onClick = onChange, + ) + } else { + GroupItem( + title = title, + subtitle = detail, + icon = Icons.AutoMirrored.Rounded.MenuBook, + tone = accentTone(4), + ) + } + } +} + +/** + * The region's name in the language the app is showing. Names live in the + * catalog in both languages rather than in string resources (K16), so the + * choice between them is made here, by the composition — which below Android + * 13 is the only place that knows which language the reader chose. + */ +@Composable +internal fun DiaryPlace.regionName(): String? = localized(regionRu, regionEn) + +/** @see regionName */ +@Composable +internal fun DiaryPlace.systemName(): String? = localized(systemRu, systemEn) + +@Composable +internal fun localized(ru: String?, en: String?): String? { + val russian = Locale.current.language == "ru" + val first = if (russian) ru else en + return first?.takeIf { it.isNotBlank() } ?: (if (russian) en else ru)?.takeIf { it.isNotBlank() } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index 0aba1442..da37c767 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -6,6 +6,13 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.lumenpearson.lessons.core.data.di.Graph +import com.lumenpearson.lessons.core.data.diary.DiaryCache +import com.lumenpearson.lessons.core.data.diary.DiaryCachedMarks +import com.lumenpearson.lessons.core.data.diary.DiaryCachedPeriods +import com.lumenpearson.lessons.core.data.diary.DiaryCachedStudents +import com.lumenpearson.lessons.core.data.diary.DiaryCachedWeek +import com.lumenpearson.lessons.core.data.diary.diaryIsFresh +import com.lumenpearson.lessons.core.data.repository.DiaryBinding import com.lumenpearson.lessons.core.data.repository.DiaryFailure import com.lumenpearson.lessons.core.data.repository.DiaryField import com.lumenpearson.lessons.core.data.repository.DiaryPeriod @@ -14,14 +21,21 @@ import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryStudent import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Clock +import java.time.Instant import java.time.LocalDate +import java.time.ZoneId import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -38,13 +52,31 @@ import kotlinx.coroutines.launch * than one 401 for both meanings. * @property student the pupil everything below is about; `null` only while the * list is still loading or empty. + * @property zone the zone the diary cuts its days at — the session's, which the + * server named at registration. Moscow until a session says otherwise, which + * is what every session before the second diary was. + * @property signInTarget which diary the form would sign in to: one picked on + * this screen, else the live session's, else the one a bare `401` left, else + * the class's binding, else Petersburg — the one diary this form ever offered + * before it could be asked for another. Its login is a placeholder; the typed + * one replaces it on submit. + * @property place what the catalog says about [signInTarget] — its names and + * the host the password goes to — or `null` until the catalog has been read. + * @property picking the diary picker is open in place of the form. + * @property savedAt the rows on screen are what was saved at this moment, + * shown because the diary could not be reached just now; `null` when they + * are the diary's answer of this visit. */ data class DiaryUiState( val ready: Boolean = false, val session: DiarySession? = null, val reauth: Boolean = false, val signingIn: Boolean = false, - val signInError: DiaryFailure? = null, + /** + * Why the last sign-in failed, for the form to paint itself by — cleared by + * the next keystroke. The sentence is [signInOutcome]'s to say. + */ + val signInError: DiarySignInProblem? = null, /** * What the last sign-in attempt came to, waiting to be shown once. * @@ -56,13 +88,17 @@ data class DiaryUiState( * because the form is no longer on screen by then. */ val signInOutcome: DiarySignInOutcome? = null, + val signInTarget: DiaryTarget = DiaryTarget.petersburg(""), + val place: DiaryPlace? = null, + val picking: Boolean = false, val signingOut: Boolean = false, val students: List = emptyList(), val studentsLoading: Boolean = false, val studentsError: DiaryFailure? = null, val selectedStudentId: Long? = null, val tab: DiaryTab = DiaryTab.SCHEDULE, - val weekStart: LocalDate = diaryWeekStart(diaryToday()), + val zone: ZoneId = DefaultDiaryZone, + val weekStart: LocalDate = diaryWeekStart(diaryToday(DefaultDiaryZone)), val scheduleLoading: Boolean = false, val scheduleError: DiaryFailure? = null, val days: List = emptyList(), @@ -70,13 +106,14 @@ data class DiaryUiState( val gradesError: DiaryFailure? = null, val subjects: List = emptyList(), val gradeRange: DiaryRange? = null, + val savedAt: Instant? = null, /** The row whose corrections are open in a sheet, or `null` for none. */ val editing: DiaryCorrections? = null, val savingEdit: Boolean = false, val editError: DiaryFailure? = null, ) { /** - * The date it is in the city whose diary this is. + * The date it is where the diary is. * * Read on every access rather than frozen into the state, because the * state object is built once when the screen opens and carried forward by @@ -84,7 +121,7 @@ data class DiaryUiState( * the pupil first opened the diary, and a phone left on the screen * overnight kept offering «на этой неделе» for the week that had ended. */ - val today: LocalDate get() = diaryToday() + val today: LocalDate get() = diaryToday(zone) val student: DiaryStudent? get() = students.firstOrNull { it.id == selectedStudentId } @@ -96,8 +133,14 @@ data class DiaryUiState( /** Whether stepping back to this week would move anything. */ val canReturnToThisWeek: Boolean get() = weekStart != diaryWeekStart(today) + + /** The login the form starts with: the account's, when one is known. */ + val knownLogin: String get() = session?.login ?: signInTarget.login } +/** Petersburg's zone, which every diary session had before the second diary. */ +private val DefaultDiaryZone: ZoneId = ZoneId.of(DiaryTarget.PETERSBURG_ZONE) + /** * The result of one sign-in attempt, for the pop-up that reports it. * @@ -112,39 +155,67 @@ sealed interface DiarySignInOutcome { /** @param login the account, echoed back so it can be checked for typos. */ data class Succeeded(val login: String) : DiarySignInOutcome - data class Failed(val failure: DiaryFailure) : DiarySignInOutcome + /** @param problem said by `DiaryProblemText`, the one mapping there is. */ + data class Failed(val problem: DiarySignInProblem) : DiarySignInOutcome } /** - * The diary section's state holder. + * The diary section's state holder — and, on a phone in no class, the diary + * home's. * * It owns three loads — the pupils, a week of the timetable, a term of marks — - * and one rule that runs through all of them: a failure that means "the diary - * logged us out upstream" flips [DiaryUiState.reauth] instead of becoming an - * error message. Anything else is kept as a typed [DiaryFailure] and turned - * into a sentence by the screen, which is the only place that knows how to - * phrase one. + * and two rules that run through all of them. + * + * The first: what the phone saved is drawn before the network answers, and a + * save younger than [com.lumenpearson.lessons.core.data.diary.DiaryFreshFor] + * is not asked for again. The cache is filled by the repository's own reads + * (write-through), so the week drawn from it is the week the diary answered, + * not a second derivation. When the diary cannot be reached, the saved rows + * stay on screen with the moment they were saved, rather than being replaced + * by a failure card over nothing. + * + * The second: a failure that means "the diary logged us out upstream" flips + * [DiaryUiState.reauth] instead of becoming an error message. Anything else is + * kept as a typed [DiaryFailure] and turned into a sentence by the screen, + * which is the only place that knows how to phrase one. * * The password never reaches this class as state: it arrives as an argument to * [signIn], is handed to the repository, and is gone when the call returns. */ class DiaryViewModel( private val repository: DiaryRepository, + private val cache: DiaryCache = NoDiaryCache, + binding: Flow = flowOf(null), + private val describe: suspend (DiaryTarget) -> DiaryPlace? = { null }, + private val clock: Clock = Clock.systemUTC(), ) : ViewModel() { - private val state = MutableStateFlow(DiaryUiState()) + private val state = MutableStateFlow( + DiaryUiState(weekStart = diaryWeekStart(diaryToday(DefaultDiaryZone, clock))), + ) val uiState: StateFlow = state.asStateFlow() /** Cancelled and replaced whenever the pupil, the week or the tab changes. */ private var loadJob: Job? = null + /** The home's start refresh while it runs; see [refreshOnStart]. */ + private var startRefresh: Job? = null + /** Asked for once per pupil: terms do not change while a screen is open. */ private val periods = mutableMapOf() + /** A diary picked on this screen, until a sign-in to it lands. */ + private var chosen: DiaryTarget? = null + + /** What a bare `401` left, and what the class's join said; see [DiaryUiState.signInTarget]. */ + private var storedTarget: DiaryTarget? = null + private var boundTarget: DiaryTarget? = null + init { viewModelScope.launch { repository.session.collect { session -> val had = state.value.session + val zone = session?.target?.zoneId() ?: DefaultDiaryZone state.update { it.copy( ready = true, @@ -156,6 +227,17 @@ class DiaryViewModel( selectedStudentId = if (session == null) null else it.selectedStudentId, days = if (session == null) emptyList() else it.days, subjects = if (session == null) emptyList() else it.subjects, + savedAt = if (session == null) null else it.savedAt, + zone = zone, + // The week follows the zone only while nobody has moved + // it: a session in Tomsk arriving after the screen opened + // on Moscow's date must not leave the pupil on the week + // Moscow was in, and must not undo a week they chose. + weekStart = if (it.weekStart == diaryWeekStart(diaryToday(it.zone, clock))) { + diaryWeekStart(diaryToday(zone, clock)) + } else { + it.weekStart + }, // The correction sheet goes with everything else. A // write that meets a dead token clears the session from // under it, and the sheet would stay on top of the @@ -167,34 +249,89 @@ class DiaryViewModel( editError = if (session == null) null else it.editError, ) } + settleTarget() if (session != null && state.value.students.isEmpty()) loadStudents() } } + viewModelScope.launch { + repository.target.collect { target -> + storedTarget = target + settleTarget() + } + } + viewModelScope.launch { + binding.map { it?.targetFor(login = "") } + .distinctUntilChanged() + .collect { target -> + boundTarget = target + settleTarget() + } + } + } + + /** + * Works out [DiaryUiState.signInTarget] again, and what the catalog says + * about it when that changed. + */ + private fun settleTarget() { + val target = signInTargetOf(chosen, state.value.session, storedTarget, boundTarget) + if (target == state.value.signInTarget && state.value.place != null) return + val sameDiary = state.value.signInTarget.sameDiaryAs(target) + state.update { it.copy(signInTarget = target, place = if (sameDiary) it.place else null) } + if (sameDiary && state.value.place != null) return + viewModelScope.launch { + val place = runCatching { describe(target) }.getOrNull() + // A later target may have arrived while the catalog was read. + if (state.value.signInTarget.sameDiaryAs(target)) { + state.update { it.copy(place = place) } + } + } + } + + /** Opens the diary picker in place of the sign-in form. */ + fun startPicking() { + state.update { it.copy(picking = true) } + } + + /** Closes the picker without changing the diary. */ + fun cancelPicking() { + state.update { it.copy(picking = false) } + } + + /** + * The picker's answer: the next sign-in goes to [target]. Held in memory + * only — it carries no secret, but nothing is stored until the diary has + * said yes, which is when the repository writes the session and its target. + */ + fun choose(target: DiaryTarget) { + chosen = target + state.update { it.copy(picking = false, signInError = null) } + settleTarget() } /** * Signs in, or answers the re-authentication prompt; both are the same call. * - * To the diary this phone already knows — the live session's, or the one a - * bare `401` left behind — so a re-authentication goes to the same - * provider, region and school with only the password typed. With none - * known this form can only mean Petersburg, the one diary it has ever - * offered; choosing another is the diary picker's, not this form's. + * To [DiaryUiState.signInTarget] — so a re-authentication goes to the same + * provider, region and school with only the password typed, and a family + * whose class names its diary signs in to that one without searching. */ fun signIn(login: String, password: String) { if (state.value.signingIn) return viewModelScope.launch { state.update { it.copy(signingIn = true, signInError = null) } - val known = state.value.session?.target ?: repository.target.first() + // Read again rather than taken from the state: the stored target + // is a DataStore read that may not have reached the collector yet. + val known = chosen ?: state.value.session?.target ?: repository.target.first() ?: boundTarget val target = known?.copy(login = login.trim()) ?: DiaryTarget.petersburg(login.trim()) val result = repository.signIn(target, password) - val failure = result.exceptionOrNull()?.let(::signInFailure) + val problem = result.exceptionOrNull()?.let { DiarySignInProblem.of(it) } state.update { it.copy( signingIn = false, - signInError = failure, - reauth = if (failure == null) false else it.reauth, - signInOutcome = failure?.let(DiarySignInOutcome::Failed) + signInError = problem, + reauth = if (problem == null) false else it.reauth, + signInOutcome = problem?.let(DiarySignInOutcome::Failed) // The login as it was typed, not as the server echoed // it: the session row arrives moments later through the // repository's flow, and the pop-up is about the @@ -202,7 +339,8 @@ class DiaryViewModel( ?: DiarySignInOutcome.Succeeded(login), ) } - if (failure == null) { + if (problem == null) { + chosen = null // The pupils are re-read rather than kept: the same phone may // have signed in as a different parent. periods.clear() @@ -219,18 +357,24 @@ class DiaryViewModel( state.update { it.copy(signingOut = true) } repository.signOut() periods.clear() + chosen = null state.update { DiaryUiState( ready = true, - weekStart = diaryWeekStart(it.today), + zone = DefaultDiaryZone, + weekStart = diaryWeekStart(diaryToday(DefaultDiaryZone, clock)), ) } + settleTarget() } } fun selectStudent(id: Long) { if (state.value.selectedStudentId == id) return state.update { it.copy(selectedStudentId = id, days = emptyList(), subjects = emptyList()) } + // Kept, so the next launch — and the start refresh, which reads the + // stored choice — are about the same child. + viewModelScope.launch { runCatching { cache.selectStudent(id) } } reload() } @@ -252,9 +396,52 @@ class DiaryViewModel( reload() } - /** What the "повторить" button on every failure card does. */ + /** + * The week holding [date], on the timetable tab — what a stale widget tap + * asks for when it lands on the diary home rather than on a class calendar. + */ + fun showWeekOf(date: LocalDate) { + val start = diaryWeekStart(date) + if (state.value.weekStart == start && state.value.tab == DiaryTab.SCHEDULE) return + state.update { it.copy(weekStart = start, tab = DiaryTab.SCHEDULE) } + reload() + } + + /** What the "повторить" button on every failure card does: always the network. */ fun retry() { - if (state.value.students.isEmpty()) loadStudents() else reload() + if (state.value.students.isEmpty()) loadStudents(force = true) else reload(force = true) + } + + /** + * The foreground refresh, run by the diary home each time it comes to the + * front: [refresh] is `DiaryImport.refreshIfStale`, which re-reads this week + * and the next when the saved copy is older than + * [com.lumenpearson.lessons.core.data.diary.DiaryFreshFor] — and is the only + * thing that reads the diary without somebody pressing something. + * + * The screen's own week load waits for it and then reads the save again, + * so a cold start asks the diary for the week once and not once per caller: + * the week the refresh just saved is fresh, and the load finds it so. Rows + * already on screen are redrawn from the save when it lands. + */ + fun refreshOnStart(refresh: suspend () -> Result) { + if (startRefresh?.isActive == true) return + val job = viewModelScope.launch { runCatching { refresh() } } + startRefresh = job + viewModelScope.launch { + job.join() + if (loadJob?.isActive != true && state.value.student != null) reload() + } + } + + /** + * Waits for a start refresh that is under way; `true` when there was one, + * so the caller knows the save may have changed under it. + */ + private suspend fun awaitStartRefresh(): Boolean { + val running = startRefresh?.takeIf { it.isActive } ?: return false + running.join() + return true } /** Dismisses the inline sign-in error so the next keystroke starts clean. */ @@ -272,59 +459,90 @@ class DiaryViewModel( reload() } - private fun loadStudents() { + private fun loadStudents(force: Boolean = false) { loadJob?.cancel() - loadJob = viewModelScope.launch { - state.update { it.copy(studentsLoading = true, studentsError = null) } - val result = repository.students() - val found = result.getOrNull() - if (found == null) { - val failure = DiaryFailure.of(result.exceptionOrNull() ?: DiaryFailure.Unavailable) - state.update { - it.copy( - studentsLoading = false, - studentsError = failure.takeUnless { f -> f is DiaryFailure.ReauthRequired }, - reauth = it.reauth || failure is DiaryFailure.ReauthRequired, - ) - } - return@launch + loadJob = viewModelScope.launch { loadStudentsNow(force) } + } + + /** + * The pupils: what was saved first, then the diary's answer unless the save + * is fresh. A choice stored earlier — by the import, or by this screen — is + * the child shown, so a family with two children opens on the one they + * picked rather than on whoever the diary lists first. + */ + private suspend fun loadStudentsNow(force: Boolean) { + val saved = runCatching { cache.students.first() }.getOrNull() ?: NoStudents + val remembered = runCatching { cache.selectedStudentId.first() }.getOrNull() + if (saved.students.isNotEmpty()) applyStudents(saved.students, remembered) + if (!force && saved.students.isNotEmpty() && diaryIsFresh(saved.loadedAt, clock.instant())) { + load(force = false) + return + } + + state.update { + it.copy(studentsLoading = it.students.isEmpty(), studentsError = null) + } + val result = repository.students() + val found = result.getOrNull() + if (found == null) { + val failure = DiaryFailure.of(result.exceptionOrNull() ?: DiaryFailure.Unavailable) + if (saved.students.isNotEmpty() && failure.keepsSavedRows) { + state.update { it.copy(studentsLoading = false, savedAt = saved.loadedAt) } + load(force = false) + return } state.update { it.copy( studentsLoading = false, - students = found, - // Keeps the chosen child across a refresh, and falls back to - // the first one — which for most accounts is the only one, - // and is why the picker is hidden at that size. - selectedStudentId = found.firstOrNull { student -> - student.id == it.selectedStudentId - }?.id ?: found.firstOrNull()?.id, + studentsError = failure.takeUnless { f -> f is DiaryFailure.ReauthRequired }, + reauth = it.reauth || failure is DiaryFailure.ReauthRequired, ) } - load() + return + } + state.update { it.copy(studentsLoading = false) } + applyStudents(found, remembered) + load(force = false) + } + + private suspend fun applyStudents(found: List, remembered: Long?) { + // The chosen child across a refresh, then the stored choice, then the + // first — which for most accounts is the only one, and is why the + // picker is hidden at that size. + val current = state.value.selectedStudentId + val selected = found.firstOrNull { it.id == current }?.id + ?: found.firstOrNull { it.id == remembered }?.id + ?: found.firstOrNull()?.id + state.update { it.copy(students = found, selectedStudentId = selected) } + // Written down when it was a default rather than a choice, because the + // start refresh reads the stored one and would otherwise refresh no one + // for an account with two children. + if (selected != null && selected != remembered && found.size > 1) { + runCatching { cache.selectStudent(selected) } } } - private fun reload() { + private fun reload(force: Boolean = false) { loadJob?.cancel() - loadJob = viewModelScope.launch { load() } + loadJob = viewModelScope.launch { load(force) } } /** - * Fetches the open tab again. + * Fetches the open tab again, from the diary and not from the save. * - * Public because writing a correction has to be followed by a read: none of - * this is cached, the server is what applies a correction, and `retry` — the - * only other way back in — is reachable only from a failure card. + * Public because writing a correction has to be followed by a read: the + * server is what applies a correction, the save holds the rows from before + * it, and `retry` — the only other way back in — is reachable only from a + * failure card. */ - fun refresh() = reload() + fun refresh() = reload(force = true) - private suspend fun load() { + private suspend fun load(force: Boolean) { val current = state.value val student = current.student ?: return when (current.tab) { - DiaryTab.SCHEDULE -> loadSchedule(student.id, current.weekStart) - DiaryTab.GRADES -> loadGrades(student.id, current.today) + DiaryTab.SCHEDULE -> loadSchedule(student.id, current.weekStart, force) + DiaryTab.GRADES -> loadGrades(student.id, current.today, force) } } @@ -337,8 +555,19 @@ class DiaryViewModel( * awaited in parallel: one week is one round trip's worth of waiting, not * two. */ - private suspend fun loadSchedule(studentId: Long, weekStart: LocalDate) { - state.update { it.copy(scheduleLoading = true, scheduleError = null) } + private suspend fun loadSchedule(studentId: Long, weekStart: LocalDate, force: Boolean) { + var saved = savedWeek(studentId, weekStart) + showSavedWeek(weekStart, saved) + // The start refresh may be reading this very week; its answer is the + // one to draw, and asking again beside it would be the same request + // twice. + if (awaitStartRefresh()) { + saved = savedWeek(studentId, weekStart) + showSavedWeek(weekStart, saved) + } + val savedAt = saved?.savedAt + if (!force && savedAt != null && diaryIsFresh(savedAt, clock.instant())) return + val weekEnd = weekStart.plusDays(6) val (lessons, homework) = coroutineScope { val timetable = async { repository.schedule(studentId, weekStart, weekEnd) } @@ -347,6 +576,10 @@ class DiaryViewModel( } val failure = lessons.exceptionOrNull() ?: homework.exceptionOrNull() if (failure != null) { + if (savedAt != null && DiaryFailure.of(failure).keepsSavedRows) { + state.update { it.copy(scheduleLoading = false, savedAt = savedAt) } + return + } applyFailure(failure) { copy(scheduleLoading = false, scheduleError = it) } return } @@ -355,7 +588,26 @@ class DiaryViewModel( lessons = lessons.getOrDefault(emptyList()), homework = homework.getOrDefault(emptyList()), ) - state.update { it.copy(scheduleLoading = false, days = days) } + state.update { it.copy(scheduleLoading = false, days = days, savedAt = null) } + } + + private suspend fun savedWeek(studentId: Long, weekStart: LocalDate): DiaryCachedWeek? = + runCatching { cache.week(studentId, weekStart).first() }.getOrNull() + + /** Draws a saved week, or the skeleton when there is none to draw. */ + private fun showSavedWeek(weekStart: LocalDate, saved: DiaryCachedWeek?) { + if (saved?.savedAt != null) { + state.update { + it.copy( + scheduleLoading = false, + scheduleError = null, + savedAt = null, + days = diaryWeek(weekStart, saved.lessons, saved.homework), + ) + } + } else { + state.update { it.copy(scheduleLoading = true, scheduleError = null, savedAt = null) } + } } /** @@ -366,24 +618,59 @@ class DiaryViewModel( * longer than the 62 days one request may cover. A term that cannot be read * is not an error: the range simply falls back to the last 62 days. */ - private suspend fun loadGrades(studentId: Long, today: LocalDate) { - state.update { it.copy(gradesLoading = true, gradesError = null) } - val period = if (periods.containsKey(studentId)) { - periods[studentId] + private suspend fun loadGrades(studentId: Long, today: LocalDate, force: Boolean) { + val period = currentPeriod(studentId, force) + val range = diaryGradeRange(today, period) + val saved = runCatching { cache.marks(studentId).first() }.getOrNull() + val savedAt = saved?.takeIf { it.covers(range) }?.loadedAt + if (saved != null && savedAt != null) { + state.update { + it.copy( + gradesLoading = false, + gradesError = null, + savedAt = null, + subjects = summariseMarks(saved.marks), + gradeRange = range, + ) + } + if (!force && diaryIsFresh(savedAt, clock.instant())) return } else { - repository.periods(studentId).getOrNull() - ?.firstOrNull { it.isCurrent } - .also { periods[studentId] = it } + state.update { it.copy(gradesLoading = true, gradesError = null, savedAt = null) } } - val range = diaryGradeRange(today, period) + val result = repository.grades(studentId, range.from, range.to) val failure = result.exceptionOrNull() if (failure != null) { + if (savedAt != null && DiaryFailure.of(failure).keepsSavedRows) { + state.update { it.copy(gradesLoading = false, savedAt = savedAt) } + return + } applyFailure(failure) { copy(gradesLoading = false, gradesError = it) } return } val subjects = summariseMarks(result.getOrDefault(emptyList())) - state.update { it.copy(gradesLoading = false, subjects = subjects, gradeRange = range) } + state.update { + it.copy(gradesLoading = false, subjects = subjects, gradeRange = range, savedAt = null) + } + } + + /** + * The term today falls in: remembered for the screen's life, else the saved + * terms when they are fresh, else the diary's — and the saved ones again + * when the diary cannot answer, since a term from last week is a far better + * window than none. + */ + private suspend fun currentPeriod(studentId: Long, force: Boolean): DiaryPeriod? { + if (!force && periods.containsKey(studentId)) return periods[studentId] + val saved = runCatching { cache.periods(studentId).first() }.getOrNull() + val period = if (!force && saved != null && diaryIsFresh(saved.loadedAt, clock.instant())) { + saved.periods.firstOrNull { it.isCurrent } + } else { + repository.periods(studentId).getOrNull()?.firstOrNull { it.isCurrent } + ?: saved?.periods?.firstOrNull { it.isCurrent } + } + periods[studentId] = period + return period } // -- corrections -------------------------------------------------------- @@ -554,40 +841,68 @@ class DiaryViewModel( companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { - DiaryViewModel(repository = Graph.container.diaryRepository) + val container = Graph.container + DiaryViewModel( + repository = container.diaryRepository, + cache = container.diaryCache, + binding = container.sessionRepository.session.map { it?.diary }, + describe = { target -> diaryPlaceOf(container.regionLookup.catalog(), target) }, + ) } } } } /** - * A sign-in's [DiarySignInProblem] in the words this screen already has. + * Which diary a sign-in goes to; see [DiaryUiState.signInTarget]. The login is + * whatever the source carried, and the form replaces it with what was typed. + */ +internal fun signInTargetOf( + chosen: DiaryTarget?, + session: DiarySession?, + stored: DiaryTarget?, + bound: DiaryTarget?, +): DiaryTarget = chosen ?: session?.target ?: stored ?: bound ?: DiaryTarget.petersburg("") + +/** The same diary, region and school, whoever is signing in to it. */ +private fun DiaryTarget.sameDiaryAs(other: DiaryTarget): Boolean = + provider == other.provider && region == other.region && schoolId == other.schoolId + +/** + * Whether a failed read leaves the saved rows on screen, with when they were + * saved, instead of a failure card. * - * A bridge, and a lossy one: the sign-in now fails in more ways than the - * [DiaryFailure] this form was written against, and «слишком много попыток» - * or «дневник выключен на сервере» have no sentence here yet — they read as the - * nearest one. `DiaryProblemText` is where each problem gets its own; when this - * form switches to it, this function goes. + * The failures that say nothing about the rows — the diary or our server could + * not be reached just now — and nothing else: a sign-in that ended, or an + * answer that says this app asked for the wrong thing, is not something the + * saved rows can stand in for. + */ +private val DiaryFailure.keepsSavedRows: Boolean + get() = this is DiaryFailure.Offline || this is DiaryFailure.Unavailable + +/** When a saved week is from: its older half, since both are drawn together. */ +private val DiaryCachedWeek.savedAt: Instant? + get() { + val lessons = lessonsLoadedAt ?: return null + val homework = homeworkLoadedAt ?: return null + return minOf(lessons, homework) + } + +private val NoStudents = DiaryCachedStudents(emptyList(), loadedAt = null) + +/** + * A cache that holds nothing, for a view model built without one — the tests + * that are about the network and nothing in front of it. */ -internal fun signInFailure(failure: Throwable): DiaryFailure = when (failure) { - is DiarySignInProblem.WrongPassword, - DiarySignInProblem.LoginTooShort, - DiarySignInProblem.SignInRequired, - -> DiaryFailure.SignInRequired - DiarySignInProblem.ReauthRequired -> DiaryFailure.ReauthRequired - DiarySignInProblem.ServerDisabled -> DiaryFailure.Disabled - DiarySignInProblem.ServerAddressRefused -> DiaryFailure.ServerAddressRefused - is DiarySignInProblem.TooManyAttempts -> DiaryFailure.Throttled(failure.retryAfterSeconds) - is DiarySignInProblem.ProviderUnavailable, - is DiarySignInProblem.ProviderRefusesPhone, - is DiarySignInProblem.Timeout, - -> DiaryFailure.Unavailable - is DiarySignInProblem.ProviderUnreadable -> DiaryFailure.Unreadable - is DiarySignInProblem.ProviderOffline, - DiarySignInProblem.Offline, - DiarySignInProblem.RegisterUnreachable, - DiarySignInProblem.ServerMissing, - -> DiaryFailure.Offline(failure) - is DiarySignInProblem -> DiaryFailure.Unexpected(code = null, reason = failure) - else -> DiaryFailure.of(failure) +internal object NoDiaryCache : DiaryCache { + override val students: Flow = flowOf(NoStudents) + override val selectedStudentId: Flow = flowOf(null) + override suspend fun selectStudent(id: Long?) = Unit + override fun week(studentId: Long, monday: LocalDate): Flow = + flowOf(DiaryCachedWeek(monday, emptyList(), emptyList(), null, null)) + override fun marks(studentId: Long): Flow = + flowOf(DiaryCachedMarks(null, null, emptyList(), null)) + override fun periods(studentId: Long): Flow = + flowOf(DiaryCachedPeriods(emptyList(), null)) + override suspend fun clear() = Unit } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt index a779e014..06a0b684 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt @@ -32,6 +32,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -63,8 +64,9 @@ import com.lumenpearson.lessons.ui.common.ServerUrlSheet import com.lumenpearson.lessons.ui.onboarding.OnboardingActions /** - * First run: turn a six-character code from the classroom whiteboard into a - * session. + * Turn a class code into a session: the eight-character code a class hands out, + * or the ten-character personal one from the bot's «📱 Подключить телефон» — + * one field takes both (`ClassCodeLengths`). * * Shaped like the first-run flow in * [Essentials](https://github.com/sameerasw/essentials): a centred mark, a @@ -72,34 +74,40 @@ import com.lumenpearson.lessons.ui.onboarding.OnboardingActions * pinned to the bottom edge carrying its label on the left and an arrow on the * right. The content above it scrolls; the action does not move. * - * There is no navigation callback for success — a successful join writes a - * session and the app shell reacts to it. The screen's own jobs are to say what - * the app will do once it has a class, to take the code, and to give a pupil - * whose school runs its own server a way to point the app at it. + * A successful join writes a session. Raised from settings, the app shell + * reacts to that alone; in the first run the shell holds the screen instead, + * and [onJoined] is how the flow hears of it. The screen's own jobs are to say + * what the app will do once it has a class, to take the code, and to let a + * pupil point the app at the class's server — the APK carries none. * - * @param onBack non-null only when this is the last step of the first-run flow, - * where it is one of four screens and the other three are worth being able to - * go back to. Reached on its own — after signing out — there is nothing behind - * it, so the square is absent rather than dead. + * @param onBack the first run's way back to the chooser. `null` where there is + * nothing behind the screen, so the square is absent rather than dead. + * @param onJoined the class just joined, once per join; the first run decides + * there whether the class's diary is offered next. `AddClassSheet` passes + * nothing and keeps its own reading of the one-shot. */ @Composable fun JoinScreen( modifier: Modifier = Modifier, onBack: (() -> Unit)? = null, + onJoined: ((classId: Long) -> Unit)? = null, viewModel: JoinViewModel = viewModel(factory = JoinViewModel.Factory), ) { val state by viewModel.uiState.collectAsStateWithLifecycle() var showServerSheet by rememberSaveable { mutableStateOf(false) } + val joined by rememberUpdatedState(onJoined) // A one-shot belongs to whoever sees it first, and this screen sees it - // first. It does not act on it — joining writes a session and the shell - // navigates on the session — but leaving it set hands the next observer + // first. It hands it to [onJoined] when there is one — the first run — and + // consumes it either way, because leaving it set hands the next observer // somebody else's join. `AddClassSheet` resolves the same view model // against the Activity's store, so a class joined during onboarding was // still announced when «Добавить класс» was opened an hour later, and the // sheet dismissed itself before the user could type a second code. LaunchedEffect(state.joinedClassId) { - if (state.joinedClassId != null) viewModel.consumeJoined() + val classId = state.joinedClassId ?: return@LaunchedEffect + joined?.invoke(classId) + viewModel.consumeJoined() } if (showServerSheet) { @@ -193,9 +201,9 @@ fun JoinScreen( Spacer(Modifier.height(GroupSpacing)) } - // The same row the first-run steps end with, so the last screen of - // the flow does not change shape under the finger that has pressed - // its way through three identical ones. + // The same row the first-run steps end with, so the class-code step + // does not change shape under the finger that has pressed its way + // through the introduction's identical ones. OnboardingActions( label = correctedString(R.string.join_action), icon = Icons.AutoMirrored.Rounded.ArrowForward, @@ -319,6 +327,7 @@ internal fun JoinError?.asText(): String? = when (this) { null -> null JoinError.InvalidCode -> correctedString(R.string.join_error_invalid_code, ClassCodeLengths.first, ClassCodeLengths.last) JoinError.UnknownCode -> correctedString(R.string.join_error_unknown_code) + JoinError.NoServer -> correctedString(R.string.join_error_no_server) JoinError.InviteOnly -> correctedString(R.string.join_error_invite_only) is JoinError.TooManyAttempts -> minutes ?.let { pluralStringResource(R.plurals.join_error_too_many_wait, it, it) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt index 455e0837..f2555025 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt @@ -7,6 +7,7 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.lumenpearson.lessons.core.data.di.Graph +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException import com.lumenpearson.lessons.core.data.repository.JoinFailure import com.lumenpearson.lessons.core.data.repository.SessionRepository import com.lumenpearson.lessons.core.data.repository.SettingsRepository @@ -55,6 +56,16 @@ sealed interface JoinError { */ data class TooManyAttempts(val minutes: Int?) : JoinError + /** + * No server address is set, so nothing was asked. + * + * Its own case because the cure is on this screen — the «Адрес сервера» + * row under the button — and because the only other words for it were the + * interceptor's English exception message, which is what a pupil saw: + * «Не удалось подключиться: No server address configured» (#154). + */ + data object NoServer : JoinError + /** * The server refused the code some other way, or was unreachable. * @@ -83,7 +94,12 @@ sealed interface JoinError { // unreachable: «Не удалось подключиться: Could not reach the // server» went on a Russian screen, and the Russian sentence // written for exactly that case was never shown again. - is JoinFailure.Offline -> Rejected(classified.reason.message?.takeIf { it.isNotBlank() }) + is JoinFailure.Offline -> + if (classified.reason.causes().any { it is ServerAddressMissingException }) { + NoServer + } else { + Rejected(classified.reason.message?.takeIf { it.isNotBlank() }) + } is JoinFailure.Rejected -> Rejected(classified.reason?.message?.takeIf { it.isNotBlank() }) } @@ -104,11 +120,13 @@ data class JoinUiState( /** * The class just joined, until somebody consumes it. * - * The screen ignores this — joining writes a session and the shell - * navigates on the session, which is still the one mechanism. It exists - * for the «Добавить класс» sheet, which is raised from inside an app that - * is already signed in: nothing navigates there, so the sheet has to be - * told, and the class id alone cannot tell it. Re-entering the code of the + * Joining writes a session, and outside the first run the shell navigates + * on the session. Two callers need more than that. The «Добавить класс» + * sheet is raised from inside an app that is already signed in: nothing + * navigates there, so the sheet has to be told, and the class id alone + * cannot tell it. And the first run holds the screen through a join (the + * shell's hold), because a class whose join names a diary goes on to that + * diary's sign-in — so the join screen hands this to its `onJoined`. Re-entering the code of the * class already on screen is a real case — it is how somebody whose device * was revoked gets back in — and it leaves the active class exactly as it * was while having plainly succeeded. @@ -120,11 +138,13 @@ data class JoinUiState( } /** - * First-run screen state. + * The join screen's state, for the first run's class-code step and the + * «Добавить класс» sheet alike. * - * Success is deliberately *not* reported back through a callback: joining writes - * a session, the app shell observes the session, and navigation follows from - * that. One mechanism, so signing out later cannot take a different path back. + * Success is reported as a one-shot ([JoinUiState.joinedClassId]) rather than a + * callback held by this view model: it is resolved against the activity's + * store and outlives either screen, and a callback kept here would outlive the + * screen that passed it. * * @param deviceName sent with the join request so a teacher can tell one pupil's * phone from another in the class admin panel. @@ -235,3 +255,6 @@ class JoinViewModel( } } } + +/** The exception and what it wraps, a few levels deep — enough for OkHttp's wrapping, never a cycle. */ +private fun Throwable.causes(): Sequence = generateSequence(this) { it.cause }.take(8) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt index f3695cb5..94026e4f 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalDocumentSheet.kt @@ -35,6 +35,7 @@ import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import com.lumenpearson.lessons.ui.common.openInBrowser /** What the sheet has to draw: nothing yet, nothing at all, or the document. */ internal sealed interface LegalLoad { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt index 5e531bf8..98811ff8 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/legal/LegalOpener.kt @@ -1,8 +1,6 @@ package com.lumenpearson.lessons.ui.legal -import android.content.ActivityNotFoundException import android.content.Context -import android.content.Intent import android.net.ConnectivityManager import android.net.NetworkCapabilities import androidx.compose.runtime.Composable @@ -12,10 +10,10 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.intl.Locale -import androidx.core.net.toUri import com.lumenpearson.lessons.BuildConfig import com.lumenpearson.lessons.core.data.legal.LegalDocument import com.lumenpearson.lessons.core.data.legal.legalUrl +import com.lumenpearson.lessons.ui.common.openInBrowser /** Where a tap on a legal link ends up. */ internal sealed interface LegalTarget { @@ -99,18 +97,3 @@ internal fun isOnline(context: Context): Boolean { }.getOrDefault(false) } -/** - * `false` when nothing could open [url]. - * - * A work profile or a locked-down school phone may have no browser at all, and - * the about card's links already learned that an unguarded `startActivity` - * takes the app down on one. - */ -internal fun openInBrowser(context: Context, url: String): Boolean = try { - context.startActivity( - Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), - ) - true -} catch (_: ActivityNotFoundException) { - false -} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt new file mode 100644 index 00000000..869f2071 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt @@ -0,0 +1,226 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearOutSlowInEasing +import androidx.compose.animation.core.tween +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.CloudDownload +import androidx.compose.material.icons.rounded.ErrorOutline +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material.icons.rounded.Refresh +import androidx.compose.material.icons.rounded.RemoveCircleOutline +import androidx.compose.material.icons.rounded.Schedule +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import com.lumenpearson.lessons.core.designsystem.component.LessonsWavyProgress +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.diary.asText +import kotlin.math.roundToInt +import kotlinx.coroutines.delay + +/** + * «Загружаем дневник»: this week and the next, the terms, the homework and the + * marks, fetched once so the diary home opens from the phone's own copy. + * + * The bar moves while a request is out rather than sitting still and jumping: + * each step says where it will leave the bar ([ImportUi.target]), and the bar + * creeps most of the way there, slowing as it goes, until the answer puts it + * where it really is. It never goes backwards, and with animations off it + * shows only what is done. + */ +@Composable +internal fun ImportPage(viewModel: OnboardingViewModel) { + val ui by viewModel.importing.state.collectAsStateWithLifecycle() + val motion = LocalMotion.current + val shown = remember { Animatable(0f) } + + LaunchedEffect(ui.completed, ui.target, ui.done, ui.failed, motion.enabled) { + if (ui.completed > shown.value || !motion.enabled) shown.snapTo(ui.completed) + val stopped = ui.done != null || ui.failed != null || ui.choosing != null + if (motion.enabled && !stopped && ui.target > shown.value) { + val aim = shown.value + (ui.target - shown.value) * CreepShare + shown.animateTo(aim, tween(motion.durationMillis(CreepMillis), easing = LinearOutSlowInEasing)) + } + } + + // The full bar is seen before the summary slides in; a manual «Дальше» + // stays underneath for whoever is faster than the pause. + LaunchedEffect(ui.done) { + if (ui.done == null) return@LaunchedEffect + delay(motion.durationMillis(DoneHoldMillis).toLong()) + viewModel.importShown() + } + + val failed = ui.failed + StepScaffold( + actions = { + when { + ui.done != null -> OnboardingActions( + label = correctedString(R.string.onboarding_action_continue), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onClick = viewModel::importShown, + ) + failed != null && failed.needsSignIn -> OnboardingActions( + label = correctedString(R.string.onboarding_import_sign_in_again), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onClick = viewModel::signInAgain, + ) + failed != null -> OnboardingActions( + label = correctedString(R.string.onboarding_action_retry), + icon = Icons.Rounded.Refresh, + onClick = viewModel::retryImport, + ) + else -> OnboardingActions( + label = correctedString(R.string.onboarding_import_running), + icon = Icons.Rounded.CloudDownload, + busy = true, + onClick = {}, + ) + } + }, + ) { + Spacer(Modifier.height(24.dp)) + OnboardingTitle( + title = correctedString(R.string.onboarding_import_title), + subtitle = correctedString(R.string.onboarding_import_subtitle), + ) + Spacer(Modifier.height(24.dp)) + LessonsWavyProgress( + progress = shown.value, + description = correctedString(R.string.onboarding_import_progress, (ui.completed * 100).roundToInt()), + ) + Spacer(Modifier.height(GroupSpacing)) + + ui.choosing?.let { students -> + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.onboarding_import_pick_title)) + NoteCard(correctedString(R.string.onboarding_import_pick_text)) + Spacer(Modifier.height(8.dp)) + RoundedCardContainer { + students.forEach { student -> + ChoiceRow( + title = student.name, + subtitle = listOfNotNull(student.className, student.school) + .filter { it.isNotBlank() } + .joinToString(", ") + .ifBlank { null }, + icon = Icons.Rounded.Person, + tone = accentTone(3), + selected = false, + onClick = { viewModel.pickStudent(student.id) }, + ) + } + } + } + Spacer(Modifier.height(GroupSpacing)) + } + + RoundedCardContainer { + ImportStages.forEach { stage -> StageRow(ui = ui, stage = stage) } + } + + if (failed != null) { + Spacer(Modifier.height(GroupSpacing)) + NoteCard( + if (failed.needsSignIn) { + correctedString(R.string.onboarding_import_expired) + } else { + correctedString(R.string.onboarding_import_failed, failed.problem.asText()) + }, + ) + TextButton(onClick = viewModel::startOver, modifier = Modifier.fillMaxWidth()) { + Text(correctedString(R.string.onboarding_import_restart)) + } + } + Spacer(Modifier.height(24.dp)) + } +} + +@Composable +private fun StageRow(ui: ImportUi, stage: DiaryImportPhase) { + val state = stageStateOf(ui, stage) + val done = ui.done + val subtitle = when (state) { + StageState.WAITING -> correctedString(R.string.onboarding_import_waiting) + StageState.RUNNING -> correctedString(R.string.onboarding_import_running) + StageState.SKIPPED -> correctedString(R.string.onboarding_import_skipped) + StageState.FAILED -> correctedString(R.string.onboarding_import_stopped) + StageState.DONE -> when { + done != null && stage == DiaryImportPhase.SCHEDULE -> + pluralStringResource(R.plurals.onboarding_import_lessons, done.lessons, done.lessons) + done != null && stage == DiaryImportPhase.HOMEWORK -> + pluralStringResource(R.plurals.onboarding_import_assignments, done.homework, done.homework) + done != null && stage == DiaryImportPhase.MARKS -> + pluralStringResource(R.plurals.diary_marks_count, done.marks, done.marks) + else -> correctedString(R.string.onboarding_import_done) + } + } + ChoiceRow( + title = correctedString(stage.labelRes), + subtitle = subtitle, + tone = accentTone(stage.ordinal), + selected = state == StageState.RUNNING, + trailing = { + when (state) { + StageState.RUNNING -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + else -> Icon( + imageVector = when (state) { + StageState.DONE -> Icons.Rounded.Check + StageState.SKIPPED -> Icons.Rounded.RemoveCircleOutline + StageState.FAILED -> Icons.Rounded.ErrorOutline + else -> Icons.Rounded.Schedule + }, + contentDescription = null, + tint = if (state == StageState.FAILED) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + }, + ) +} + +private val DiaryImportPhase.labelRes: Int + get() = when (this) { + DiaryImportPhase.STUDENTS, DiaryImportPhase.CHOOSE_STUDENT -> R.string.onboarding_import_phase_students + DiaryImportPhase.PERIODS -> R.string.onboarding_import_phase_periods + DiaryImportPhase.SCHEDULE -> R.string.onboarding_import_phase_schedule + DiaryImportPhase.HOMEWORK -> R.string.onboarding_import_phase_homework + DiaryImportPhase.MARKS -> R.string.onboarding_import_phase_marks + } + +/** How much of the way to a step's target the bar creeps before the answer. */ +private const val CreepShare = 0.85f + +/** How long the creep takes: longer than most answers, so it rarely stalls at its end. */ +private const val CreepMillis = 6_000 + +/** How long a full bar is left on screen before the summary. */ +private const val DoneHoldMillis = 700 diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt new file mode 100644 index 00000000..146b5a24 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt @@ -0,0 +1,181 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.diary.DiaryImport +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** A pupil on the chooser; see `DiaryPlace` for why not the data layer's type. */ +@Immutable +data class StudentUi(val id: Long, val name: String, val className: String?, val school: String?) + +/** What a finished import brought, and what it had to leave out. */ +@Immutable +data class ImportDone( + val lessons: Int, + val homework: Int, + val marks: Int, + val skipped: Set, +) + +/** Where an import stopped, and whether picking up there can work. */ +@Immutable +data class ImportFailure( + val phase: DiaryImportPhase, + val problem: DiarySignInProblem, + val resumable: Boolean, +) { + /** The diary ended the session: only a new sign-in continues. */ + val needsSignIn: Boolean + get() = problem is DiarySignInProblem.ReauthRequired || problem is DiarySignInProblem.SignInRequired +} + +/** + * The import screen's state. + * + * @property completed the part of the bar that is done. + * @property target where the step under way will leave it — the bar creeps + * toward it while the request is out rather than sitting still and jumping. + * @property choosing the pupils to pick from, while the import waits for one. + */ +@Immutable +data class ImportUi( + val completed: Float = 0f, + val target: Float = 0f, + val phase: DiaryImportPhase? = null, + val choosing: List? = null, + val done: ImportDone? = null, + val failed: ImportFailure? = null, +) + +/** One row of the import screen. */ +enum class StageState { WAITING, RUNNING, DONE, SKIPPED, FAILED } + +/** The phases the screen shows a row for; choosing a pupil is a card, not a row. */ +val ImportStages: List = listOf( + DiaryImportPhase.STUDENTS, + DiaryImportPhase.PERIODS, + DiaryImportPhase.SCHEDULE, + DiaryImportPhase.HOMEWORK, + DiaryImportPhase.MARKS, +) + +/** + * The state of [stage]'s row. Phases run in declaration order, so everything + * before the one under way is done — including a phase the import skipped + * because the cache already had it (the pupils a registration returned). + */ +fun stageStateOf(ui: ImportUi, stage: DiaryImportPhase): StageState { + ui.done?.let { done -> return if (stage in done.skipped) StageState.SKIPPED else StageState.DONE } + ui.failed?.let { failed -> + return when { + stage == failed.phase -> StageState.FAILED + stage.ordinal < failed.phase.ordinal -> StageState.DONE + else -> StageState.WAITING + } + } + val current = ui.phase ?: return StageState.WAITING + return when { + stage.ordinal < current.ordinal -> StageState.DONE + stage == current -> StageState.RUNNING + else -> StageState.WAITING + } +} + +/** + * Runs [DiaryImport] for the import step and turns its progress into [ImportUi]. + * + * The pupil chooser is a suspension, not a callback into the screen: the + * import awaits [choose], which the screen reaches through [ImportUi.choosing]. + */ +class ImportRunner( + private val scope: CoroutineScope, + private val import: DiaryImport, +) { + private val mutable = MutableStateFlow(ImportUi()) + val state: StateFlow = mutable.asStateFlow() + + private var job: Job? = null + private var pending: CompletableDeferred? = null + private var offered: List = emptyList() + + val running: Boolean get() = job?.isActive == true + + /** + * Starts, or picks up after a failure. The bar keeps what was done: a + * resumed import does not repeat the phases before [resumeFrom]. + */ + fun start(resumeFrom: DiaryImportPhase? = null) { + if (running) return + mutable.update { it.copy(done = null, failed = null, choosing = null) } + job = scope.launch { + import.run(resumeFrom = resumeFrom, choose = ::awaitChoice).collect { progress -> + when (progress) { + is DiaryImportProgress.Running -> mutable.update { + it.copy( + completed = maxOf(it.completed, progress.completed), + target = progress.target, + phase = progress.phase, + choosing = null, + ) + } + is DiaryImportProgress.ChoosingStudent -> mutable.update { + it.copy(completed = maxOf(it.completed, progress.completed), phase = DiaryImportPhase.CHOOSE_STUDENT) + } + is DiaryImportProgress.Done -> mutable.update { + it.copy( + completed = 1f, + target = 1f, + choosing = null, + done = ImportDone(progress.lessons, progress.homework, progress.marks, progress.skipped), + ) + } + is DiaryImportProgress.Failed -> mutable.update { + it.copy( + completed = maxOf(it.completed, progress.completed), + target = maxOf(it.completed, progress.completed), + choosing = null, + failed = ImportFailure(progress.phase, progress.problem, progress.resumable), + ) + } + } + } + } + } + + /** The pupil picked on the chooser; the import goes on with them. */ + fun choose(id: Long) { + val student = offered.firstOrNull { it.id == id } ?: return + mutable.update { it.copy(choosing = null) } + pending?.complete(student) + } + + /** Leaving the step: the request in flight is cancelled with the collector. */ + fun stop() { + job?.cancel() + job = null + pending?.cancel() + pending = null + mutable.value = ImportUi() + } + + private suspend fun awaitChoice(students: List): DiaryStudent { + val choice = CompletableDeferred() + pending = choice + offered = students + mutable.update { + it.copy(choosing = students.map { student -> StudentUi(student.id, student.shortName, student.className, student.school) }) + } + return choice.await() + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt new file mode 100644 index 00000000..db4809df --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt @@ -0,0 +1,394 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.catalog.CatalogRegion +import com.lumenpearson.lessons.core.data.catalog.CatalogSystem +import com.lumenpearson.lessons.core.data.catalog.MatchVia +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.catalog.RegionMatch +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.ui.diary.httpsHostOf + +/* + * The region, school and provider steps, read out of the bundled catalog into + * `:app` values. + * + * Plain values rather than the catalog's own types, which live in `:core:data` + * and are deliberately not promised stable to the Compose compiler: a step + * holding a `CatalogRegion` would recompose on every frame of a state it never + * changed. And read, never re-derived (K18): what is recommended, what can be + * signed into and in what role are the generator's answers — these functions + * only filter what to show and name it. + */ + +/** What the app can do about a region's diary, in one word, for a row of the region list. */ +enum class OfferKind { SIGN_IN, GOSUSLUGI, SITE, UNSUPPORTED, PAPER } + +/** [kind], and the name of the system it is about. */ +@Immutable +data class RegionOffer(val kind: OfferKind, val systemRu: String?, val systemEn: String?) + +/** + * One region as the region step draws it. + * + * @property matched what the query found it by, when that was not its name — + * a city, an alias or the subject code — so the row can say why it is here. + */ +@Immutable +data class RegionRowUi( + val key: String, + val nameRu: String, + val nameEn: String, + val code: String, + val via: MatchVia, + val matched: String?, + val offer: RegionOffer, +) + +/** How a system on the provider step is reached. */ +enum class ProviderRowKind { + /** The app's own form signs in. */ + SIGN_IN, + + /** «Сетевой город» without a school picked: its sign-in needs one. */ + NEEDS_SCHOOL, + + /** Госуслуги, in the browser; nothing comes back. */ + HANDOFF, + + /** A diary the app cannot read, whose site the browser can open. */ + SITE, + + /** A diary the app cannot read, with nowhere to send anybody. */ + UNSUPPORTED, + + /** No electronic diary at all. */ + PAPER, +} + +/** + * One system on the provider step. + * + * @property index the system's index in the region's catalog row. + * @property role the catalog's role: `primary`, `secondary`, `migrating_to`. + * @property url where [ProviderRowKind.HANDOFF] and [ProviderRowKind.SITE] send + * the browser — always https, never an app named by package. + * @property gosuslugi the handoff lands on a Госуслуги sign-in. + * @property host where a password would go, for a signable row. + */ +@Immutable +data class ProviderRowUi( + val index: Int, + val platform: String, + val nameRu: String, + val nameEn: String, + val role: String?, + val kind: ProviderRowKind, + val recommended: Boolean, + val url: String?, + val gosuslugi: Boolean, + val host: String?, +) + +/** The generator's reason codes, exactly (K18); anything else reads as [UNSUPPORTED]. */ +enum class WhyReason(val code: String) { + PRIMARY("primary"), + TOR_PRIMARY("tor_primary"), + FRONT_END("front_end"), + MOVING_TO("moving_to"), + UNREACHABLE("unreachable"), + UNSUPPORTED("unsupported"), + NO_DIARY("no_diary"), + ; + + companion object { + fun of(code: String?): WhyReason = entries.firstOrNull { it.code == code } ?: UNSUPPORTED + } +} + +/** The generator's modifiers on a recommendation. */ +enum class WhyModifier(val code: String) { + UNVERIFIED("unverified"), + ESIA_ONLY("esia_only"), +} + +/** + * Everything «Почему?» says about the recommended row, as data; the words are + * `WhyText`'s. + * + * @property mainSystemRu the region's own diary where the recommendation is a + * front end over it, which is what the front-end sentence names. + */ +@Immutable +data class WhyUi( + val reason: WhyReason, + val modifiers: Set, + val confidence: String?, + val regionRu: String, + val regionEn: String, + val systemRu: String, + val systemEn: String, + val mainSystemRu: String?, + val mainSystemEn: String?, + val schoolYear: String?, + val surveyMonth: String?, + val host: String?, +) + +/** The provider step, whole. */ +@Immutable +data class ProviderPage( + val regionKey: String, + val regionRu: String, + val regionEn: String, + val rows: List, + val why: WhyUi?, +) { + /** The row the main button acts for: the recommended one, else the first the app can sign in to. */ + val main: ProviderRowUi? + get() = rows.firstOrNull { it.recommended && it.kind != ProviderRowKind.UNSUPPORTED && it.kind != ProviderRowKind.PAPER } + ?: rows.firstOrNull { it.kind == ProviderRowKind.SIGN_IN || it.kind == ProviderRowKind.NEEDS_SCHOOL } +} + +/** + * Whether a region's chapter has a school step and a sign-in: a school step + * exactly where the signable diary is «Сетевой город» (its sign-in names the + * school), a sign-in wherever the app's form can go at all. + */ +fun regionPlanOf(region: CatalogRegion): RegionPlan { + val signable = region.systems.filter(::isSignable) + return RegionPlan( + showsSchool = signable.any { it.platform == NETSCHOOL }, + signable = signable.isNotEmpty(), + ) +} + +/** What a region row says can be done there: its recommended system, read as the catalog has it. */ +fun regionOfferOf(catalog: RegionCatalog, region: CatalogRegion): RegionOffer { + val recommended = region.recommended?.system?.let(region.systems::getOrNull) + val signable = region.systems.firstOrNull(::isSignable) + val shown = signable ?: recommended ?: region.systems.firstOrNull() + val platform = shown?.platform?.let(catalog.platforms::get) + val kind = when { + shown == null -> OfferKind.UNSUPPORTED + shown.platform == PAPER -> OfferKind.PAPER + isSignable(shown) -> OfferKind.SIGN_IN + isGosuslugi(region, shown) -> OfferKind.GOSUSLUGI + httpsUrl(shown) != null && shown.action == ACTION_HANDOFF -> OfferKind.SITE + else -> OfferKind.UNSUPPORTED + } + return RegionOffer(kind = kind, systemRu = platform?.nameRu, systemEn = platform?.nameEn) +} + +/** A search hit as a row; see [RegionRowUi.matched]. */ +fun regionRowOf(catalog: RegionCatalog, match: RegionMatch): RegionRowUi = regionRowOf( + catalog = catalog, + region = match.region, + via = match.via, + matched = when (match.via) { + MatchVia.CITY -> original(catalog, match.region.cities, match.matched) + MatchVia.ALIAS -> original(catalog, match.region.aliases, match.matched) + MatchVia.CODE -> match.region.code + else -> null + }, +) + +fun regionRowOf(catalog: RegionCatalog, region: CatalogRegion, via: MatchVia = MatchVia.LIST, matched: String? = null) = + RegionRowUi( + key = region.key, + nameRu = region.nameRu, + nameEn = region.nameEn, + code = region.code, + via = via, + matched = matched, + offer = regionOfferOf(catalog, region), + ) + +/** + * The search hands back the words it matched folded (lower case, ё as е); the + * row names the city as the catalog spells it. + */ +private fun original(catalog: RegionCatalog, candidates: List, folded: String): String = + candidates.firstOrNull { fold(catalog, it) == fold(catalog, folded) } ?: folded + +/** The search's own folding, from the catalog's table: no Cyrillic is written in Kotlin. */ +private fun fold(catalog: RegionCatalog, text: String): String { + val table = catalog.search.fold + return text.lowercase().map { char -> table[char.toString()] ?: char.toString() }.joinToString("") + .split(' ').filter { it.isNotBlank() }.joinToString(" ") +} + +/** + * The provider step for [region]: the systems a family could mean, in catalog + * order, with the recommended one marked. + * + * Left out: a legacy or unclear system (the survey's history, not a choice), a + * portal or an admissions site (not a diary), and ТОР where the catalog says + * the region is not on it. The recommended system is always kept, whatever its + * role. + */ +fun providerPageOf(catalog: RegionCatalog, region: CatalogRegion, school: PickedSchool?): ProviderPage { + val recommendedIndex = region.recommended?.system + val rows = region.systems.mapIndexedNotNull { index, system -> + val recommended = index == recommendedIndex + if (!recommended && !shown(catalog, region, system)) return@mapIndexedNotNull null + val platform = catalog.platforms[system.platform] + ProviderRowUi( + index = index, + platform = system.platform, + nameRu = platform?.nameRu ?: system.platform, + nameEn = platform?.nameEn ?: system.platform, + role = system.role, + kind = kindOf(region, system, school), + recommended = recommended, + url = httpsUrl(system), + gosuslugi = isGosuslugi(region, system), + host = hostOf(catalog, system), + ) + } + val recommended = recommendedIndex?.let(region.systems::getOrNull) + val why = recommended?.let { system -> + val platform = catalog.platforms[system.platform] + val main = region.systems.firstOrNull { it.role == ROLE_PRIMARY && it !== system } + ?.platform?.let(catalog.platforms::get) + WhyUi( + reason = WhyReason.of(region.recommended?.reason), + modifiers = region.recommended?.modifiers.orEmpty() + .mapNotNull { code -> WhyModifier.entries.firstOrNull { it.code == code } } + .toSet(), + confidence = region.recommended?.confidence, + regionRu = region.nameRu, + regionEn = region.nameEn, + systemRu = platform?.nameRu ?: system.platform, + systemEn = platform?.nameEn ?: system.platform, + mainSystemRu = main?.nameRu, + mainSystemEn = main?.nameEn, + schoolYear = catalog.survey.schoolYear, + surveyMonth = catalog.survey.month, + host = if (isSignable(system)) hostOf(catalog, system) else null, + ) + } + return ProviderPage( + regionKey = region.key, + regionRu = region.nameRu, + regionEn = region.nameEn, + rows = rows, + why = why, + ) +} + +private fun shown(catalog: RegionCatalog, region: CatalogRegion, system: CatalogSystem): Boolean { + if (system.role !in ShownRoles) return false + val kind = catalog.platforms[system.platform]?.kind + if (kind == KIND_PORTAL || kind == KIND_ADMISSIONS) return false + if (system.platform == TOR && region.tor == TOR_ABSENT) return false + return true +} + +private fun kindOf(region: CatalogRegion, system: CatalogSystem, school: PickedSchool?): ProviderRowKind = when { + system.platform == PAPER -> ProviderRowKind.PAPER + isSignable(system) && system.platform == NETSCHOOL && school == null -> ProviderRowKind.NEEDS_SCHOOL + isSignable(system) -> ProviderRowKind.SIGN_IN + system.action == ACTION_HANDOFF && httpsUrl(system) != null -> + if (isGosuslugi(region, system)) ProviderRowKind.HANDOFF else ProviderRowKind.SITE + httpsUrl(system) != null -> ProviderRowKind.SITE + else -> ProviderRowKind.UNSUPPORTED +} + +/** + * The app's own form signs in here: the generator said `signin`, and the + * system is one of the two this app speaks — Petersburg, or «Сетевой город» in + * a region whose allow-list row takes a password. + */ +internal fun isSignable(system: CatalogSystem): Boolean = system.action == ACTION_SIGN_IN && when (system.platform) { + PETERSBURG -> true + NETSCHOOL -> system.netschool?.password == true + else -> false +} + +private fun isGosuslugi(region: CatalogRegion, system: CatalogSystem): Boolean = + system.platform == TOR || + system.netschool?.password == false || + (region.recommended?.system?.let(region.systems::getOrNull) === system && + region.recommended?.modifiers?.contains(WhyModifier.ESIA_ONLY.code) == true) + +/** The handoff target, else the site, and only ever https (K19). */ +private fun httpsUrl(system: CatalogSystem): String? = + (system.handoffUrl ?: system.webUrl)?.takeIf { it.startsWith("https://") } + +/** Where a password for [system] would go, by the allow-list's own rule; `null` if nowhere. */ +private fun hostOf(catalog: RegionCatalog, system: CatalogSystem): String? = when (system.platform) { + PETERSBURG -> catalog.platforms[PETERSBURG]?.origin?.let(::httpsHostOf) + NETSCHOOL -> system.netschool?.origin?.let(::httpsHostOf) + else -> null +} + +/** + * The sign-in target for [system] of [region], with the login still blank: + * the form is where it is typed. `null` for a system the form cannot reach, or + * «Сетевой город» with no school. + */ +fun targetFor(region: CatalogRegion, system: CatalogSystem, school: PickedSchool?): DiaryTarget? = when { + !isSignable(system) -> null + system.platform == PETERSBURG -> DiaryTarget.petersburg(login = "") + school == null -> null + else -> system.netschool?.let { row -> + DiaryTarget.netschool( + region = row.region, + schoolId = school.id, + schoolName = school.name, + login = "", + zone = row.zone.ifBlank { region.zone }, + ) + } +} + +/** + * A joined class's diary as a sign-in target, when this build can sign in to + * it: Petersburg, or «Сетевой город» in a password region with a school. The + * zone is the catalog's, because the binding carries none. + */ +fun classTargetOf(catalog: RegionCatalog, binding: DiaryBinding?): DiaryTarget? { + val target = binding?.targetFor(login = "") ?: return null + return when (target.provider) { + DiaryProviderKey.PETERSBURG -> target + DiaryProviderKey.NETSCHOOL -> { + val row = catalog.regions.asSequence() + .flatMap { it.systems.asSequence() } + .mapNotNull { it.netschool } + .firstOrNull { it.region == target.region } + if (row == null || !row.password) null else target.copy(zone = row.zone.ifBlank { target.zone }) + } + } +} + +/** + * The school search's first query, out of the name typed on the region step: + * the number when there is one — «ГБОУ лицей № 239» → «239» — else the longest + * word that is not a word every school has. The diary's own list rarely spells + * a school the way the company register does, and a number matches both. + */ +fun schoolQueryFromHint(hint: String?, schoolWords: Collection): String { + val text = hint?.trim().orEmpty() + if (text.isEmpty()) return "" + Regex("""\d+""").find(text)?.let { return it.value } + val common = schoolWords.map { it.lowercase() }.toSet() + return text.split(Regex("""[\s,.«»"()]+""")) + .filter { it.isNotBlank() && it.lowercase() !in common } + .maxByOrNull { it.length } + .orEmpty() +} + +private const val PETERSBURG = "petersburg" +private const val NETSCHOOL = "netschool" +private const val TOR = "tor-myschool" +private const val PAPER = "paper" +private const val ACTION_SIGN_IN = "signin" +private const val ACTION_HANDOFF = "handoff" +private const val ROLE_PRIMARY = "primary" +private const val TOR_ABSENT = "absent" +private const val KIND_PORTAL = "portal" +private const val KIND_ADMISSIONS = "admissions" +private val ShownRoles = setOf("primary", "secondary", "migrating_to") diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlow.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlow.kt new file mode 100644 index 00000000..b4e8540b --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlow.kt @@ -0,0 +1,396 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.repository.ShellMode + +/** + * Every screen the first run can show. + * + * The first five are the introduction, in Essentials' own order: say what this + * is, say what it is not and let the user opt out of the one thing it records, + * set the handful of preferences that change how the app feels, ask the system + * for what the alerts need — and only then ask for a way in ([WAY_IN]). Putting + * a credential first asks a stranger for it on a screen that has not yet said + * what it is for. + * + * [PERMISSIONS] stays before [WAY_IN] although a family that takes the diary + * way in gets no alerts (K23): the owner put the chooser after the existing + * steps, and moving the ask behind a branch would put it on one path only. + * + * From [WAY_IN] the flow branches, which is why it is a path and not an index + * into this enum (see [OnboardingState]): [CLASS_CODE] is the join screen, and + * [REGION] → [SCHOOL] → [PROVIDER] → [SIGN_IN] → [IMPORT] → [SUMMARY] is the + * family's own diary. A class whose join names a diary goes on from + * [CLASS_CODE] to [SIGN_IN] as well. Reaching [WAY_IN] is what counts as having + * seen the introduction. + */ +enum class OnboardingStep { + WELCOME, + ACKNOWLEDGEMENT, + PREFERENCES, + PERMISSIONS, + WAY_IN, + CLASS_CODE, + REGION, + SCHOOL, + PROVIDER, + SIGN_IN, + IMPORT, + SUMMARY, +} + +/** The two ways in the chooser offers. */ +enum class WayIn { CLASS_CODE, FIND_SCHOOL } + +/** + * Which run of steps the dots count. + * + * The dots count a chapter rather than the whole flow, because the whole flow + * is not known until the chooser has been answered, and a count that grew at + * the chooser would read as the flow getting longer — which is exactly what the + * dots must never do. + */ +enum class Chapter { INTRO, SCHOOL, CLASS, DIARY } + +/** How much of the badge strip a step shows. */ +enum class HeroMode { + /** The badge and the dots. */ + FULL, + + /** The dots only: a search or a keyboard needs the height more than a shape does. */ + COMPACT, + + /** Nothing: the join screen has a heading of its own. */ + HIDDEN, +} + +/** The dots: step [k] of [n] in [chapter]. */ +@Immutable +data class StepProgress(val chapter: Chapter, val k: Int, val n: Int) + +/** A school picked on [OnboardingStep.SCHOOL]: the diary's own id, never a register row. */ +@Immutable +data class PickedSchool(val id: Long, val name: String) + +/** + * What a region's catalog row decides about the rest of the chapter. + * + * @property showsSchool the region's signable diary is «Сетевой город», whose + * sign-in needs a school picked from the region's own list. + * @property signable the app's own form can sign in to one of its diaries. + */ +@Immutable +data class RegionPlan(val showsSchool: Boolean, val signable: Boolean) + +/** + * The answers the flow has collected. None is a secret: the login and the + * password are never here (see [OnboardingState]). + * + * @property region the catalog key. + * @property schoolHint the school name typed on the region step, carried to + * prefill the school search. + * @property system the index into the region's catalog systems chosen on the + * provider step. + * @property classBound [OnboardingStep.SIGN_IN] is the joined class's diary + * rather than one the family picked. + * @property resumeFrom the import phase to pick up from after a re-sign-in. + */ +@Immutable +data class OnboardingChoices( + val wayIn: WayIn? = null, + val region: String? = null, + val schoolHint: String? = null, + val school: PickedSchool? = null, + val system: Int? = null, + val classBound: Boolean = false, + val resumeFrom: String? = null, +) + +/** + * Where the flow is: the steps walked, how far back may be walked, and the + * answers. + * + * A path rather than a step because the flow branches: going back is popping, + * the slide's direction is depth, and the badge morphs along the path. Ordinal + * order means nothing once PROVIDER can lead to CLASS_CODE. + * + * [floor] is raised by a commit — a join, a registration, a finished import — + * so that the steps before it cannot be walked back into: the join screen must + * not reopen over a class already joined, and the sign-in must not mint a + * second server session. + * + * Saved whole in the view model's `SavedStateHandle` ([toSaved]), and nothing + * else of the flow is: the login lives in the sign-in step's memory, the + * password in the form's, the diary's session in a plain field. + */ +@Immutable +data class OnboardingState( + val path: List, + val floor: Int = 0, + val choices: OnboardingChoices = OnboardingChoices(), +) { + init { + require(path.isNotEmpty()) { "A flow is always on some step" } + } + + val current: OnboardingStep get() = path.last() + val depth: Int get() = path.lastIndex + val canGoBack: Boolean get() = depth > floor +} + +/** + * The flow's rules, as functions of its state: no Compose and no Android, so + * each can be asked on the JVM. + */ +object OnboardingFlow { + + private val Intro = listOf( + OnboardingStep.WELCOME, + OnboardingStep.ACKNOWLEDGEMENT, + OnboardingStep.PREFERENCES, + OnboardingStep.PERMISSIONS, + OnboardingStep.WAY_IN, + ) + + /** + * A fresh install starts at the welcome; one that has seen the introduction + * — which is what leaving the last class makes of it — starts at the + * chooser, where both ways in are, rather than on a bare join screen. + */ + fun initial(introduced: Boolean): OnboardingState = + OnboardingState(path = listOf(if (introduced) OnboardingStep.WAY_IN else OnboardingStep.WELCOME)) + + /** + * Where a flow the process lost picks up, when the stored hold says it was + * mid-way: a registered diary goes on to its import, a joined class whose + * diary this build can sign in to goes on to that sign-in, and anything + * else was finished by the write it held for. `null` is «finish». + */ + fun resume(mode: ShellMode, bindingUsable: Boolean, hasDiarySession: Boolean): OnboardingState? = + when { + mode == ShellMode.DIARY -> OnboardingState(path = listOf(OnboardingStep.IMPORT)) + mode == ShellMode.CLASS && bindingUsable && !hasDiarySession -> OnboardingState( + path = listOf(OnboardingStep.SIGN_IN), + choices = OnboardingChoices(classBound = true), + ) + else -> null + } + + fun push(state: OnboardingState, next: OnboardingStep): OnboardingState = + state.copy(path = state.path + next) + + /** [push], with the floor raised to the new step: nothing before it can be walked back into. */ + fun commit(state: OnboardingState, next: OnboardingStep): OnboardingState { + val pushed = push(state, next) + return pushed.copy(floor = pushed.depth) + } + + /** + * One step back, or the state unchanged at the floor. + * + * Unchanged rather than an error, because two back events can be drained in + * one input pass before `BackHandler`'s `enabled` has caught up — tapping + * back twice during the slide — and the second must find nothing to do. + */ + fun back(state: OnboardingState): OnboardingState = + if (state.canGoBack) state.copy(path = state.path.dropLast(1)) else state + + /** + * Back to the sign-in with the floor lowered to it, for an import the + * diary ended: the session died, and only a new one continues. When the + * path did not come through a sign-in — a flow resumed straight into its + * import — the sign-in replaces the import. + */ + fun reopenSignIn(state: OnboardingState): OnboardingState { + val before = state.path.getOrNull(state.depth - 1) + return if (before == OnboardingStep.SIGN_IN) { + state.copy(path = state.path.dropLast(1), floor = state.depth - 1) + } else { + state.copy(path = state.path.dropLast(1) + OnboardingStep.SIGN_IN, floor = state.depth) + } + } + + /** The whole flow again from the chooser, forgetting every answer. */ + fun restart(): OnboardingState = OnboardingState(path = listOf(OnboardingStep.WAY_IN)) + + /** + * What the region's diaries make of the rest of the chapter; `null` for a + * region not picked yet, which projects the longest route. + */ + fun regionTail(plan: RegionPlan?): List = buildList { + if (plan == null || plan.showsSchool) add(OnboardingStep.SCHOOL) + add(OnboardingStep.PROVIDER) + if (plan == null || plan.signable) { + add(OnboardingStep.SIGN_IN) + add(OnboardingStep.IMPORT) + add(OnboardingStep.SUMMARY) + } + } + + /** + * The steps still ahead of [state]'s current one, by what is known now. + * An unknown projects the longest route, so that a count built on it can + * only shrink as the answers come in. + */ + fun remainder(state: OnboardingState, plan: RegionPlan?): List = + when (val step = state.current) { + OnboardingStep.WELCOME, + OnboardingStep.ACKNOWLEDGEMENT, + OnboardingStep.PREFERENCES, + OnboardingStep.PERMISSIONS -> Intro.drop(Intro.indexOf(step) + 1) + + OnboardingStep.WAY_IN -> when (state.choices.wayIn) { + WayIn.CLASS_CODE -> listOf(OnboardingStep.CLASS_CODE) + WayIn.FIND_SCHOOL -> listOf(OnboardingStep.REGION) + regionTail(plan) + null -> emptyList() + } + + OnboardingStep.REGION -> regionTail(plan) + + OnboardingStep.SCHOOL, + OnboardingStep.PROVIDER -> regionTail(plan).let { tail -> tail.drop(tail.indexOf(step) + 1) } + + // Nothing is known until the join answers, and the join screen + // shows no dots; the next chapter starts behind it. + OnboardingStep.CLASS_CODE -> emptyList() + + OnboardingStep.SIGN_IN -> listOf(OnboardingStep.IMPORT, OnboardingStep.SUMMARY) + OnboardingStep.IMPORT -> listOf(OnboardingStep.SUMMARY) + OnboardingStep.SUMMARY -> emptyList() + } + + /** + * Step k of n in the current chapter, or `null` where no dots are drawn: + * on the join screen, and wherever the chapter is one step long. + * + * A chapter starts at the beginning of the path, after the last chooser and + * after the last join screen. The chooser itself closes the introduction, + * so what lies beyond it is never counted there. + */ + fun progress(state: OnboardingState, plan: RegionPlan?): StepProgress? { + if (state.current == OnboardingStep.CLASS_CODE) return null + val start = chapterStart(state) + val walked = state.path.subList(start, state.path.size) + val ahead = if (state.current == OnboardingStep.WAY_IN) emptyList() else buildList { + for (step in remainder(state, plan)) { + if (step == OnboardingStep.CLASS_CODE) break + add(step) + if (step == OnboardingStep.WAY_IN) break + } + } + val counted = (walked + ahead).filter { it != OnboardingStep.CLASS_CODE } + val n = counted.size + val k = walked.count { it != OnboardingStep.CLASS_CODE } + if (n < 2 || k < 1) return null + return StepProgress(chapter = chapterOf(state, start), k = k, n = n) + } + + private fun chapterStart(state: OnboardingState): Int { + var start = 0 + for (index in 0 until state.depth) { + val step = state.path[index] + if (step == OnboardingStep.WAY_IN || step == OnboardingStep.CLASS_CODE) start = index + 1 + } + return start + } + + private fun chapterOf(state: OnboardingState, start: Int): Chapter = + when (state.path.getOrNull(start - 1)) { + OnboardingStep.WAY_IN -> Chapter.SCHOOL + OnboardingStep.CLASS_CODE -> Chapter.CLASS + else -> if (state.path.first() in Intro) Chapter.INTRO else Chapter.DIARY + } + + fun heroMode(step: OnboardingStep): HeroMode = when (step) { + OnboardingStep.CLASS_CODE -> HeroMode.HIDDEN + OnboardingStep.REGION, + OnboardingStep.SCHOOL, + OnboardingStep.PROVIDER, + OnboardingStep.SIGN_IN -> HeroMode.COMPACT + else -> HeroMode.FULL + } + + /** + * Forward is deeper. Not ordinal: PROVIDER → CLASS_CODE goes to a lower + * ordinal and is plainly a step forward. + */ + fun isForward(fromDepth: Int, toDepth: Int): Boolean = toDepth > fromDepth + + /** + * The steps the badge morphs along: [path], but still holding the steps a + * back gesture has just popped, so the badge has the shape it is leaving to + * morph *from*. A path that went elsewhere at some depth replaces the trail. + */ + fun badgeTrail(previous: List, path: List): List = + if (previous.size >= path.size && previous.subList(0, path.size) == path) previous else path +} + +/** The saved-state keys, one per field, so a key can never hold two things. */ +internal object OnboardingKeys { + const val PATH = "onboarding.path" + const val FLOOR = "onboarding.floor" + const val WAY_IN = "onboarding.way_in" + const val REGION = "onboarding.region" + const val SCHOOL_HINT = "onboarding.school_hint" + const val SCHOOL_ID = "onboarding.school_id" + const val SCHOOL_NAME = "onboarding.school_name" + const val SYSTEM = "onboarding.system" + const val CLASS_BOUND = "onboarding.class_bound" + const val RESUME_FROM = "onboarding.resume_from" + + val all = listOf( + PATH, FLOOR, WAY_IN, REGION, SCHOOL_HINT, SCHOOL_ID, SCHOOL_NAME, SYSTEM, CLASS_BOUND, RESUME_FROM, + ) +} + +/** + * The state as bundle values: strings, numbers and one `ArrayList`. + * + * Plain keys rather than one encoded string, because the path is never empty + * and nothing here needs escaping; and a pure pair of functions so the mapping + * is asked on the JVM rather than trusted. + */ +fun OnboardingState.toSaved(): Map = mapOf( + OnboardingKeys.PATH to ArrayList(path.map { it.name }), + OnboardingKeys.FLOOR to floor, + OnboardingKeys.WAY_IN to choices.wayIn?.name, + OnboardingKeys.REGION to choices.region, + OnboardingKeys.SCHOOL_HINT to choices.schoolHint, + OnboardingKeys.SCHOOL_ID to choices.school?.id, + OnboardingKeys.SCHOOL_NAME to choices.school?.name, + OnboardingKeys.SYSTEM to choices.system, + OnboardingKeys.CLASS_BOUND to choices.classBound, + OnboardingKeys.RESUME_FROM to choices.resumeFrom, +) + +/** + * [toSaved] read back, or `null` for anything that is not one — an unknown + * step name from another build, a floor past the path. Nothing is better than + * a guessed flow: the caller then starts afresh. + */ +fun onboardingStateOf(saved: Map): OnboardingState? { + val names = (saved[OnboardingKeys.PATH] as? List<*>) ?: return null + val path = names.map { name -> + OnboardingStep.entries.firstOrNull { it.name == name } ?: return null + } + if (path.isEmpty()) return null + val floor = (saved[OnboardingKeys.FLOOR] as? Int) ?: 0 + if (floor !in path.indices) return null + val schoolId = saved[OnboardingKeys.SCHOOL_ID] as? Long + val schoolName = saved[OnboardingKeys.SCHOOL_NAME] as? String + return OnboardingState( + path = path, + floor = floor, + choices = OnboardingChoices( + wayIn = (saved[OnboardingKeys.WAY_IN] as? String)?.let { name -> + WayIn.entries.firstOrNull { it.name == name } + }, + region = saved[OnboardingKeys.REGION] as? String, + schoolHint = saved[OnboardingKeys.SCHOOL_HINT] as? String, + school = if (schoolId != null && schoolName != null) PickedSchool(schoolId, schoolName) else null, + system = saved[OnboardingKeys.SYSTEM] as? Int, + classBound = saved[OnboardingKeys.CLASS_BOUND] as? Boolean ?: false, + resumeFrom = saved[OnboardingKeys.RESUME_FROM] as? String, + ), + ) +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingHero.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingHero.kt index eef73d82..c8c563cd 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingHero.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingHero.kt @@ -26,9 +26,16 @@ import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.AltRoute +import androidx.compose.material.icons.automirrored.rounded.Login +import androidx.compose.material.icons.rounded.CloudDownload import androidx.compose.material.icons.rounded.Key +import androidx.compose.material.icons.rounded.Lock +import androidx.compose.material.icons.rounded.Map import androidx.compose.material.icons.rounded.Notifications +import androidx.compose.material.icons.rounded.School import androidx.compose.material.icons.rounded.Shield +import androidx.compose.material.icons.rounded.TaskAlt import androidx.compose.material.icons.rounded.Tune import androidx.compose.material.icons.rounded.WavingHand import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -39,6 +46,9 @@ import androidx.compose.material3.Surface import androidx.compose.material3.toPath import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment @@ -60,6 +70,7 @@ import androidx.graphics.shapes.Morph import androidx.graphics.shapes.RoundedPolygon import com.lumenpearson.lessons.R import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding import kotlin.math.floor import kotlinx.coroutines.delay @@ -84,7 +95,7 @@ private const val GlyphOutMillis = 120 /** * The strip above the first-run steps: one shape that becomes the next step's - * shape, and a row of dots that says how far along the flow is. + * shape, and a row of dots that says how far along the chapter is. * * Adapted from `OnboardingHero.kt` and `OnboardingProgressHeader.kt` in * [GMS Flags Reborn](https://github.com/polodarb/GMS-Flags-Reborn) (Apache 2.0) @@ -93,43 +104,53 @@ private const val GlyphOutMillis = 120 * polygons, drawn on a Canvas, with the progress driven by an `Animatable` that * is reset whenever the step changes. What is left behind is the rest of that * screen — the orbiting accent shapes, the parallax and the depth maths — which - * belongs to an app whose first run is four screens of its own artwork. This - * one is a school timetable; one shape is the whole decoration it wants. + * belongs to an app whose first run is its own artwork. This one is a school + * timetable; one shape is the whole decoration it wants. * * **It lives outside the step's own content, above the transition.** That is * the entire reason the morph exists: `AnimatedContent` builds a fresh * composable per step, so a badge drawn inside a step could only ever fade in * as a new object. Held here, across the swap, it has a previous shape to - * become — which is the difference between the flow reading as five screens and - * reading as one screen changing its mind. + * become — which is the difference between the flow reading as a dozen screens + * and reading as one screen changing its mind. * - * The strip carries the status-bar inset, because it is now the top of the - * page, and carries it *inside* its animated height so that nothing of it is - * left behind on the last step. The body under it keeps its own scroll, so what - * passes under the clock on these four steps is this strip rather than the first - * card — a change from what `StepScaffold` used to do alone, and the price of a - * header that survives the step change. + * The strip carries the status-bar inset, because it is the top of the page, + * and carries it *inside* its animated height so that nothing of it is left + * behind where the strip is gone. * - * On [OnboardingStep.JOIN] the height animates to zero rather than the strip - * being dropped outright: the join screen is a screen of its own with its own - * heading, and a shape above it would be a second title. Animating rather than - * removing keeps the last step's arrival continuous with the four before it. + * How much of it shows is the step's [HeroMode]: all of it; the dots alone on + * the search and form steps, where a keyboard needs the height more than a + * shape does; or nothing on the join screen, which has its own heading — the + * height animates to zero rather than the strip being dropped, so the arrival + * stays continuous with the steps before it. Every duration is the reader's + * motion setting's ([LocalMotion]), which the first run used to ignore. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable internal fun OnboardingHero( - step: OnboardingStep, + state: OnboardingState, + progress: StepProgress?, modifier: Modifier = Modifier, ) { - val shown = step != OnboardingStep.JOIN + val motion = LocalMotion.current + val mode = OnboardingFlow.heroMode(state.current) // The status-bar inset is inside the animated height rather than around it. // Held outside, it would survive the collapse and leave the join screen // pushed down by a strip that is no longer there — and that screen draws its // own content under the bar, as every other full screen in this app does. val inset = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + val badge by animateDpAsState( + targetValue = if (mode == HeroMode.COMPACT) 0.dp else HeroHeight, + animationSpec = tween(motion.durationMillis(MorphMillis)), + label = "onboarding_hero_badge", + ) val height by animateDpAsState( - targetValue = if (shown) inset + HeroHeight + DotSize + ScreenPadding else 0.dp, - animationSpec = tween(MorphMillis), + targetValue = when (mode) { + HeroMode.HIDDEN -> 0.dp + HeroMode.COMPACT -> inset + DotSize + ScreenPadding + HeroMode.FULL -> inset + HeroHeight + DotSize + ScreenPadding + }, + animationSpec = tween(motion.durationMillis(MorphMillis)), label = "onboarding_hero_height", ) @@ -151,12 +172,25 @@ internal fun OnboardingHero( Box( modifier = Modifier .fillMaxWidth() - .height(HeroHeight), + .height(badge) + .clipToBounds(), contentAlignment = Alignment.Center, ) { - StepBadge(step = step) + StepBadge(state = state) + } + // A new chapter cross-fades in rather than the old row shrinking + // to its first dot, which would read as the flow going backwards. + AnimatedContent( + targetState = progress, + contentKey = { it?.chapter }, + transitionSpec = { + fadeIn(tween(motion.durationMillis(MorphMillis))) + .togetherWith(fadeOut(tween(motion.durationMillis(MorphMillis)))) + }, + label = "onboarding_hero_chapter", + ) { shown -> + if (shown == null) Spacer(Modifier.height(DotSize)) else StepDots(progress = shown) } - StepDots(step = step) Spacer(Modifier.height(ScreenPadding)) } } @@ -172,8 +206,16 @@ internal fun OnboardingHero( */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -private fun StepBadge(step: OnboardingStep) { - // One continuous position along the steps rather than a morph restarted at +private fun StepBadge(state: OnboardingState) { + val motion = LocalMotion.current + // The steps the badge morphs along. It keeps a step a back gesture has just + // popped until a different path replaces it, so the shape it is leaving is + // still there to morph *from*. + var remembered by remember { mutableStateOf(state.path) } + val trail = OnboardingFlow.badgeTrail(remembered, state.path) + SideEffect { remembered = trail } + + // One continuous position along the path rather than a morph restarted at // each change, and that is a fix rather than a preference. Restarting means // snapping the outline to the step just left and animating on from there, // so a second press inside the 420 ms — which on a first-run flow is an @@ -181,17 +223,18 @@ private fun StepBadge(step: OnboardingStep) { // forwards. The reference has exactly that; `animateFloatAsState` retargets // from wherever the value currently is, so an interrupted morph carries on // from the outline actually on screen, and going back a step is the same - // movement in reverse for free. + // movement in reverse for free. Depth, not ordinal: the flow branches. val position by animateFloatAsState( - targetValue = step.ordinal.toFloat(), - animationSpec = tween(MorphMillis), + targetValue = state.depth.toFloat(), + animationSpec = tween(motion.durationMillis(MorphMillis)), label = "onboarding_badge_position", ) - val steps = OnboardingStep.entries - val lower = floor(position).toInt().coerceIn(0, steps.lastIndex) - val upper = (lower + 1).coerceAtMost(steps.lastIndex) + val lower = floor(position).toInt().coerceIn(0, trail.lastIndex) + val upper = (lower + 1).coerceAtMost(trail.lastIndex) - val morph = remember(lower, upper) { Morph(badgeShape(steps[lower]), badgeShape(steps[upper])) } + val from = trail[lower] + val to = trail[upper] + val morph = remember(from, to) { Morph(badgeShape(from), badgeShape(to)) } val progress = (position - lower).coerceIn(0f, 1f) val path = remember { Path() } val container = MaterialTheme.colorScheme.primaryContainer @@ -217,10 +260,10 @@ private fun StepBadge(step: OnboardingStep) { } AnimatedContent( - targetState = step, + targetState = state.current, transitionSpec = { - (fadeIn(tween(GlyphInMillis)) + scaleIn(initialScale = 0.7f)) - .togetherWith(fadeOut(tween(GlyphOutMillis)) + scaleOut(targetScale = 1.2f)) + (fadeIn(tween(motion.durationMillis(GlyphInMillis))) + scaleIn(initialScale = 0.7f)) + .togetherWith(fadeOut(tween(motion.durationMillis(GlyphOutMillis))) + scaleOut(targetScale = 1.2f)) }, label = "onboarding_hero_glyph", ) { current -> @@ -235,27 +278,22 @@ private fun StepBadge(step: OnboardingStep) { } /** - * How far along the flow is: one dot per introduction step, the current one - * stretched into a bar. + * How far along the chapter is: one dot per step, the current one stretched + * into a bar. * - * [OnboardingStep.JOIN] is deliberately not counted. The dots are a promise - * about how much reading is left, and the join screen is not reading — it is - * the thing the reading was for. Counting it would also mean the row losing a - * dot at the moment the strip collapses, which reads as the flow having got - * longer. + * The dots count a chapter ([StepProgress]) and never the join screen: they are + * a promise about how much is left, and a count that grew — at the chooser, + * where the rest of the flow first becomes known — would break it. So the + * introduction ends at the chooser, and choosing a way starts a new count. */ @Composable -private fun StepDots(step: OnboardingStep) { - val counted = OnboardingStep.entries.filter { it != OnboardingStep.JOIN } - // On the join step the strip is collapsing, and `step` is no longer one of - // the dots: without this the stretched bar would shrink back to a dot on - // the way out, which reads as the flow having gone backwards at the very - // moment it finished. It stays on the last step it belonged to. - val marked = if (step == OnboardingStep.JOIN) counted.last() else step +private fun StepDots(progress: StepProgress) { + val motion = LocalMotion.current val label = correctedString( - R.string.onboarding_step_of, - marked.ordinal + 1, - counted.size, + R.string.onboarding_step_of_chapter, + correctedString(progress.chapter.labelRes), + progress.k, + progress.n, ) Row( @@ -269,42 +307,50 @@ private fun StepDots(step: OnboardingStep) { contentDescription = label }, ) { - counted - .forEach { entry -> - val current = entry == marked - val width by animateDpAsState( - targetValue = if (current) CurrentDotWidth else DotSize, - animationSpec = tween(MorphMillis), - label = "onboarding_dot_width", - ) - val colour by animateColorAsState( - targetValue = if (entry.ordinal <= marked.ordinal) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.surfaceContainerHighest - }, - animationSpec = tween(MorphMillis), - label = "onboarding_dot_colour", - ) - Surface( - modifier = Modifier.size(width = width, height = DotSize), - shape = RoundedCornerShape(percent = 50), - color = colour, - content = {}, - ) - } + for (index in 1..progress.n) { + val current = index == progress.k + val width by animateDpAsState( + targetValue = if (current) CurrentDotWidth else DotSize, + animationSpec = tween(motion.durationMillis(MorphMillis)), + label = "onboarding_dot_width", + ) + val colour by animateColorAsState( + targetValue = if (index <= progress.k) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.surfaceContainerHighest + }, + animationSpec = tween(motion.durationMillis(MorphMillis)), + label = "onboarding_dot_colour", + ) + Surface( + modifier = Modifier.size(width = width, height = DotSize), + shape = RoundedCornerShape(percent = 50), + color = colour, + content = {}, + ) + } } } +/** The chapter's name, which the dots' description reads out. */ +private val Chapter.labelRes: Int + get() = when (this) { + Chapter.INTRO -> R.string.onboarding_chapter_intro + Chapter.SCHOOL -> R.string.onboarding_chapter_school + Chapter.CLASS -> R.string.onboarding_chapter_class + Chapter.DIARY -> R.string.onboarding_chapter_diary + } + /** * The shape each step wears. * * Chosen for how different the outlines are from their neighbours rather than * for meaning: a morph between two shapes of the same family is a wobble, and - * the point of the badge is that the change is unmistakable. [OnboardingStep.JOIN] + * the point of the badge is that the change is unmistakable. The join screen * never draws — the strip has collapsed by then — but it needs an entry, and - * the welcome shape is the honest one to give it: it is the shape the badge is - * wearing as it leaves. + * the welcome shape is the honest one to give it: it is what the badge last + * wore when the flow first had one. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) private fun badgeShape(step: OnboardingStep): RoundedPolygon = when (step) { @@ -312,7 +358,14 @@ private fun badgeShape(step: OnboardingStep): RoundedPolygon = when (step) { OnboardingStep.ACKNOWLEDGEMENT -> MaterialShapes.Clover4Leaf OnboardingStep.PREFERENCES -> MaterialShapes.Cookie6Sided OnboardingStep.PERMISSIONS -> MaterialShapes.PuffyDiamond - OnboardingStep.JOIN -> MaterialShapes.Cookie9Sided + OnboardingStep.WAY_IN -> MaterialShapes.Clover8Leaf + OnboardingStep.CLASS_CODE -> MaterialShapes.Cookie9Sided + OnboardingStep.REGION -> MaterialShapes.Sunny + OnboardingStep.SCHOOL -> MaterialShapes.Pentagon + OnboardingStep.PROVIDER -> MaterialShapes.Gem + OnboardingStep.SIGN_IN -> MaterialShapes.Arch + OnboardingStep.IMPORT -> MaterialShapes.SoftBurst + OnboardingStep.SUMMARY -> MaterialShapes.Cookie12Sided } /** The glyph inside the badge: what the step is about, in one picture. */ @@ -321,7 +374,14 @@ private fun badgeGlyph(step: OnboardingStep): ImageVector = when (step) { OnboardingStep.ACKNOWLEDGEMENT -> Icons.Rounded.Shield OnboardingStep.PREFERENCES -> Icons.Rounded.Tune OnboardingStep.PERMISSIONS -> Icons.Rounded.Notifications - OnboardingStep.JOIN -> Icons.Rounded.Key + OnboardingStep.WAY_IN -> Icons.AutoMirrored.Rounded.AltRoute + OnboardingStep.CLASS_CODE -> Icons.Rounded.Key + OnboardingStep.REGION -> Icons.Rounded.Map + OnboardingStep.SCHOOL -> Icons.Rounded.School + OnboardingStep.PROVIDER -> Icons.AutoMirrored.Rounded.Login + OnboardingStep.SIGN_IN -> Icons.Rounded.Lock + OnboardingStep.IMPORT -> Icons.Rounded.CloudDownload + OnboardingStep.SUMMARY -> Icons.Rounded.TaskAlt } /** @@ -371,10 +431,12 @@ internal fun OnboardingReveal( delayMillis: Int = 0, content: @Composable ColumnScope.() -> Unit, ) { + val motion = LocalMotion.current val progress = remember { Animatable(0f) } LaunchedEffect(Unit) { - if (delayMillis > 0) delay(delayMillis.toLong()) - progress.animateTo(targetValue = 1f, animationSpec = tween(MorphMillis)) + val wait = motion.durationMillis(delayMillis) + if (wait > 0) delay(wait.toLong()) + progress.animateTo(targetValue = 1f, animationSpec = tween(motion.durationMillis(MorphMillis))) } // A `Column`, and the receiver says so. This was a `Box` taking a plain diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt index 9d9ca42c..fa6e8869 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt @@ -68,13 +68,18 @@ internal val ActionHeight: Dp = 56.dp * in exactly this row. The shape carries the meaning: the label sits hard left * and the glyph hard right, so the button reads as "what this does" on one end * and "where it takes you" on the other, and the two ends stay in the same place - * on all four screens while everything above them changes. + * on every step of the first run while everything above them changes. * * @param onBack `null` on the first step, which has nowhere to go back to. The * square is then dropped rather than disabled — a dead control in the corner * of the very first screen a user sees is worse than no control. * @param busy replaces the trailing glyph with a spinner rather than swapping * the whole button, which would move the label out from under the finger. + * @param footer drawn under the row, inside the same inset: the welcome step's + * line accepting the terms and the privacy policy. Inside rather than below + * the component, because the row carries the navigation-bar inset, and a + * line placed after it would sit under the gesture bar — or, given an inset + * of its own, count it twice. */ @Composable internal fun OnboardingActions( @@ -85,75 +90,104 @@ internal fun OnboardingActions( onBack: (() -> Unit)? = null, enabled: Boolean = true, busy: Boolean = false, + footer: (@Composable () -> Unit)? = null, ) { val view = rememberHapticView() - Row( + Column( modifier = modifier .fillMaxWidth() .navigationBarsPadding() .padding(ScreenPadding), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - if (onBack != null) { - OutlinedButton( + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (onBack != null) BackSquare(onBack) + + Button( onClick = { LessonsHaptics.press(view) - onBack() + onClick() }, - modifier = Modifier.size(ActionHeight), - shape = MaterialTheme.shapes.large, - contentPadding = PaddingValues(0.dp), + enabled = enabled && !busy, + modifier = Modifier + .weight(1f) + .height(ActionHeight), ) { - Icon( - imageVector = Icons.AutoMirrored.Rounded.ArrowBack, - contentDescription = correctedString(R.string.action_back), - modifier = Modifier.size(24.dp), + Text( + text = label, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, ) - } - } - - Button( - onClick = { - LessonsHaptics.press(view) - onClick() - }, - enabled = enabled && !busy, - modifier = Modifier - .weight(1f) - .height(ActionHeight), - ) { - Text( - text = label, - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.Bold, - ) - Spacer(Modifier.weight(1f)) + Spacer(Modifier.weight(1f)) - if (busy) { - CircularProgressIndicator( - modifier = Modifier.size(24.dp), - strokeWidth = 2.dp, - color = MaterialTheme.colorScheme.onPrimary, - ) - } else { - Icon( - imageVector = icon, - contentDescription = null, - modifier = Modifier.size(24.dp), - ) + if (busy) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary, + ) + } else { + Icon( + imageVector = icon, + contentDescription = null, + modifier = Modifier.size(24.dp), + ) + } } } + footer?.invoke() + } +} + +/** + * The first run's bottom row with nothing but the way back, for a step whose + * one action lives in its own form — the sign-in's button is the form's, + * because the password must not leave the form to reach a button out here. + */ +@Composable +internal fun OnboardingBackRow(onBack: () -> Unit, modifier: Modifier = Modifier) { + Row( + modifier = modifier + .fillMaxWidth() + .navigationBarsPadding() + .padding(ScreenPadding), + ) { + BackSquare(onBack) + } +} + +/** The square way back, the same on every step. */ +@Composable +private fun BackSquare(onBack: () -> Unit) { + val view = rememberHapticView() + OutlinedButton( + onClick = { + LessonsHaptics.press(view) + onBack() + }, + modifier = Modifier.size(ActionHeight), + shape = MaterialTheme.shapes.large, + contentPadding = PaddingValues(0.dp), + ) { + Icon( + imageVector = Icons.AutoMirrored.Rounded.ArrowBack, + contentDescription = correctedString(R.string.action_back), + modifier = Modifier.size(24.dp), + ) } } /** * The big rounded headline every first-run step opens with. * - * One composable rather than four copies of the same `Text` so that the four - * screens cannot drift apart in size or weight, which is precisely what happened + * One composable rather than a copy of the same `Text` per step, so that the + * steps cannot drift apart in size or weight, which is precisely what happened * to the two that existed before this. */ @Composable diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingRows.kt new file mode 100644 index 00000000..f3005963 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingRows.kt @@ -0,0 +1,178 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material.icons.rounded.Search +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile +import com.lumenpearson.lessons.core.designsystem.component.GroupRow +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.theme.AccentTone +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.designsystem.theme.appScrollMotionBlur +import com.lumenpearson.lessons.core.designsystem.theme.rowContainer +import com.lumenpearson.lessons.core.designsystem.theme.rowSelectedContainer + +/** + * The shape of the list steps — region, school, provider: a lazy list that + * grows, then the action row, which does not move. + * + * Separate from `StepScaffold` because that one scrolls a plain column, and a + * column that scrolls cannot hold a lazy list — eighty-nine regions drawn at + * once is a first frame nobody should wait for. The keyboard padding is on the + * outer column, as the join screen has it, so the keyboard shrinks the list and + * lifts the action rather than covering it. + */ +@Composable +internal fun ListStepScaffold( + actions: @Composable () -> Unit, + content: LazyListScope.() -> Unit, +) { + val listState = rememberLazyListState() + Column( + modifier = Modifier + .fillMaxSize() + .imePadding(), + ) { + LazyColumn( + state = listState, + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .appScrollMotionBlur(listState), + contentPadding = PaddingValues(horizontal = ScreenPadding, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(GroupSpacing), + content = content, + ) + actions() + } +} + +/** + * A row that is one answer of several: highlighted when chosen, and said to be + * so, because the highlight alone is a colour a screen reader cannot see. + * + * On `GroupRow` rather than `GroupItem`, which has no container parameter and + * so no way to show a choice other than by its switch. + */ +@Composable +internal fun ChoiceRow( + title: String, + tone: AccentTone, + selected: Boolean, + modifier: Modifier = Modifier, + subtitle: String? = null, + icon: ImageVector? = null, + onClick: (() -> Unit)? = null, + trailing: @Composable (() -> Unit)? = null, + below: @Composable (ColumnScope.() -> Unit)? = null, +) { + GroupRow( + modifier = modifier.semantics { + this.selected = selected + if (onClick != null) role = Role.RadioButton + }, + container = if (selected) MaterialTheme.colorScheme.rowSelectedContainer else MaterialTheme.colorScheme.rowContainer, + onClick = onClick, + ) { + if (icon != null) AccentIconTile(icon = icon, tone = tone) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(text = title, style = MaterialTheme.typography.titleMedium) + if (subtitle != null) { + Text( + text = subtitle, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + below?.invoke(this) + } + trailing?.invoke() + } +} + +/** A sentence in place of a list: nothing found, what to type, why the search is resting. */ +@Composable +internal fun NoteCard(text: String, modifier: Modifier = Modifier) { + RoundedCardContainer(modifier = modifier) { + GroupRow { + Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** + * The search field of the region and school steps. + * + * @param onSearch the keyboard's search key; `null` where typing is enough. + */ +@Composable +internal fun SearchBox( + value: String, + onValueChange: (String) -> Unit, + label: String, + clearLabel: String, + modifier: Modifier = Modifier, + onSearch: (() -> Unit)? = null, +) { + val keyboard = LocalSoftwareKeyboardController.current + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier.fillMaxWidth(), + label = { Text(label) }, + leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) }, + trailingIcon = if (value.isEmpty()) { + null + } else { + { + IconButton(onClick = { onValueChange("") }) { + Icon(Icons.Rounded.Close, contentDescription = clearLabel) + } + } + }, + singleLine = true, + shape = MaterialTheme.shapes.large, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions( + onSearch = { + keyboard?.hide() + onSearch?.invoke() + }, + ), + ) +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt index d557aad6..9a2f439f 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -35,10 +36,9 @@ import androidx.compose.material.icons.rounded.Widgets import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration @@ -54,6 +54,7 @@ import com.lumenpearson.lessons.core.designsystem.component.SectionHeader import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding import com.lumenpearson.lessons.core.designsystem.theme.ThemeRevealAnchor import com.lumenpearson.lessons.core.designsystem.theme.accentTone @@ -61,6 +62,7 @@ import com.lumenpearson.lessons.core.designsystem.theme.appSlideMotionBlur import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.core.model.ThemeMode import com.lumenpearson.lessons.ui.join.JoinScreen +import com.lumenpearson.lessons.ui.legal.LegalAcceptanceLine import com.lumenpearson.lessons.ui.settings.EdgeFadeRow import com.lumenpearson.lessons.ui.settings.PermissionCard import com.lumenpearson.lessons.ui.settings.SettingsUiState @@ -69,35 +71,7 @@ import com.lumenpearson.lessons.ui.settings.SupportsDynamicColor import com.lumenpearson.lessons.ui.settings.labelRes import com.lumenpearson.lessons.ui.settings.rememberPermissionPrompts -/** - * The five screens a new install opens with, in order. - * - * The order is Essentials' own and it is not arbitrary: say what this is, say - * what it is not and let the user opt out of the one thing it records, let them - * set the handful of preferences that change how the app feels before they have - * formed a habit, and only then ask for something. Putting the class-code field - * first — which is what the app did before — asks a stranger for a credential on - * a screen that has not yet said what the credential is for. - * - * [PERMISSIONS] goes last before [JOIN], for two reasons. It is the first time - * the app hands the user over to the system, and everything the three - * permissions are *for* — a bell in ten minutes, a replacement lesson, a - * morning summary — is about the timetable that arrives on the very next - * screen, so the ask sits as close to its payoff as the flow allows; put before - * [PREFERENCES] it would interrupt a run of in-app switches with two system - * dialogs. And [JOIN] is where `onboardingDone` is written, so a step in front - * of it leaves that rule — reaching the last step is what counts as "seen" — - * exactly as it was. - */ -enum class OnboardingStep { - WELCOME, - ACKNOWLEDGEMENT, - PREFERENCES, - PERMISSIONS, - JOIN, -} - -/** How long one step takes to slide the next one in. */ +/** How long one step takes to slide the next one in, before the reader's motion setting. */ private const val StepTransitionMillis = 400 /** @@ -108,96 +82,97 @@ private const val StepTransitionMillis = 400 * user: anything long enough to notice as a sequence reads as the screen * being slow. */ -private const val RevealStagger = 90 +internal const val RevealStagger = 90 + +/** The top of the path, which is what the transition animates between. */ +private data class PathTop(val step: OnboardingStep, val depth: Int) /** - * The first-run flow. + * The first run: the introduction, the chooser, and whichever way in is chosen. + * + * There is no navigation graph behind it. The path is [OnboardingViewModel]'s + * saved state ([OnboardingState]); every preference on the introduction is + * written straight through [SettingsViewModel] — the same instance the settings + * screen uses, so anything set here is already stored by the time the flow + * ends — and the class-code step is the real join screen rather than a copy. * - * There is no navigation graph behind it and no view model of its own: the step - * is one piece of saveable state, every preference on it is written straight - * through [SettingsViewModel] — the same instance the settings screen uses, so - * anything set here is already stored by the time the flow ends — and the last - * step is the real join screen rather than a copy of it. + * The flow, not a credential, decides when it ends. The join and the diary's + * registration each write one mid-way, and the shell's hold (set on entering + * those steps) keeps this screen up until [OnboardingViewModel.finish]. * - * Reaching the last step is what counts as "seen". It is recorded there rather - * than after a successful join so that somebody who closes the app at the code - * field is not made to read the introduction a second time. + * @param introduced the introduction was seen before — the flow opens at the + * chooser. Latched by the caller: the flow records it on reaching the + * chooser, and re-reading it live would restart the flow under the user. */ @Composable fun OnboardingScreen( + introduced: Boolean, modifier: Modifier = Modifier, - viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory), + viewModel: OnboardingViewModel = viewModel(factory = OnboardingViewModel.Factory), + settingsViewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory), ) { - val state by viewModel.uiState.collectAsStateWithLifecycle() - // Saveable, not remembered, and the language picker on the first step is - // what makes that load-bearing rather than tidy. Below API 33 choosing a - // language recreates the activity — that is the only way to replace a base - // context — and a `remember` here would have put the user back on the - // welcome screen every time they touched it. `recreate()` saves and - // restores instance state exactly as a rotation does, so the step, the - // latched "show the introduction" decision in `LessonsApp` and the settings - // view model (retained with the ViewModelStore) all come back as they were; - // only the slide animation is lost, which is the right thing to lose. - var step by rememberSaveable { mutableStateOf(OnboardingStep.WELCOME) } - - fun goTo(next: OnboardingStep) { - if (next == OnboardingStep.JOIN) viewModel.setOnboardingDone() - step = next - } + LaunchedEffect(Unit) { viewModel.start(introduced) } - // The system gesture walks the same path as the button, so the flow has one - // way back rather than two that disagree. On the first step it is left - // alone, which lets it do what it means there: leave the app. - // - // Bounded rather than trusting `enabled` to have caught up. That flag - // reaches the callback in a SideEffect, after the composition is applied, - // while the write below lands in the snapshot at once — so two back events - // drained in one input pass both see it true, and the second asks for the - // step before the first. Reachable by tapping back twice during the slide, - // which is exactly where this screen is slowest, and a crash writes no - // saved state, so it restarted the whole introduction. - BackHandler(enabled = step != OnboardingStep.WELCOME) { - OnboardingStep.entries.getOrNull(step.ordinal - 1)?.let { step = it } - } + val settings by settingsViewModel.uiState.collectAsStateWithLifecycle() + val flow by viewModel.flow.collectAsStateWithLifecycle() + val plan by viewModel.plan.collectAsStateWithLifecycle() + val motion = LocalMotion.current Surface( modifier = modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer, ) { + // One frame after the splash, while a saved flow or the stored hold is + // read: a surface, rather than a guessed first step and a jump. + val state = flow ?: return@Surface + val progress = remember(state, plan) { OnboardingFlow.progress(state, plan) } + + // The system gesture walks the same path as the back square, so the + // flow has one way back rather than two that disagree. At the floor it + // is left alone, which lets it do what it means there: leave the app. + // + // `back()` is bounded by the floor rather than trusting `enabled` to + // have caught up. That flag reaches the callback in a SideEffect, after + // the composition is applied, while the write lands in the snapshot at + // once — so two back events drained in one input pass both see it + // true. Reachable by tapping back twice during the slide, which is + // exactly where this screen is slowest. + BackHandler(enabled = state.canGoBack) { viewModel.back() } + val onBack: (() -> Unit)? = if (state.canGoBack) viewModel::back else null + Column(modifier = Modifier.fillMaxSize()) { // Above the transition rather than inside a step, because that is - // what lets one shape become the next one instead of five shapes + // what lets one shape become the next one instead of a dozen shapes // fading past each other. See OnboardingHero. - OnboardingHero(step = step) + OnboardingHero(state = state, progress = progress) AnimatedContent( - targetState = step, + targetState = PathTop(state.current, state.depth), transitionSpec = { - // Direction carries the meaning: forward pushes the old screen - // off to the left, back pulls it in from there. Without it the - // two directions look identical and the flow feels one-way. - if (targetState.ordinal > initialState.ordinal) { - (slideInHorizontally { it } + fadeIn(tween(StepTransitionMillis))) - .togetherWith( - slideOutHorizontally { -it } + fadeOut(tween(StepTransitionMillis)), - ) + val millis = motion.durationMillis(StepTransitionMillis) + // Direction carries the meaning: forward pushes the old + // screen off to the left, back pulls it in from there. + // Depth, not ordinal — the flow branches, and the provider + // step's way to the class code is plainly forward. + if (OnboardingFlow.isForward(initialState.depth, targetState.depth)) { + (slideInHorizontally(tween(millis)) { it } + fadeIn(tween(millis))) + .togetherWith(slideOutHorizontally(tween(millis)) { -it } + fadeOut(tween(millis))) } else { - (slideInHorizontally { -it } + fadeIn(tween(StepTransitionMillis))) - .togetherWith( - slideOutHorizontally { it } + fadeOut(tween(StepTransitionMillis)), - ) + (slideInHorizontally(tween(millis)) { -it } + fadeIn(tween(millis))) + .togetherWith(slideOutHorizontally(tween(millis)) { it } + fadeOut(tween(millis))) } }, label = "onboarding_step", - ) { current -> - // Each step travels a full screen width, which is the biggest single - // movement in the app; blurring it is what the scroll-blur setting - // means here. Driven by the transition's own fraction, so the - // shader and the slide can never disagree about where the page is. + ) { top -> + // Each step travels a full screen width, which is the biggest + // single movement in the app; blurring it is what the + // scroll-blur setting means here. Driven by the transition's + // own fraction, so the shader and the slide can never disagree + // about where the page is. val slide = transition.animateFloat( - transitionSpec = { tween(StepTransitionMillis) }, + transitionSpec = { tween(motion.durationMillis(StepTransitionMillis)) }, label = "onboarding_slide", - ) { state -> if (state == EnterExitState.Visible) 1f else 0f } + ) { phase -> if (phase == EnterExitState.Visible) 1f else 0f } val travel = LocalConfiguration.current.screenWidthDp.dp Box( @@ -209,35 +184,50 @@ fun OnboardingScreen( travel = travel, ), ) { - when (current) { + when (top.step) { OnboardingStep.WELCOME -> WelcomeStep( - state = state, - viewModel = viewModel, - onNext = { goTo(OnboardingStep.ACKNOWLEDGEMENT) }, + state = settings, + viewModel = settingsViewModel, + onNext = viewModel::next, ) OnboardingStep.ACKNOWLEDGEMENT -> AcknowledgementStep( - state = state, - viewModel = viewModel, - onBack = { goTo(OnboardingStep.WELCOME) }, - onNext = { goTo(OnboardingStep.PREFERENCES) }, + state = settings, + viewModel = settingsViewModel, + onBack = onBack, + onNext = viewModel::next, ) OnboardingStep.PREFERENCES -> PreferencesStep( - state = state, - viewModel = viewModel, - onBack = { goTo(OnboardingStep.ACKNOWLEDGEMENT) }, - onNext = { goTo(OnboardingStep.PERMISSIONS) }, + state = settings, + viewModel = settingsViewModel, + onBack = onBack, + onNext = viewModel::next, ) OnboardingStep.PERMISSIONS -> PermissionsStep( - onBack = { goTo(OnboardingStep.PREFERENCES) }, - onNext = { goTo(OnboardingStep.JOIN) }, + onBack = onBack, + onNext = viewModel::next, ) - OnboardingStep.JOIN -> JoinScreen( - onBack = { goTo(OnboardingStep.PERMISSIONS) }, + OnboardingStep.WAY_IN -> WayInStep(viewModel = viewModel, onBack = onBack) + + OnboardingStep.CLASS_CODE -> JoinScreen( + onBack = onBack, + onJoined = { viewModel.onJoined() }, ) + + OnboardingStep.REGION -> RegionStep(viewModel = viewModel, onBack = onBack) + + OnboardingStep.SCHOOL -> SchoolStep(viewModel = viewModel, onBack = onBack) + + OnboardingStep.PROVIDER -> ProviderStep(viewModel = viewModel, onBack = onBack) + + OnboardingStep.SIGN_IN -> SignInPage(viewModel = viewModel, onBack = onBack) + + OnboardingStep.IMPORT -> ImportPage(viewModel = viewModel) + + OnboardingStep.SUMMARY -> SummaryPage(settings = settings, viewModel = viewModel) } } } @@ -272,9 +262,14 @@ private fun WelcomeStep( StepScaffold( actions = { OnboardingActions( - label = correctedString(R.string.onboarding_action_begin), + label = correctedString(R.string.onboarding_action_proceed), icon = Icons.AutoMirrored.Rounded.ArrowForward, onClick = onNext, + // Always drawn, whatever the build says about where its + // documents are published: with no address the line opens the + // copies bundled in the APK, so there is never a first screen + // that asks to continue without saying on what terms. + footer = { LegalAcceptanceLine() }, ) }, ) { @@ -346,7 +341,7 @@ private fun WelcomeStep( private fun AcknowledgementStep( state: SettingsUiState, viewModel: SettingsViewModel, - onBack: () -> Unit, + onBack: (() -> Unit)?, onNext: () -> Unit, ) { Column( @@ -442,7 +437,7 @@ private fun AcknowledgementStep( private fun PreferencesStep( state: SettingsUiState, viewModel: SettingsViewModel, - onBack: () -> Unit, + onBack: (() -> Unit)?, onNext: () -> Unit, ) { StepScaffold( @@ -532,6 +527,10 @@ private fun PreferencesStep( * Step four: the three things the app needs from the system, asked one at a * time. * + * It comes before the chooser on both ways in, although a family that takes + * the diary way gets no alerts from it (K23): the chooser comes after the + * introduction, and an ask moved behind one branch would be an ask on one path. + * * Each permission gets a card of its own rather than a shared group, because * each is a separate question with a separate answer, and a group reads as one * block to be dealt with in one go — which is exactly the "allow everything" @@ -539,19 +538,19 @@ private fun PreferencesStep( * page's, from [PermissionCard]: the same button, the same wording, and the * same handling of a dialog the platform has stopped offering. * - * Nothing here blocks [OnboardingStep.JOIN]. The action moves on whatever the + * Nothing here blocks [OnboardingStep.WAY_IN]. The action moves on whatever the * answers were — «Потом» while something is missing, «Дальше» once nothing is — * and it is never disabled, because a pupil who refuses all three still gets a * timetable, a week view and a widget; what they lose is being told about them. * * The step is not skipped when everything is already granted either. Skipping - * forward would make the back gesture from [OnboardingStep.JOIN] land here and + * forward would make the back gesture from [OnboardingStep.WAY_IN] land here and * be thrown straight forward again, which is a flow with no way back rather * than a shortcut. */ @Composable private fun PermissionsStep( - onBack: () -> Unit, + onBack: (() -> Unit)?, onNext: () -> Unit, ) { val prompts = rememberPermissionPrompts() @@ -605,7 +604,7 @@ private fun PermissionsStep( * translation test to keep in step and four more chances for the same word to * end up spelled two ways. */ -private val AppLanguage.labelRes: Int +internal val AppLanguage.labelRes: Int get() = when (this) { AppLanguage.SYSTEM -> R.string.settings_language_system AppLanguage.RUSSIAN -> R.string.settings_language_russian @@ -623,7 +622,7 @@ private const val ProseTint = 0.5f * and its settings pages do not. See the note on `SectionHeader.titleColor`. */ @Composable -private fun AccentSection( +internal fun AccentSection( title: String, content: @Composable ColumnScope.() -> Unit, ) { @@ -645,11 +644,14 @@ private fun AccentSection( * it — is kept, one level up. */ @Composable -private fun StepScaffold( +internal fun StepScaffold( actions: @Composable () -> Unit, content: @Composable ColumnScope.() -> Unit, ) { - Column(modifier = Modifier.fillMaxSize()) { + // The keyboard padding on the outer column, as the join screen has it: + // on the sign-in step the keyboard then shrinks the scrolling body and + // lifts the row, rather than covering the form it was opened for. + Column(modifier = Modifier.fillMaxSize().imePadding()) { Column( modifier = Modifier .weight(1f) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt new file mode 100644 index 00000000..ed09cc49 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt @@ -0,0 +1,543 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.createSavedStateHandle +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.catalog.RegionLookupResult +import com.lumenpearson.lessons.core.data.catalog.RegionMatch +import com.lumenpearson.lessons.core.data.di.Graph +import com.lumenpearson.lessons.core.data.diary.DiaryCache +import com.lumenpearson.lessons.core.data.diary.DiaryImport +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.SettingsRepository +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.ui.diary.DiaryPlace +import com.lumenpearson.lessons.ui.diary.DiarySchoolRow +import com.lumenpearson.lessons.ui.diary.diaryPlaceOf +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +/** + * What the flow reaches in the rest of the app, as functions a test can + * replace one by one. `RegionLookup` has no public constructor and the diary's + * session type none either, which is why these are lambdas and adapters rather + * than the container's own objects. + */ +class OnboardingDeps( + val settings: SettingsRepository, + val shellMode: ShellModeSource, + val currentClass: suspend () -> Session?, + val currentDiary: suspend () -> DiarySession?, + val storedTarget: suspend () -> DiaryTarget?, + val signOutDiary: suspend () -> Result, + val signIn: OnboardingSignIn, + val diaryImport: DiaryImport, + val cache: DiaryCache, + val catalog: suspend () -> RegionCatalog, + val regionsByName: suspend (String) -> List, + val findRegions: suspend (String) -> RegionLookupResult, + val schools: suspend (regionKey: String, query: String) -> Result>, +) + +/** + * The sign-in step's heading: which diary, and where the password goes. + * + * @property forgotUrl the diary's own site, for «Забыли пароль?» — https only. + */ +@Immutable +data class SignInHeader( + val provider: DiaryProviderKey, + val place: DiaryPlace, + val schoolName: String?, + val classBound: Boolean, + val className: String?, + val forgotUrl: String?, +) + +/** + * The last screen: who the diary is, the class if there is one, and what the + * session costs to keep. + */ +@Immutable +data class SummaryUi( + val studentName: String?, + val studentClass: String?, + val studentSchool: String?, + val place: DiaryPlace?, + val login: String?, + val petersburg: Boolean, + val className: String?, + val classSchool: String?, +) { + /** A class is joined: the timetable, the widget and the alerts are the class's. */ + val inClass: Boolean get() = className != null +} + +/** + * The first run's state holder. + * + * Resolved against the activity's store, like every view model here — which + * means it outlives the flow: [finish] clears what it saved and marks it done, + * and [start] builds a fresh flow the next time the way in is shown (leaving + * the last class) instead of reopening the summary of the last one. + * + * What survives what: + * * the path and the answers ([OnboardingState]) are in [saved], so a + * recreation below API 33 (a language change) and a process death both + * bring the flow back where it was; + * * the login is in [SignInStep]'s memory: recreation yes, process death no; + * * the password is in the form's `remember` and nowhere here; + * * the diary's session between the phone's sign-in and our server's answer + * is a plain field of [SignInStep], dropped when the step is left. + * + * The hold (K3): entering the class-code or the sign-in step asks the shell to + * keep the flow on screen, because the join and the registration each write a + * credential that would otherwise swap the flow for a home mid-way; [finish] + * releases it. After a process death with no saved state, [start] resumes by + * [OnboardingFlow.resume]. + */ +class OnboardingViewModel( + private val saved: SavedStateHandle, + private val deps: OnboardingDeps, +) : ViewModel() { + + private val mutable = MutableStateFlow(null) + val flow: StateFlow = mutable.asStateFlow() + + private val catalogState = MutableStateFlow(null) + + val region = RegionFinder( + scope = viewModelScope, + catalog = ::catalog, + byName = deps.regionsByName, + find = deps.findRegions, + ) + val school = SchoolFinder(scope = viewModelScope, schools = deps.schools) + val signIn = SignInStep(scope = viewModelScope, signIn = deps.signIn) + val importing = ImportRunner(scope = viewModelScope, import = deps.diaryImport) + + val baseUrl: StateFlow = deps.settings.settings + .map { it.baseUrl } + .stateIn(viewModelScope, SharingStarted.Eagerly, "") + + /** What the chosen region makes of the rest of its chapter; `null` until one is chosen. */ + val plan: StateFlow = combine(catalogState, mutable) { catalog, state -> + catalog?.region(state?.choices?.region)?.let(::regionPlanOf) + }.stateIn(viewModelScope, SharingStarted.Eagerly, null) + + val provider: StateFlow = combine(catalogState, mutable) { catalog, state -> + val choices = state?.choices ?: return@combine null + catalog?.region(choices.region)?.let { providerPageOf(catalog, it, choices.school) } + }.stateIn(viewModelScope, SharingStarted.Eagerly, null) + + private val header = MutableStateFlow(null) + val signInHeader: StateFlow = header.asStateFlow() + + private val summaryState = MutableStateFlow(null) + val summary: StateFlow = summaryState.asStateFlow() + + /** The diary the sign-in step signs in to; resolved on entering it, never saved. */ + private var target: DiaryTarget? = null + + private var finished = false + + /** Bumped by every [start], so arriving at the same step in a new flow still counts as arriving. */ + private var generation = 0 + + init { + viewModelScope.launch { catalogState.value = deps.catalog() } + viewModelScope.launch { + mutable.filterNotNull() + .map { generation to it.current } + .distinctUntilChanged() + .collect { (_, step) -> entered(step) } + } + } + + /** + * Builds the flow the first time the way in is shown — from what was + * saved, else from the stored hold (a flow the process lost mid-way), else + * from the start. Called by the screen whenever it enters the composition. + */ + fun start(introduced: Boolean) { + if (mutable.value != null && !finished) return + finished = false + generation += 1 + mutable.value = null + onboardingStateOf(OnboardingKeys.all.associateWith { saved.get(it) })?.let { + mutable.value = it + return + } + viewModelScope.launch { + val shell = deps.shellMode.current() + if (!shell.held || shell.mode == ShellMode.NONE) { + set(OnboardingFlow.initial(introduced)) + return@launch + } + val resumed = OnboardingFlow.resume( + mode = shell.mode, + bindingUsable = classTargetOf(catalog(), deps.currentClass()?.diary) != null, + hasDiarySession = deps.currentDiary() != null, + ) + if (resumed == null) finish() else set(resumed) + } + } + + // --- The introduction and the chooser ------------------------------------------------- + + /** The introduction's own «next»: the steps run in order up to the chooser. */ + fun next() { + val state = mutable.value ?: return + val following = when (state.current) { + OnboardingStep.WELCOME -> OnboardingStep.ACKNOWLEDGEMENT + OnboardingStep.ACKNOWLEDGEMENT -> OnboardingStep.PREFERENCES + OnboardingStep.PREFERENCES -> OnboardingStep.PERMISSIONS + OnboardingStep.PERMISSIONS -> OnboardingStep.WAY_IN + else -> return + } + set(OnboardingFlow.push(state, following)) + } + + fun chooseWay(way: WayIn) = update { it.copy(choices = it.choices.copy(wayIn = way)) } + + fun proceedFromWayIn() { + val state = mutable.value ?: return + when (state.choices.wayIn) { + WayIn.CLASS_CODE -> set(OnboardingFlow.push(state, OnboardingStep.CLASS_CODE)) + WayIn.FIND_SCHOOL -> set(OnboardingFlow.push(state, OnboardingStep.REGION)) + null -> Unit + } + } + + fun setServer(url: String) { + viewModelScope.launch { deps.settings.update { it.copy(baseUrl = url) } } + } + + fun back() { + val state = mutable.value ?: return + if (!state.canGoBack) return + if (state.current == OnboardingStep.SIGN_IN) signIn.abandon() + set(OnboardingFlow.back(state)) + } + + // --- Region, school, provider --------------------------------------------------------- + + /** + * A region picked; [hint] is the school name typed, when the region was + * reached through the directory. Picking another region forgets the school + * and the system picked for the last one. + */ + fun pickRegion(key: String, hint: String? = null) = update { + if (it.choices.region == key && hint == null) { + it + } else { + it.copy(choices = it.choices.copy(region = key, schoolHint = hint, school = null, system = null)) + } + } + + fun proceedFromRegion() { + val state = mutable.value ?: return + if (state.choices.region == null) return + val next = if (plan.value?.showsSchool == true) OnboardingStep.SCHOOL else OnboardingStep.PROVIDER + set(OnboardingFlow.push(state, next)) + } + + fun pickSchool(row: DiarySchoolRow) = update { + it.copy(choices = it.choices.copy(school = PickedSchool(row.id, row.name))) + } + + fun proceedFromSchool() { + val state = mutable.value ?: return + set(OnboardingFlow.push(state, OnboardingStep.PROVIDER)) + } + + /** «Моей школы нет в списке»: on to the provider step, where the class code is. */ + fun skipSchool() { + val state = mutable.value ?: return + set(OnboardingFlow.push(state.copy(choices = state.choices.copy(school = null)), OnboardingStep.PROVIDER)) + } + + /** A «Сетевой город» row with no school: back to the school step, which is behind this one. */ + fun toSchool() { + val state = mutable.value ?: return + val before = state.path.getOrNull(state.depth - 1) + set(if (before == OnboardingStep.SCHOOL) OnboardingFlow.back(state) else OnboardingFlow.push(state, OnboardingStep.SCHOOL)) + } + + /** + * The system to sign in to, from the provider step. The server address is + * the screen's gate, before this is called: the registration needs one. + */ + fun signInWith(systemIndex: Int) { + val state = mutable.value ?: return + val withSystem = state.copy(choices = state.choices.copy(system = systemIndex, classBound = false)) + set(OnboardingFlow.push(withSystem, OnboardingStep.SIGN_IN)) + } + + fun toClassCode() { + val state = mutable.value ?: return + set(OnboardingFlow.push(state, OnboardingStep.CLASS_CODE)) + } + + // --- The class code ------------------------------------------------------------------- + + /** + * A class joined. When the join named a diary this build can sign in to, + * and no diary is signed in on this phone already, the flow offers it — + * committed, so the join screen cannot be walked back into over a class + * already joined. Otherwise the flow is done. + */ + fun onJoined() { + viewModelScope.launch { + val state = mutable.value ?: return@launch + val usable = classTargetOf(catalog(), deps.currentClass()?.diary) != null + if (usable && deps.currentDiary() == null) { + set( + OnboardingFlow.commit(state, OnboardingStep.SIGN_IN) + .let { it.copy(choices = it.choices.copy(classBound = true)) }, + ) + } else { + finish() + } + } + } + + // --- Sign-in -------------------------------------------------------------------------- + + fun submitSignIn(password: String) { + val chosen = target ?: return + signIn.submit(chosen, password, onRegistered = ::registered) + } + + fun retrySignIn() = signIn.retry(onRegistered = ::registered) + + /** «Не сейчас» on a class's diary: the class is joined, and the diary can wait for settings. */ + fun skipSignIn() { + signIn.abandon() + finish() + } + + /** + * The server holds the session: committed, so a back gesture cannot reopen + * the form and mint a second server session with a second sign-in. + */ + private fun registered() { + val state = mutable.value ?: return + set(OnboardingFlow.commit(state, OnboardingStep.IMPORT)) + } + + // --- Import --------------------------------------------------------------------------- + + fun retryImport() { + val failed = importing.state.value.failed ?: return + importing.stop() + importing.start(resumeFrom = failed.phase.takeIf { failed.resumable }) + } + + /** + * The diary ended the session during the import: back to the form, and + * pick up where the import stopped once a new session is registered. + */ + fun signInAgain() { + val state = mutable.value ?: return + val failed = importing.state.value.failed + importing.stop() + val reopened = OnboardingFlow.reopenSignIn(state) + set(reopened.copy(choices = reopened.choices.copy(resumeFrom = failed?.phase?.name))) + } + + /** + * «Выйти из дневника и начать заново»: best-effort sign-out, then the + * chooser — or, on a class's diary, the end of the flow, since the class is + * still there to go home to. + */ + fun startOver() { + viewModelScope.launch { + importing.stop() + deps.signOutDiary() + val state = mutable.value ?: return@launch + if (state.choices.classBound || deps.currentClass() != null) finish() else set(OnboardingFlow.restart()) + } + } + + fun pickStudent(id: Long) = importing.choose(id) + + /** The import finished and its full bar has been seen. */ + fun importShown() { + val state = mutable.value ?: return + if (state.current != OnboardingStep.IMPORT || importing.state.value.done == null) return + set(OnboardingFlow.commit(state, OnboardingStep.SUMMARY)) + } + + // --- The end -------------------------------------------------------------------------- + + /** + * The flow is over: what it saved goes, the hold is released, and the + * shell swaps the flow for the home the stored credential asks for. + */ + fun finish() { + finished = true + signIn.abandon() + importing.stop() + OnboardingKeys.all.forEach { saved.remove(it) } + viewModelScope.launch { deps.shellMode.release() } + } + + // --- Internals ------------------------------------------------------------------------ + + private suspend fun catalog(): RegionCatalog = + catalogState.value ?: deps.catalog().also { catalogState.value = it } + + private fun update(transform: (OnboardingState) -> OnboardingState) { + mutable.value?.let { set(transform(it)) } + } + + private fun set(state: OnboardingState) { + mutable.value = state + if (finished) return + state.toSaved().forEach { (key, value) -> saved[key] = value } + } + + /** Side effects of arriving at a step, once per arrival. */ + private suspend fun entered(step: OnboardingStep) { + when (step) { + // Reaching the chooser is what counts as having seen the + // introduction: somebody who closes the app here is not made to + // read it again. + OnboardingStep.WAY_IN -> deps.settings.update { + if (it.onboardingDone) it else it.copy(onboardingDone = true) + } + OnboardingStep.CLASS_CODE -> deps.shellMode.hold() + OnboardingStep.REGION -> if (region.state.value.rows.isEmpty()) region.type(region.state.value.query) + OnboardingStep.SCHOOL -> { + val choices = mutable.value?.choices ?: return + val key = catalog().region(choices.region) + ?.systems?.firstNotNullOfOrNull { it.netschool?.takeIf { row -> row.password }?.region } + ?: return + school.open(key, schoolQueryFromHint(choices.schoolHint, catalog().search.schoolWords)) + } + OnboardingStep.SIGN_IN -> { + deps.shellMode.hold() + resolveTarget() + } + OnboardingStep.IMPORT -> { + val choices = mutable.value?.choices + if (!importing.running && importing.state.value.done == null) { + importing.start(resumeFrom = phaseOf(choices?.resumeFrom)) + } + if (choices?.resumeFrom != null) update { it.copy(choices = it.choices.copy(resumeFrom = null)) } + } + OnboardingStep.SUMMARY -> loadSummary() + else -> Unit + } + } + + /** + * The diary the form signs in to: the one picked on the provider step, else + * the joined class's, else the one this phone was signed in to (a re-sign-in + * after the diary ended an import). + */ + private suspend fun resolveTarget() { + val choices = mutable.value?.choices ?: return + val catalog = catalog() + val cls = deps.currentClass() + val picked = catalog.region(choices.region)?.let { region -> + choices.system?.let(region.systems::getOrNull)?.let { targetFor(region, it, choices.school) } + } + val chosen = when { + choices.classBound -> classTargetOf(catalog, cls?.diary) + else -> picked + } ?: deps.storedTarget() + target = chosen + if (chosen == null) { + header.value = null + return + } + val stored = deps.storedTarget() + if (signIn.state.value.login.isBlank() && stored?.provider == chosen.provider) { + signIn.setLogin(stored.login) + } + val system = catalog.region(choices.region)?.let { region -> choices.system?.let(region.systems::getOrNull) } + header.value = SignInHeader( + provider = chosen.provider, + place = diaryPlaceOf(catalog, chosen), + schoolName = chosen.schoolName, + classBound = choices.classBound, + className = if (choices.classBound) cls?.className else null, + forgotUrl = (system?.webUrl ?: forgotUrlOf(catalog, chosen))?.takeIf { it.startsWith("https://") }, + ) + } + + private fun forgotUrlOf(catalog: RegionCatalog, target: DiaryTarget): String? = + catalog.regions.asSequence().flatMap { it.systems.asSequence() }.firstOrNull { system -> + when (target.provider) { + DiaryProviderKey.PETERSBURG -> system.platform == "petersburg" + DiaryProviderKey.NETSCHOOL -> system.netschool?.region == target.region + } + }?.webUrl + + private suspend fun loadSummary() { + val catalog = catalog() + val session = deps.currentDiary() + val cls = deps.currentClass() + val pupils = deps.cache.students.first().students + val selected = deps.cache.selectedStudentId.first() + val student = pupils.firstOrNull { it.id == selected } ?: pupils.firstOrNull() + summaryState.value = SummaryUi( + studentName = student?.fullName?.ifBlank { student.shortName }, + studentClass = student?.className, + studentSchool = student?.school ?: session?.target?.schoolName, + place = session?.target?.let { diaryPlaceOf(catalog, it) }, + login = session?.login, + petersburg = session?.target?.provider == DiaryProviderKey.PETERSBURG, + className = cls?.className, + classSchool = cls?.school, + ) + } + + companion object { + val Factory: ViewModelProvider.Factory = viewModelFactory { + initializer { + val container = Graph.container + OnboardingViewModel( + saved = createSavedStateHandle(), + deps = OnboardingDeps( + settings = container.settingsRepository, + shellMode = container.shellMode, + currentClass = { container.sessionRepository.current() }, + currentDiary = { container.diaryRepository.current() }, + storedTarget = { container.diaryRepository.target.first() }, + signOutDiary = { container.diaryRepository.signOut() }, + signIn = container.diarySignIn.forOnboarding(), + diaryImport = container.diaryImport, + cache = container.diaryCache, + catalog = { container.regionLookup.catalog() }, + regionsByName = { container.regionLookup.byName(it) }, + findRegions = { container.regionLookup.find(it) }, + schools = { region, query -> container.schoolDirectory.providerSchools(region, query) }, + ), + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt new file mode 100644 index 00000000..88b15bbf --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt @@ -0,0 +1,401 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.automirrored.rounded.Login +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import androidx.compose.material.icons.automirrored.rounded.OpenInNew +import androidx.compose.material.icons.rounded.Key +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.intl.Locale +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.LessonsBottomSheet +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.AccentTone +import com.lumenpearson.lessons.core.designsystem.theme.ScreenPadding +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.common.ServerUrlSheet +import com.lumenpearson.lessons.ui.common.openInBrowser +import com.lumenpearson.lessons.ui.diary.localized +import java.time.YearMonth +import java.time.format.DateTimeFormatter + +/** + * «Электронный дневник»: the systems the region's schools use, the recommended + * one highlighted, and «Почему?» beside it. + * + * Every answer on this page is the catalog's — which system is recommended and + * why, which can be signed into, where a handoff goes — read, never re-derived + * (K18). What the page adds is what to do about each: + * + * * a system the app's own form reaches goes on to the sign-in, behind the + * server gate: the registration needs a server, and the page asks for its + * address here, where it is first needed (DESIGN decision 7); + * * ТОР «Моя школа» and the Госуслуги-only «Сетевой город» regions are a + * handoff — the browser opens the catalog's https address, and nothing comes + * back. The app never takes a Госуслуги sign-in, never embeds a browser and + * never names an app by its package; + * * a system the app cannot read says so, and the class code is offered. + */ +@Composable +internal fun ProviderStep( + viewModel: OnboardingViewModel, + onBack: (() -> Unit)?, +) { + val page by viewModel.provider.collectAsStateWithLifecycle() + val baseUrl by viewModel.baseUrl.collectAsStateWithLifecycle() + var whyShown by rememberSaveable { mutableStateOf(false) } + var handoff by rememberSaveable { mutableStateOf(null) } + var serverFor by rememberSaveable { mutableStateOf(null) } + val current = page + + fun signIn(row: ProviderRowUi) { + if (baseUrl.isBlank()) serverFor = row.index else viewModel.signInWith(row.index) + } + + fun act(row: ProviderRowUi) = when (row.kind) { + ProviderRowKind.SIGN_IN -> signIn(row) + ProviderRowKind.NEEDS_SCHOOL -> viewModel.toSchool() + ProviderRowKind.HANDOFF, ProviderRowKind.SITE -> handoff = row.index + ProviderRowKind.UNSUPPORTED, ProviderRowKind.PAPER -> Unit + } + + serverFor?.let { index -> + ServerUrlSheet( + initialUrl = baseUrl, + description = correctedString(R.string.onboarding_sign_in_needs_server), + onDismiss = { serverFor = null }, + onConfirm = { url -> + serverFor = null + viewModel.setServer(url) + if (url.isNotBlank()) viewModel.signInWith(index) + }, + ) + } + val handoffRow = current?.rows?.firstOrNull { it.index == handoff } + if (handoffRow != null) { + HandoffSheet( + row = handoffRow, + onDismiss = { handoff = null }, + onClassCode = { + handoff = null + viewModel.toClassCode() + }, + ) + } + val why = current?.why + if (whyShown && why != null) { + WhySheet(why = why, onDismiss = { whyShown = false }) + } + + val main = current?.main + ListStepScaffold( + actions = { + OnboardingActions( + label = correctedString( + when (main?.kind) { + ProviderRowKind.SIGN_IN -> R.string.onboarding_action_sign_in + ProviderRowKind.NEEDS_SCHOOL -> R.string.onboarding_action_pick_school + ProviderRowKind.HANDOFF -> R.string.onboarding_action_gosuslugi + ProviderRowKind.SITE -> R.string.onboarding_action_open_site + else -> R.string.onboarding_action_code + }, + ), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onBack = onBack, + enabled = current != null, + onClick = { if (main != null) act(main) else viewModel.toClassCode() }, + ) + }, + ) { + item(key = "title") { + OnboardingTitle( + title = correctedString(R.string.onboarding_provider_title), + subtitle = current?.let { + correctedString(R.string.onboarding_provider_subtitle, localized(it.regionRu, it.regionEn).orEmpty()) + }, + ) + } + if (current != null) { + item(key = "systems") { + RoundedCardContainer { + current.rows.forEach { row -> + ProviderRow( + row = row, + onClick = { act(row) }.takeIf { + row.kind != ProviderRowKind.UNSUPPORTED && row.kind != ProviderRowKind.PAPER + }, + onWhy = { whyShown = true }.takeIf { row.recommended && why != null }, + ) + } + } + } + } + item(key = "code") { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.onboarding_provider_code_section)) + RoundedCardContainer { + GroupLinkItem( + title = correctedString(R.string.onboarding_provider_code_title), + subtitle = correctedString(R.string.onboarding_provider_code_text), + icon = Icons.Rounded.Key, + tone = accentTone(1), + onClick = viewModel::toClassCode, + ) + } + } + } + } +} + +@Composable +private fun ProviderRow( + row: ProviderRowUi, + onClick: (() -> Unit)?, + onWhy: (() -> Unit)?, +) { + val name = localized(row.nameRu, row.nameEn).orEmpty() + val action = correctedString( + when (row.kind) { + ProviderRowKind.SIGN_IN -> + if (row.platform == PETERSBURG_PLATFORM) { + R.string.onboarding_provider_action_account + } else { + R.string.onboarding_provider_action_sign_in + } + ProviderRowKind.NEEDS_SCHOOL -> R.string.onboarding_provider_action_needs_school + ProviderRowKind.HANDOFF -> R.string.onboarding_provider_action_gosuslugi + ProviderRowKind.SITE -> R.string.onboarding_provider_action_site + ProviderRowKind.UNSUPPORTED -> R.string.onboarding_provider_action_unsupported + ProviderRowKind.PAPER -> R.string.onboarding_provider_action_paper + }, + ) + val role = roleRes(row.role)?.let { correctedString(it) } + ChoiceRow( + title = name, + subtitle = role?.let { correctedString(R.string.onboarding_provider_line, it, action) } ?: action, + icon = when (row.kind) { + ProviderRowKind.SIGN_IN, ProviderRowKind.NEEDS_SCHOOL -> Icons.AutoMirrored.Rounded.Login + ProviderRowKind.HANDOFF, ProviderRowKind.SITE -> Icons.AutoMirrored.Rounded.OpenInNew + ProviderRowKind.UNSUPPORTED, ProviderRowKind.PAPER -> Icons.AutoMirrored.Rounded.MenuBook + }, + // Neutral for a system nothing can be done with, but still drawn and + // still readable: «почему» and the class code below say what instead. + tone = when (row.kind) { + ProviderRowKind.UNSUPPORTED, ProviderRowKind.PAPER -> AccentTone( + container = MaterialTheme.colorScheme.surfaceContainerHighest, + content = MaterialTheme.colorScheme.outline, + ) + else -> accentTone(2) + }, + selected = row.recommended, + onClick = onClick, + below = if (row.recommended) { + { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + PillChip(text = correctedString(R.string.onboarding_provider_recommended)) + if (onWhy != null) { + val described = correctedString(R.string.onboarding_provider_why_description, name) + TextButton( + onClick = onWhy, + modifier = Modifier.semantics { contentDescription = described }, + ) { + Text(correctedString(R.string.onboarding_provider_why)) + } + } + } + } + } else { + null + }, + ) +} + +@StringRes +private fun roleRes(role: String?): Int? = when (role) { + "primary" -> R.string.onboarding_provider_role_primary + "secondary" -> R.string.onboarding_provider_role_secondary + "migrating_to" -> R.string.onboarding_provider_role_moving_to + else -> null +} + +/** + * Where a handoff goes, and what to do there — before the browser takes over, + * because nothing comes back from it and the flow stays on this step. + */ +@Composable +private fun HandoffSheet( + row: ProviderRowUi, + onDismiss: () -> Unit, + onClassCode: () -> Unit, +) { + val context = LocalContext.current + var failed by rememberSaveable { mutableStateOf(false) } + val url = row.url + LessonsBottomSheet( + onDismissRequest = onDismiss, + title = correctedString(R.string.onboarding_handoff_title, localized(row.nameRu, row.nameEn).orEmpty()), + ) { + Column( + modifier = Modifier.padding(horizontal = ScreenPadding), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + text = correctedString( + if (row.gosuslugi) R.string.onboarding_handoff_gosuslugi else R.string.onboarding_handoff_site, + ), + style = MaterialTheme.typography.bodyMedium, + ) + if (failed) { + Text( + text = correctedString(R.string.onboarding_handoff_no_browser), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + ) { + TextButton(onClick = onClassCode) { + Text(correctedString(R.string.onboarding_provider_code_title)) + } + if (url != null) { + Button( + onClick = { + // ACTION_VIEW on the catalog's https address, and + // nothing else: the phone decides what opens it. + if (openInBrowser(context, url)) onDismiss() else failed = true + }, + ) { + Text(correctedString(R.string.onboarding_handoff_open)) + } + } + } + } + } +} + +/** «Почему?»: the catalog's reason for the recommendation, and how sure it is. */ +@Composable +private fun WhySheet(why: WhyUi, onDismiss: () -> Unit) { + val russian = Locale.current.language == "ru" + val month = surveyMonthText(why.surveyMonth, if (russian) java.util.Locale.forLanguageTag("ru") else java.util.Locale.ENGLISH) + val lines = whyLines( + why = why, + region = (if (russian) why.regionRu else why.regionEn).ifBlank { why.regionRu }, + system = (if (russian) why.systemRu else why.systemEn).ifBlank { why.systemRu }, + mainSystem = if (russian) why.mainSystemRu else why.mainSystemEn ?: why.mainSystemRu, + month = month, + ) + LessonsBottomSheet( + onDismissRequest = onDismiss, + title = correctedString( + R.string.onboarding_why_title, + (if (russian) why.systemRu else why.systemEn).ifBlank { why.systemRu }, + ), + ) { + Column( + modifier = Modifier + .padding(horizontal = ScreenPadding) + .padding(bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + lines.forEach { line -> + Text( + text = correctedString(line.id, *line.args.toTypedArray()), + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } +} + +/** One paragraph of «Почему?»: a string and its arguments, so the choice of paragraphs is asked on the JVM. */ +data class WhyLine(@param:StringRes val id: Int, val args: List = emptyList()) + +/** + * The paragraphs of «Почему?», in order: the reason (by the catalog's code), + * how sure the survey is, the modifiers, where the password goes when the app + * can sign in, and which survey this comes from. + * + * Every reason and modifier is a `when` with a literal `R.string` in each + * branch, so the unused-string guard sees every one of them. + */ +fun whyLines( + why: WhyUi, + region: String, + system: String, + mainSystem: String?, + month: String?, +): List = buildList { + val year = why.schoolYear ?: UnknownYear + add( + when (why.reason) { + WhyReason.PRIMARY -> WhyLine(R.string.onboarding_why_primary, listOf(region, system, year)) + WhyReason.TOR_PRIMARY -> WhyLine(R.string.onboarding_why_tor_primary, listOf(region, system)) + WhyReason.FRONT_END -> + WhyLine(R.string.onboarding_why_front_end, listOf(region, system, mainSystem ?: system)) + WhyReason.MOVING_TO -> WhyLine(R.string.onboarding_why_moving_to, listOf(region, system)) + WhyReason.UNREACHABLE -> WhyLine(R.string.onboarding_why_unreachable, listOf(region, system)) + WhyReason.UNSUPPORTED -> WhyLine(R.string.onboarding_why_unsupported, listOf(region, system)) + WhyReason.NO_DIARY -> WhyLine(R.string.onboarding_why_no_diary, listOf(region, year)) + }, + ) + when (why.confidence) { + "high" -> add(WhyLine(R.string.onboarding_why_confidence_high)) + "medium" -> add(WhyLine(R.string.onboarding_why_confidence_medium)) + "low" -> add(WhyLine(R.string.onboarding_why_confidence_low)) + } + for (modifier in WhyModifier.entries) { + if (modifier !in why.modifiers) continue + add( + when (modifier) { + WhyModifier.ESIA_ONLY -> WhyLine(R.string.onboarding_why_esia_only) + WhyModifier.UNVERIFIED -> WhyLine(R.string.onboarding_why_unverified) + }, + ) + } + why.host?.let { add(WhyLine(R.string.onboarding_why_privacy, listOf(it))) } + month?.let { add(WhyLine(R.string.onboarding_why_source, listOf(it))) } +} + +/** «сентябрь 2026» out of the catalog's `2026-09`; `null` for anything else. */ +fun surveyMonthText(month: String?, locale: java.util.Locale): String? = + month?.let { runCatching { YearMonth.parse(it) }.getOrNull() } + ?.format(DateTimeFormatter.ofPattern("LLLL yyyy", locale)) + +/** A school year the catalog did not state, which no sentence should print as «null». */ +private const val UnknownYear = "—" + +private const val PETERSBURG_PLATFORM = "petersburg" diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt new file mode 100644 index 00000000..972d407b --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt @@ -0,0 +1,159 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.catalog.DirectoryProblem +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.catalog.RegionLookupResult +import com.lumenpearson.lessons.core.data.catalog.RegionMatch +import com.lumenpearson.lessons.core.data.catalog.SchoolDirectory +import com.lumenpearson.lessons.core.data.catalog.SchoolLookup +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** Why the school-name search said nothing useful. Every one ends in «выберите регион из списка». */ +enum class DirectoryFailure { WAIT, NO_SERVER, OFFLINE, OFF } + +/** What the directory said about the name typed, if it was asked. */ +sealed interface SchoolAnswer { + /** The query reads as a place, or is too short: nothing was asked. */ + data object NotAsked : SchoolAnswer + + /** A name too common to place — «школа № 5» is in every region. */ + data object Generic : SchoolAnswer + + @Immutable + data class Found(val hits: List, val truncated: Boolean) : SchoolAnswer + + /** [minutes] is how long to wait, rounded up, for [DirectoryFailure.WAIT]. */ + @Immutable + data class Failed(val reason: DirectoryFailure, val minutes: Int? = null) : SchoolAnswer +} + +/** + * A region the directory placed schools of that name in. + * + * @property regionKey `null` when the bundled catalog cannot place it — then it + * is named by [label] and cannot be picked: no diary can be offered for a + * region the catalog does not know. + */ +@Immutable +data class SchoolHitUi( + val regionKey: String?, + val nameRu: String?, + val nameEn: String?, + val label: String?, + val schools: Int, + val examples: List, +) + +@Immutable +data class RegionSearchUi( + val query: String = "", + val rows: List = emptyList(), + val school: SchoolAnswer = SchoolAnswer.NotAsked, + val searching: Boolean = false, +) + +/** + * The region step's search, in two speeds. + * + * Every keystroke filters the bundled catalog — names, aliases, cities, codes — + * which costs no request. The server's school directory is asked only once the + * typing has paused for [debounceMillis], or on the keyboard's search key: each + * call is counted against this phone and spent from an allowance the bot's own + * class search needs too, so never one per letter. Whether a name is worth + * asking about at all is `RegionLookup`'s rule, not this one's. + */ +class RegionFinder( + private val scope: CoroutineScope, + private val catalog: suspend () -> RegionCatalog, + private val byName: suspend (String) -> List, + private val find: suspend (String) -> RegionLookupResult, + private val debounceMillis: Long = SchoolDirectory.DEBOUNCE_MILLIS, +) { + private val mutable = MutableStateFlow(RegionSearchUi()) + val state: StateFlow = mutable.asStateFlow() + + private var nameJob: Job? = null + private var schoolJob: Job? = null + + fun type(query: String) { + mutable.update { it.copy(query = query, school = SchoolAnswer.NotAsked, searching = false) } + nameJob?.cancel() + nameJob = scope.launch { + val book = catalog() + val found = runCatching { byName(query) }.getOrDefault(emptyList()) + mutable.update { it.copy(rows = found.map { match -> regionRowOf(book, match) }) } + } + schoolJob?.cancel() + if (worthAsking(query)) { + schoolJob = scope.launch { + delay(debounceMillis) + lookUp(query) + } + } + } + + /** The keyboard's search key: ask now rather than after the pause. */ + fun submit() { + val query = mutable.value.query + if (!worthAsking(query)) return + schoolJob?.cancel() + schoolJob = scope.launch { lookUp(query) } + } + + private fun worthAsking(query: String) = query.trim().length >= SchoolDirectory.MIN_QUERY_LENGTH + + private suspend fun lookUp(query: String) { + mutable.update { it.copy(searching = true) } + val book = catalog() + val result = runCatching { find(query) }.getOrNull() + mutable.update { current -> + if (current.query != query) return@update current + current.copy( + searching = false, + rows = result?.byName?.map { match -> regionRowOf(book, match) } ?: current.rows, + school = result?.bySchool?.let(::answerOf) ?: SchoolAnswer.Failed(DirectoryFailure.OFF), + ) + } + } +} + +/** The directory's answer as the step draws it. */ +fun answerOf(lookup: SchoolLookup): SchoolAnswer = when (lookup) { + SchoolLookup.NotAsked -> SchoolAnswer.NotAsked + SchoolLookup.Generic -> SchoolAnswer.Generic + is SchoolLookup.Found -> SchoolAnswer.Found( + hits = lookup.hits.hits.map { hit -> + SchoolHitUi( + regionKey = hit.region?.key, + nameRu = hit.region?.nameRu, + nameEn = hit.region?.nameEn, + label = hit.label, + schools = hit.schools, + examples = hit.examples, + ) + }, + truncated = lookup.hits.truncated, + ) + is SchoolLookup.Failed -> when (val problem = lookup.problem) { + is DirectoryProblem.Throttled -> SchoolAnswer.Failed(DirectoryFailure.WAIT, minutesOf(problem.retryAfterSeconds)) + is DirectoryProblem.Spent -> SchoolAnswer.Failed(DirectoryFailure.WAIT, minutesOf(problem.retryAfterSeconds)) + DirectoryProblem.ServerMissing -> SchoolAnswer.Failed(DirectoryFailure.NO_SERVER) + DirectoryProblem.Offline -> SchoolAnswer.Failed(DirectoryFailure.OFFLINE) + else -> SchoolAnswer.Failed(DirectoryFailure.OFF) + } +} + +/** Rounded up, never zero: «через 0 минут» is an instruction to do nothing. */ +private fun minutesOf(seconds: Long?): Int? = seconds?.let { ((it + 59) / 60).toInt().coerceAtLeast(1) } + +/** A saved phase name read back, or `null` for one this build does not have. */ +internal fun phaseOf(name: String?): DiaryImportPhase? = DiaryImportPhase.entries.firstOrNull { it.name == name } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt new file mode 100644 index 00000000..bd5ca840 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt @@ -0,0 +1,326 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.rounded.Map +import androidx.compose.material.icons.rounded.Place +import androidx.compose.material.icons.rounded.School +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.text.intl.Locale +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.catalog.MatchVia +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import com.lumenpearson.lessons.core.designsystem.component.EmptyState +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.component.SkeletonGroup +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.diary.asText +import com.lumenpearson.lessons.ui.diary.localized +import com.lumenpearson.lessons.ui.diary.offersRetry +import java.text.Collator + +/** + * «Ваш регион»: all eighty-nine, searched as they are typed. + * + * A region's name, an alias, a city or the subject code finds it in the + * bundled catalog at once, with no request. A school's name is asked of the + * server's directory once the typing pauses, and the answer is the regions a + * school of that name may be in — or, for a name every region has («школа + * № 5»), a request to pick the region instead. Whatever the directory says or + * fails to say, the list below still works: every failure ends in «выберите + * регион из списка». + */ +@Composable +internal fun RegionStep( + viewModel: OnboardingViewModel, + onBack: (() -> Unit)?, +) { + val flow by viewModel.flow.collectAsStateWithLifecycle() + val search by viewModel.region.state.collectAsStateWithLifecycle() + val selected = flow?.choices?.region + val russian = Locale.current.language == "ru" + + // A blank query lists every region, and a reader looks for a name in the + // alphabet they read it in, not in the constitution's order. A query + // keeps the search's own ranking — the best match first. + val rows = remember(search.rows, search.query, russian) { + if (search.query.isBlank()) { + val collator = Collator.getInstance(if (russian) java.util.Locale.forLanguageTag("ru") else java.util.Locale.ENGLISH) + search.rows.sortedWith(compareBy(collator) { if (russian) it.nameRu else it.nameEn }) + } else { + search.rows + } + } + + ListStepScaffold( + actions = { + OnboardingActions( + label = correctedString(R.string.onboarding_action_continue), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onBack = onBack, + enabled = selected != null, + onClick = viewModel::proceedFromRegion, + ) + }, + ) { + item(key = "title") { + OnboardingTitle( + title = correctedString(R.string.onboarding_region_title), + subtitle = correctedString(R.string.onboarding_region_subtitle), + ) + } + item(key = "search") { + SearchBox( + value = search.query, + onValueChange = viewModel.region::type, + label = correctedString(R.string.onboarding_region_search_label), + clearLabel = correctedString(R.string.onboarding_region_clear), + onSearch = viewModel.region::submit, + ) + } + + schoolAnswer(search = search, selected = selected, onPick = viewModel::pickRegion) + + if (rows.isEmpty() && search.query.isNotBlank() && !search.searching) { + item(key = "regions-empty") { + EmptyState( + title = correctedString(R.string.onboarding_region_empty_title), + description = correctedString(R.string.onboarding_region_empty_text), + icon = Icons.Rounded.Map, + ) + } + } else if (rows.isNotEmpty()) { + item(key = "regions") { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader( + title = correctedString( + if (search.query.isBlank()) R.string.onboarding_region_all else R.string.onboarding_region_found, + ), + ) + RoundedCardContainer { + rows.forEach { row -> + ChoiceRow( + title = (if (russian) row.nameRu else row.nameEn).ifBlank { row.nameRu }, + subtitle = listOfNotNull(matchedLine(row), offerLine(row.offer)).joinToString("\n"), + icon = Icons.Rounded.Map, + tone = accentTone(0), + selected = row.key == selected, + onClick = { viewModel.pickRegion(row.key) }, + ) + } + } + } + } + } + } +} + +/** The directory's part of the list: where a school of that name may be, or why it cannot say. */ +private fun androidx.compose.foundation.lazy.LazyListScope.schoolAnswer( + search: RegionSearchUi, + selected: String?, + onPick: (key: String, hint: String?) -> Unit, +) { + if (search.searching) { + item(key = "school-searching") { NoteCard(correctedString(R.string.onboarding_region_school_searching)) } + return + } + when (val answer = search.school) { + SchoolAnswer.NotAsked -> Unit + SchoolAnswer.Generic -> item(key = "school-generic") { + NoteCard(correctedString(R.string.onboarding_region_school_generic)) + } + is SchoolAnswer.Failed -> item(key = "school-failed") { + NoteCard( + when (answer.reason) { + DirectoryFailure.WAIT -> answer.minutes + ?.let { pluralStringResource(R.plurals.onboarding_region_school_wait, it, it) } + ?: correctedString(R.string.onboarding_region_school_busy) + DirectoryFailure.NO_SERVER -> correctedString(R.string.onboarding_region_school_no_server) + DirectoryFailure.OFFLINE -> correctedString(R.string.onboarding_region_school_offline) + DirectoryFailure.OFF -> correctedString(R.string.onboarding_region_school_off) + }, + ) + } + is SchoolAnswer.Found -> { + // A region the catalog cannot place cannot be picked — there is no + // diary to offer for it — so it is left out rather than drawn dead. + val placed = answer.hits.filter { it.regionKey != null } + if (placed.isEmpty()) { + item(key = "school-empty") { NoteCard(correctedString(R.string.onboarding_region_school_empty)) } + } else { + item(key = "school-hits") { + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.onboarding_region_school_section, search.query.trim())) + RoundedCardContainer { + placed.forEach { hit -> + val key = hit.regionKey ?: return@forEach + ChoiceRow( + title = localized(hit.nameRu, hit.nameEn) ?: hit.label.orEmpty(), + subtitle = correctedString( + R.string.onboarding_region_school_group, + pluralStringResource(R.plurals.onboarding_region_school_count, hit.schools, hit.schools), + hit.examples.take(ExamplesShown).joinToString("; "), + ), + icon = Icons.Rounded.School, + tone = accentTone(3), + selected = key == selected, + onClick = { onPick(key, search.query.trim()) }, + ) + } + } + } + } + if (answer.truncated) { + item(key = "school-truncated") { + NoteCard(correctedString(R.string.onboarding_region_school_truncated)) + } + } + } + } + } +} + +/** Why a region is in the results when its name is not what matched. */ +@Composable +private fun matchedLine(row: RegionRowUi): String? { + val matched = row.matched ?: return null + return when (row.via) { + MatchVia.CITY -> correctedString(R.string.onboarding_region_by_city, matched) + MatchVia.ALIAS -> correctedString(R.string.onboarding_region_by_alias, matched) + MatchVia.CODE -> correctedString(R.string.onboarding_region_by_code, matched) + else -> null + } +} + +/** What can be done in a region, in a few words. */ +@Composable +private fun offerLine(offer: RegionOffer): String { + val system = localized(offer.systemRu, offer.systemEn).orEmpty() + return when (offer.kind) { + OfferKind.SIGN_IN -> correctedString(R.string.onboarding_region_sign_in, system) + OfferKind.GOSUSLUGI -> correctedString(R.string.onboarding_region_gosuslugi, system) + OfferKind.SITE -> correctedString(R.string.onboarding_region_site, system) + OfferKind.UNSUPPORTED -> correctedString(R.string.onboarding_region_unsupported, system) + OfferKind.PAPER -> correctedString(R.string.onboarding_region_paper) + } +} + +/** How many of a region's matching school names are listed under it. */ +private const val ExamplesShown = 3 + +/** + * «Ваша школа»: the region's own «Сетевой город» list, searched on the + * region's server straight from the phone — the server the password goes to + * next, so a failure here is the honest early warning. Shown only where the + * signable diary needs a school (`regionPlanOf`). + */ +@Composable +internal fun SchoolStep( + viewModel: OnboardingViewModel, + onBack: (() -> Unit)?, +) { + val flow by viewModel.flow.collectAsStateWithLifecycle() + val search by viewModel.school.state.collectAsStateWithLifecycle() + val page by viewModel.provider.collectAsStateWithLifecycle() + val picked = flow?.choices?.school + val signable = page?.rows?.firstOrNull { + it.kind == ProviderRowKind.SIGN_IN || it.kind == ProviderRowKind.NEEDS_SCHOOL + } + + ListStepScaffold( + actions = { + OnboardingActions( + label = correctedString(R.string.onboarding_action_continue), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onBack = onBack, + enabled = picked != null, + onClick = viewModel::proceedFromSchool, + ) + }, + ) { + item(key = "title") { + OnboardingTitle( + title = correctedString(R.string.onboarding_school_title), + subtitle = page?.let { current -> + correctedString( + R.string.onboarding_school_subtitle, + localized(current.regionRu, current.regionEn).orEmpty(), + localized(signable?.nameRu, signable?.nameEn).orEmpty(), + ) + }, + ) + } + item(key = "search") { + SearchBox( + value = search.query, + onValueChange = viewModel.school::type, + label = correctedString(R.string.onboarding_school_search_label), + clearLabel = correctedString(R.string.onboarding_region_clear), + onSearch = viewModel.school::retry, + ) + } + when { + search.searching -> item(key = "loading") { SkeletonGroup(rows = 3) } + + search.problem != null -> item(key = "problem") { + val problem = search.problem ?: return@item + EmptyState( + title = correctedString(R.string.diary_failure_title), + description = problem.asText(), + actionLabel = correctedString(R.string.onboarding_action_retry).takeIf { problem.offersRetry }, + onActionClick = viewModel.school::retry.takeIf { problem.offersRetry }, + ) + } + + search.query.trim().length < DiarySchoolSearch.MIN_QUERY_LENGTH -> item(key = "hint") { + NoteCard( + pluralStringResource( + R.plurals.onboarding_school_min_chars, + DiarySchoolSearch.MIN_QUERY_LENGTH, + DiarySchoolSearch.MIN_QUERY_LENGTH, + ), + ) + } + + search.searched && search.rows.isEmpty() -> item(key = "empty") { + NoteCard(correctedString(R.string.onboarding_school_empty)) + } + + else -> item(key = "schools") { + RoundedCardContainer { + search.rows.forEach { row -> + ChoiceRow( + title = row.name, + subtitle = row.address, + icon = Icons.Rounded.Place, + tone = accentTone(1), + selected = picked?.id == row.id, + onClick = { viewModel.pickSchool(row) }, + ) + } + } + } + } + item(key = "missing") { + TextButton(onClick = viewModel::skipSchool, modifier = Modifier.fillMaxWidth()) { + Text( + text = correctedString(R.string.onboarding_school_missing), + style = MaterialTheme.typography.labelLarge, + ) + } + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt new file mode 100644 index 00000000..bc502401 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt @@ -0,0 +1,95 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import com.lumenpearson.lessons.ui.diary.DiarySchoolRow +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * @property problem why the region's server did not answer — the same server + * the password goes to next, so `DiaryProblemText` words it (K20). + */ +@Immutable +data class SchoolSearchUi( + val regionKey: String? = null, + val query: String = "", + val rows: List = emptyList(), + val searching: Boolean = false, + val searched: Boolean = false, + val problem: DiarySignInProblem? = null, +) + +/** + * The school step's search, straight from the phone to the region's own + * «Сетевой город» server (K27). That server is where the password goes next, + * so a failure here is the honest early warning that the sign-in could not + * reach it either. Debounced and floored by the search's own constants. + */ +class SchoolFinder( + private val scope: CoroutineScope, + private val schools: suspend (regionKey: String, query: String) -> Result>, + private val debounceMillis: Long = DiarySchoolSearch.DEBOUNCE_MILLIS, +) { + private val mutable = MutableStateFlow(SchoolSearchUi()) + val state: StateFlow = mutable.asStateFlow() + + private var job: Job? = null + + /** A region picked: start over, with the query the region step carried, asked at once. */ + fun open(regionKey: String, prefill: String) { + if (mutable.value.regionKey == regionKey && mutable.value.query.isNotEmpty()) return + job?.cancel() + mutable.value = SchoolSearchUi(regionKey = regionKey, query = prefill) + search(prefill, debounce = false) + } + + fun type(query: String) { + mutable.update { it.copy(query = query) } + search(query, debounce = true) + } + + fun retry() = search(mutable.value.query, debounce = false) + + private fun search(query: String, debounce: Boolean) { + val region = mutable.value.regionKey ?: return + job?.cancel() + if (query.trim().length < DiarySchoolSearch.MIN_QUERY_LENGTH) { + mutable.update { it.copy(rows = emptyList(), searching = false, searched = false, problem = null) } + return + } + job = scope.launch { + if (debounce) delay(debounceMillis) + mutable.update { it.copy(searching = true, problem = null) } + schools(region, query).fold( + onSuccess = { found -> + mutable.update { + it.copy( + searching = false, + searched = true, + rows = found.map { school -> DiarySchoolRow(school.id, school.name, school.address) }, + ) + } + }, + onFailure = { failure -> + mutable.update { + it.copy( + searching = false, + searched = true, + rows = emptyList(), + problem = failure as? DiarySignInProblem ?: DiarySignInProblem.of(failure), + ) + } + }, + ) + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt new file mode 100644 index 00000000..f816a923 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt @@ -0,0 +1,262 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.automirrored.rounded.OpenInNew +import androidx.compose.material.icons.rounded.Dns +import androidx.compose.material.icons.rounded.Key +import androidx.compose.material.icons.rounded.Refresh +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.LessonsDialog +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.Text +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.navigation.isInsecure +import com.lumenpearson.lessons.ui.common.ServerUrlSheet +import com.lumenpearson.lessons.ui.common.openInBrowser +import com.lumenpearson.lessons.ui.diary.DiaryCredentialFields +import com.lumenpearson.lessons.ui.diary.asText +import com.lumenpearson.lessons.ui.diary.regionName +import com.lumenpearson.lessons.ui.diary.systemName + +/** + * The family's own sign-in: the app's clearly labelled form, and a card above + * it saying where the password goes — the diary's host, from the same + * allow-list the sign-in is held to — before a single character is typed. + * + * The password goes from [DiaryCredentialFields] straight to + * [OnboardingViewModel.submitSignIn] and on to the diary; our server is handed + * the session the diary issues, never the password. A failure is a pop-up in + * `DiaryProblemText`'s words (the keyboard hides a line under the button), and + * what can be done about it stays on the page after the pop-up is gone: + * re-sending the held session without the password, setting the server, the + * class code, or the Госуслуги page in the browser. + */ +@Composable +internal fun SignInPage( + viewModel: OnboardingViewModel, + onBack: (() -> Unit)?, +) { + val header by viewModel.signInHeader.collectAsStateWithLifecycle() + val ui by viewModel.signIn.state.collectAsStateWithLifecycle() + val baseUrl by viewModel.baseUrl.collectAsStateWithLifecycle() + val context = LocalContext.current + var editingServer by rememberSaveable { mutableStateOf(false) } + val current = header + val problem = ui.problem + + if (editingServer) { + ServerUrlSheet( + initialUrl = baseUrl, + description = correctedString(R.string.onboarding_sign_in_needs_server), + onDismiss = { editingServer = false }, + onConfirm = { url -> + viewModel.setServer(url) + editingServer = false + }, + ) + } + if (ui.dialog && problem != null) { + LessonsDialog( + title = correctedString(R.string.diary_sign_in_failed_title), + message = problem.asText(), + confirmLabel = correctedString(R.string.diary_dialog_dismiss), + onDismiss = viewModel.signIn::dismissDialog, + ) + } + + StepScaffold( + actions = { + when { + current?.classBound == true -> OnboardingActions( + label = correctedString(R.string.onboarding_sign_in_skip), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onBack = onBack, + enabled = !ui.busy, + onClick = viewModel::skipSignIn, + ) + onBack != null -> OnboardingBackRow(onBack = onBack) + } + }, + ) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(GroupSpacing), + ) { + Spacer(Modifier.height(8.dp)) + if (current == null) { + NoteCard(correctedString(R.string.onboarding_sign_in_no_target)) + return@Column + } + val system = current.place.systemName().orEmpty() + OnboardingTitle( + title = if (current.classBound) { + correctedString(R.string.onboarding_sign_in_class_title) + } else { + correctedString(R.string.onboarding_sign_in_title, system) + }, + subtitle = when { + current.classBound -> correctedString( + R.string.onboarding_sign_in_class_subtitle, + current.className.orEmpty(), + system, + ) + current.provider == DiaryProviderKey.PETERSBURG -> + correctedString(R.string.onboarding_sign_in_account) + else -> correctedString( + R.string.onboarding_sign_in_where, + current.place.regionName().orEmpty(), + current.schoolName.orEmpty(), + ) + }, + ) + + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.onboarding_sign_in_privacy_title)) + NoteCard( + listOfNotNull( + current.place.host?.let { correctedString(R.string.diary_password_destination, it) }, + correctedString(R.string.diary_password_notice), + ).joinToString("\n\n"), + ) + } + + if (isInsecure(baseUrl)) NoteCard(correctedString(R.string.diary_insecure_server)) + + val petersburg = current.provider == DiaryProviderKey.PETERSBURG + DiaryCredentialFields( + login = ui.login, + onLoginChange = viewModel.signIn::setLogin, + onSubmit = { _, password -> viewModel.submitSignIn(password) }, + busy = ui.busy, + failed = problem != null, + onEdited = viewModel.signIn::edited, + loginLabel = correctedString( + if (petersburg) R.string.onboarding_sign_in_email else R.string.diary_login_label, + ), + loginKeyboard = if (petersburg) KeyboardType.Email else KeyboardType.Text, + ) + + ui.stage?.let { stage -> + Text( + text = when (stage) { + SignInStage.CHECKING -> correctedString(R.string.onboarding_sign_in_stage_checking) + SignInStage.UPSTREAM -> correctedString(R.string.onboarding_sign_in_stage_upstream, system) + SignInStage.REGISTER -> correctedString(R.string.onboarding_sign_in_stage_register) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + if (problem != null && !ui.busy) { + ProblemActions( + problem = problem, + sessionHeld = ui.sessionHeld, + classBound = current.classBound, + onRetry = viewModel::retrySignIn, + onServer = { editingServer = true }, + onClassCode = viewModel::toClassCode, + onOpen = { url -> openInBrowser(context, url) }, + ) + } + + current.forgotUrl?.let { url -> + TextButton(onClick = { openInBrowser(context, url) }, modifier = Modifier.fillMaxWidth()) { + Text(correctedString(R.string.onboarding_sign_in_forgot)) + } + } + + // The server that will hold the session, named where the session is + // about to be sent to it. + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.join_server_section)) + RoundedCardContainer { + GroupLinkItem( + title = correctedString(R.string.settings_server_url), + subtitle = baseUrl.takeIf { it.isNotBlank() } + ?: correctedString(R.string.onboarding_way_server_unset), + icon = Icons.Rounded.Dns, + tone = accentTone(0), + onClick = { editingServer = true }, + ) + } + } + Spacer(Modifier.height(8.dp)) + } + } +} + +/** What can be done about [problem], as buttons that outlive its pop-up. */ +@Composable +private fun ProblemActions( + problem: DiarySignInProblem, + sessionHeld: Boolean, + classBound: Boolean, + onRetry: () -> Unit, + onServer: () -> Unit, + onClassCode: () -> Unit, + onOpen: (String) -> Unit, +) { + val handoff = (problem as? DiarySignInProblem.GosuslugiOnly)?.handoffUrl?.takeIf { it.startsWith("https://") } + val retry = sessionHeld && problem.retryKeepsSession + val server = problem.action == DiarySignInProblem.Action.SET_SERVER + // A class code is the way round a diary that refuses our server — unless a + // class is what brought the family here. + val code = problem is DiarySignInProblem.ServerRefusedSession && !classBound + if (!retry && !server && !code && handoff == null) return + RoundedCardContainer { + if (retry) { + GroupActionItem( + label = correctedString(R.string.onboarding_sign_in_retry), + icon = Icons.Rounded.Refresh, + onClick = onRetry, + ) + } + if (server) { + GroupActionItem( + label = correctedString(R.string.onboarding_sign_in_set_server), + icon = Icons.Rounded.Dns, + onClick = onServer, + ) + } + if (handoff != null) { + GroupActionItem( + label = correctedString(R.string.onboarding_handoff_open), + icon = Icons.AutoMirrored.Rounded.OpenInNew, + onClick = { onOpen(handoff) }, + ) + } + if (code) { + GroupActionItem( + label = correctedString(R.string.onboarding_provider_code_title), + icon = Icons.Rounded.Key, + onClick = onClassCode, + ) + } + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt new file mode 100644 index 00000000..eb472e02 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt @@ -0,0 +1,186 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.runtime.Immutable +import com.lumenpearson.lessons.core.data.repository.DiaryRegistration +import com.lumenpearson.lessons.core.data.repository.DiarySignIn +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.upstream.UpstreamSession +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch + +/** + * The diary's session between the phone's sign-in and our server's answer, as + * the sign-in step holds it: opaque, so that nothing on this side can read a + * token out of it — and so that a test can hand over its own, which the real + * [UpstreamSession]'s internal constructors would not allow. + */ +interface HeldUpstream { + val target: DiaryTarget +} + +/** + * [DiarySignIn]'s four steps as the onboarding uses them, one at a time: the + * step has to hold the session between the diary's answer and ours, so that a + * registration that failed for want of a network is retried without asking for + * the password again. + */ +interface OnboardingSignIn { + suspend fun preflight(target: DiaryTarget): Result + suspend fun open(target: DiaryTarget, password: String): Result + suspend fun register(held: HeldUpstream): Result + suspend fun discard(held: HeldUpstream) +} + +/** The real sign-in, its session wrapped so nothing but this adapter unwraps it. */ +fun DiarySignIn.forOnboarding(): OnboardingSignIn = object : OnboardingSignIn { + + private inner class Held(val session: UpstreamSession) : HeldUpstream { + override val target: DiaryTarget get() = session.target + override fun toString(): String = "HeldUpstream()" + } + + override suspend fun preflight(target: DiaryTarget) = this@forOnboarding.preflight(target) + + override suspend fun open(target: DiaryTarget, password: String): Result = + openUpstream(target, password).map { Held(it) } + + override suspend fun register(held: HeldUpstream): Result = + this@forOnboarding.register((held as Held).session) + + override suspend fun discard(held: HeldUpstream) = this@forOnboarding.discard((held as Held).session) +} + +/** What the sign-in is doing, for the line under the form. */ +enum class SignInStage { + /** Asking our server whether it can keep a session for this diary. */ + CHECKING, + + /** The phone signing in to the diary itself, with the password. */ + UPSTREAM, + + /** The diary's session going to our server. */ + REGISTER, +} + +/** + * @property login not a secret, but not saved either: it lives as long as this + * step's holder, which is the view model's memory (the saved-state test + * holds that no login reaches the bundle). + * @property problem the last failure, until the form is touched again. + * @property dialog the failure is still to be read in its pop-up. + * @property sessionHeld the diary let the phone in and our server has not + * answered: «Повторить» re-sends the session without the password. + */ +@Immutable +data class SignInUi( + val login: String = "", + val stage: SignInStage? = null, + val problem: DiarySignInProblem? = null, + val dialog: Boolean = false, + val sessionHeld: Boolean = false, +) { + val busy: Boolean get() = stage != null +} + +/** + * The sign-in step's state holder. + * + * The diary's session lives in [held], a plain field of this object, and + * nowhere else: never in `SavedStateHandle` (the bundle is written to disk), + * DataStore, Room or a log. It is dropped on the server's success, on a + * failure that already discarded it, and on [abandon] — leaving the step — + * which also says goodbye to it upstream. The password is never a field at + * all: it arrives as [submit]'s argument and leaves as [OnboardingSignIn.open]'s. + */ +class SignInStep( + private val scope: CoroutineScope, + private val signIn: OnboardingSignIn, +) { + private val mutable = MutableStateFlow(SignInUi()) + val state: StateFlow = mutable.asStateFlow() + + private var held: HeldUpstream? = null + private var job: Job? = null + + fun setLogin(login: String) = mutable.update { it.copy(login = login) } + + /** Any keystroke: the red fields go back to normal. */ + fun edited() = mutable.update { it.copy(problem = null, dialog = false) } + + fun dismissDialog() = mutable.update { it.copy(dialog = false) } + + /** + * Preflight, the diary, then our server; [onRegistered] once the server + * has answered with its bearer. A session already held — a registration + * that failed — is discarded first: a new password means a new session. + */ + fun submit(target: DiaryTarget, password: String, onRegistered: () -> Unit) { + if (job?.isActive == true) return + val stale = held + held = null + job = scope.launch { + stale?.let { signIn.discard(it) } + val withLogin = target.copy(login = mutable.value.login) + mutable.update { it.copy(stage = SignInStage.CHECKING, problem = null, dialog = false, sessionHeld = false) } + signIn.preflight(withLogin).onFailure { fail(it); return@launch } + mutable.update { it.copy(stage = SignInStage.UPSTREAM) } + val session = signIn.open(withLogin, password).getOrElse { fail(it); return@launch } + held = session + registerHeld(onRegistered) + } + } + + /** The server again, with the session still in hand; no password. */ + fun retry(onRegistered: () -> Unit) { + if (job?.isActive == true || held == null) return + job = scope.launch { registerHeld(onRegistered) } + } + + /** + * Leaving the step: whatever is in flight stops, and a session the server + * never took is ended with the diary rather than left to idle there. + */ + fun abandon() { + job?.cancel() + job = null + val stale = held + held = null + mutable.update { SignInUi(login = it.login) } + if (stale != null) scope.launch { signIn.discard(stale) } + } + + private suspend fun registerHeld(onRegistered: () -> Unit) { + val session = held ?: return + mutable.update { it.copy(stage = SignInStage.REGISTER, problem = null, dialog = false) } + signIn.register(session).fold( + onSuccess = { + held = null + mutable.update { it.copy(stage = null, problem = null, dialog = false, sessionHeld = false) } + onRegistered() + }, + onFailure = { failure -> + val problem = problemOf(failure) + // `register` has already discarded a session it will not see + // again; holding it here would offer a retry that cannot work. + if (!problem.retryKeepsSession) held = null + fail(problem) + }, + ) + } + + private fun fail(failure: Throwable) { + val problem = problemOf(failure) + mutable.update { + it.copy(stage = null, problem = problem, dialog = true, sessionHeld = held != null) + } + } + + private fun problemOf(failure: Throwable): DiarySignInProblem = + failure as? DiarySignInProblem ?: DiarySignInProblem.of(failure) +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt new file mode 100644 index 00000000..f721f341 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt @@ -0,0 +1,176 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.MenuBook +import androidx.compose.material.icons.rounded.BugReport +import androidx.compose.material.icons.rounded.Check +import androidx.compose.material.icons.rounded.Contrast +import androidx.compose.material.icons.rounded.Groups +import androidx.compose.material.icons.rounded.Language +import androidx.compose.material.icons.rounded.Notifications +import androidx.compose.material.icons.rounded.Person +import androidx.compose.material.icons.rounded.Timer +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.DiarySessionIdleDays +import com.lumenpearson.lessons.core.designsystem.component.GroupItem +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.diary.regionName +import com.lumenpearson.lessons.ui.diary.systemName +import com.lumenpearson.lessons.ui.settings.SettingsUiState +import com.lumenpearson.lessons.ui.settings.labelRes +import com.lumenpearson.lessons.ui.settings.rememberPermissionPrompts + +/** + * «Всё готово»: the pupil, the diary and what keeping it costs, the class if + * there is one, and the settings the introduction set — then the app. + * + * Read-only. Everything on it is changed in settings, and saying so is the + * page's job; a switch here would be a second copy of a settings row. + * + * The notifications row is left out without a class (K23): in the diary-only + * home nothing sends a notification, and a row saying they are allowed would + * promise reminders that never come. The page says instead what the + * diary-only home does not have, and that the widget does not keep the + * session alive (G8) — a family that only looks at the widget loses the + * sign-in after [DiarySessionIdleDays] days, and should hear it now. + */ +@Composable +internal fun SummaryPage( + settings: SettingsUiState, + viewModel: OnboardingViewModel, +) { + val summary by viewModel.summary.collectAsStateWithLifecycle() + // The floor is here, so back has nowhere to go but out of the flow — and + // out of the flow is the home, which is what the button does too. + BackHandler { viewModel.finish() } + + StepScaffold( + actions = { + OnboardingActions( + label = correctedString(R.string.onboarding_action_open), + icon = Icons.Rounded.Check, + onClick = viewModel::finish, + ) + }, + ) { + Spacer(Modifier.height(24.dp)) + OnboardingReveal { + OnboardingTitle( + title = correctedString(R.string.onboarding_summary_title), + subtitle = correctedString(R.string.onboarding_summary_subtitle), + ) + } + Spacer(Modifier.height(24.dp)) + + val current = summary + OnboardingReveal(delayMillis = RevealStagger) { + if (current != null) { + current.studentName?.let { name -> + AccentSection(title = correctedString(R.string.onboarding_summary_student)) { + GroupItem( + title = name, + subtitle = listOfNotNull(current.studentClass, current.studentSchool) + .filter { it.isNotBlank() } + .joinToString(", ") + .ifBlank { null }, + icon = Icons.Rounded.Person, + tone = accentTone(3), + ) + } + Spacer(Modifier.height(GroupSpacing)) + } + + AccentSection(title = correctedString(R.string.onboarding_summary_diary)) { + GroupItem( + title = listOfNotNull(current.place?.systemName(), current.place?.regionName()) + .joinToString(" · "), + subtitle = current.login?.let { correctedString(R.string.diary_signed_in_as, it) }, + icon = Icons.AutoMirrored.Rounded.MenuBook, + tone = accentTone(2), + ) + GroupItem( + title = pluralStringResource( + R.plurals.onboarding_summary_keepalive, + DiarySessionIdleDays.toInt(), + DiarySessionIdleDays.toInt(), + ), + subtitle = correctedString(R.string.onboarding_summary_petersburg_note) + .takeIf { current.petersburg }, + icon = Icons.Rounded.Timer, + tone = accentTone(4), + ) + } + Spacer(Modifier.height(GroupSpacing)) + + AccentSection(title = correctedString(R.string.onboarding_summary_class)) { + if (current.inClass) { + GroupItem( + title = current.className.orEmpty(), + subtitle = current.classSchool, + icon = Icons.Rounded.Groups, + tone = accentTone(1), + ) + } else { + GroupItem( + title = correctedString(R.string.onboarding_summary_no_class_title), + subtitle = correctedString(R.string.onboarding_summary_no_class_text), + icon = Icons.Rounded.Groups, + tone = accentTone(1), + ) + } + } + Spacer(Modifier.height(GroupSpacing)) + } + + AccentSection(title = correctedString(R.string.onboarding_summary_settings)) { + GroupItem( + title = correctedString(R.string.settings_theme_mode), + subtitle = correctedString(settings.settings.themeMode.labelRes), + icon = Icons.Rounded.Contrast, + tone = accentTone(4), + ) + GroupItem( + title = correctedString(R.string.settings_language), + subtitle = correctedString(settings.settings.language.labelRes), + icon = Icons.Rounded.Language, + tone = accentTone(1), + ) + if (current?.inClass == true) { + val missing = rememberPermissionPrompts().missing + GroupItem( + title = correctedString(R.string.onboarding_summary_notifications), + subtitle = correctedString( + if (missing == 0) { + R.string.onboarding_summary_notifications_on + } else { + R.string.onboarding_summary_notifications_off + }, + ), + icon = Icons.Rounded.Notifications, + tone = accentTone(5), + ) + } + GroupItem( + title = correctedString(R.string.onboarding_ack_reports), + subtitle = correctedString( + if (settings.settings.debugMode) R.string.onboarding_reports_on else R.string.onboarding_reports_off, + ), + icon = Icons.Rounded.BugReport, + tone = accentTone(2), + ) + } + } + Spacer(Modifier.height(24.dp)) + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/WayInStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/WayInStep.kt new file mode 100644 index 00000000..fc6be266 --- /dev/null +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/WayInStep.kt @@ -0,0 +1,144 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.rounded.Dns +import androidx.compose.material.icons.rounded.Key +import androidx.compose.material.icons.rounded.School +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.designsystem.component.GroupLinkItem +import com.lumenpearson.lessons.core.designsystem.component.PillChip +import com.lumenpearson.lessons.core.designsystem.component.RoundedCardContainer +import com.lumenpearson.lessons.core.designsystem.component.SectionHeader +import com.lumenpearson.lessons.core.designsystem.text.correctedString +import com.lumenpearson.lessons.core.designsystem.theme.GroupSpacing +import com.lumenpearson.lessons.core.designsystem.theme.accentTone +import com.lumenpearson.lessons.ui.common.ServerUrlSheet + +/** + * The chooser: by class code, as the app always worked, or on one's own — the + * region, the school and the family's own diary. + * + * Nothing on it can fail, and nothing on it needs a server. The address is + * shown, and settable, because both ways end up needing one; but it is asked + * for where it is first needed rather than here (DESIGN decision 7), because a + * family whose diary is a Госуслуги handoff needs none at all, and there is no + * address the APK could suggest (#154). + */ +@Composable +internal fun WayInStep( + viewModel: OnboardingViewModel, + onBack: (() -> Unit)?, +) { + val flow by viewModel.flow.collectAsStateWithLifecycle() + val baseUrl by viewModel.baseUrl.collectAsStateWithLifecycle() + val chosen = flow?.choices?.wayIn + var editingServer by rememberSaveable { mutableStateOf(false) } + + if (editingServer) { + ServerUrlSheet( + initialUrl = baseUrl, + onDismiss = { editingServer = false }, + onConfirm = { url -> + viewModel.setServer(url) + editingServer = false + }, + ) + } + + StepScaffold( + actions = { + OnboardingActions( + label = correctedString( + when (chosen) { + WayIn.CLASS_CODE -> R.string.onboarding_action_code + WayIn.FIND_SCHOOL -> R.string.onboarding_action_find + null -> R.string.onboarding_action_continue + }, + ), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onBack = onBack, + enabled = chosen != null, + onClick = viewModel::proceedFromWayIn, + ) + }, + ) { + Spacer(Modifier.height(24.dp)) + OnboardingReveal { + OnboardingTitle( + title = correctedString(R.string.onboarding_way_title), + subtitle = correctedString(R.string.onboarding_way_subtitle), + ) + } + Spacer(Modifier.height(24.dp)) + + OnboardingReveal(delayMillis = RevealStagger) { + Column(verticalArrangement = Arrangement.spacedBy(GroupSpacing)) { + RoundedCardContainer { + WayRow( + way = WayIn.CLASS_CODE, + chosen = chosen, + onChoose = viewModel::chooseWay, + ) + } + RoundedCardContainer { + WayRow( + way = WayIn.FIND_SCHOOL, + chosen = chosen, + onChoose = viewModel::chooseWay, + ) + } + Column(modifier = Modifier.fillMaxWidth()) { + SectionHeader(title = correctedString(R.string.join_server_section)) + RoundedCardContainer { + GroupLinkItem( + title = correctedString(R.string.settings_server_url), + subtitle = baseUrl.takeIf { it.isNotBlank() } + ?: correctedString(R.string.onboarding_way_server_unset), + icon = Icons.Rounded.Dns, + tone = accentTone(0), + onClick = { editingServer = true }, + ) + } + } + } + } + Spacer(Modifier.height(24.dp)) + } +} + +@Composable +private fun WayRow( + way: WayIn, + chosen: WayIn?, + onChoose: (WayIn) -> Unit, +) { + val code = way == WayIn.CLASS_CODE + ChoiceRow( + title = correctedString(if (code) R.string.onboarding_way_code_title else R.string.onboarding_way_school_title), + subtitle = correctedString(if (code) R.string.onboarding_way_code_text else R.string.onboarding_way_school_text), + icon = if (code) Icons.Rounded.Key else Icons.Rounded.School, + tone = accentTone(if (code) 1 else 3), + selected = chosen == way, + onClick = { onChoose(way) }, + below = { + Spacer(Modifier.height(4.dp)) + PillChip( + text = correctedString(if (code) R.string.onboarding_way_code_badge else R.string.onboarding_way_school_badge), + ) + }, + ) +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt index 284f35e0..84e99a16 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsScreen.kt @@ -77,6 +77,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.BuildConfig import com.lumenpearson.lessons.R import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile import com.lumenpearson.lessons.core.designsystem.component.GroupActionItem import com.lumenpearson.lessons.core.designsystem.component.GroupItem @@ -112,7 +113,10 @@ import com.lumenpearson.lessons.core.model.WeekStart import com.lumenpearson.lessons.navigation.labelRes import com.lumenpearson.lessons.ui.debug.DebugRow import com.lumenpearson.lessons.ui.common.ServerUrlSheet +import com.lumenpearson.lessons.ui.diary.DiaryAccountPage import com.lumenpearson.lessons.ui.diary.DiaryScreen +import com.lumenpearson.lessons.ui.diary.DiaryViewModel +import com.lumenpearson.lessons.navigation.isInsecure import com.lumenpearson.lessons.ui.common.SyncIntervalOptionsMinutes import com.lumenpearson.lessons.ui.common.asText import com.lumenpearson.lessons.ui.common.syncIntervalLabel @@ -133,6 +137,7 @@ import com.lumenpearson.lessons.ui.translate.translationRows * The enum is the single definition of the split. The root screen lists it, the * section screen renders one of it, and the shell titles the toolbar from it, so * a new section is one entry here and one branch in [SettingsSectionScreen]. + * Which of them the root offers is [listedOn], one rule for both homes. * * @param tone which accent slot the row's tile takes on the root page. */ @@ -182,15 +187,18 @@ enum class SettingsSection( 1, ), /** - * The Petersburg diary: a second account, in a service this app does not - * own, that most installs will never have. + * The diary: a second account, in a service this app does not own, that + * most installs in a class will never have — and, on a phone in no class, + * the only account there is. * - * It is a section rather than a fourth tab because a tab would show a - * sign-in wall in the bottom bar of everybody without such an account, for - * good — the toolbar never hides a destination. Next to «Класс» because - * the two rows are the same kind of thing: which account this phone is - * signed in to. The page it opens is not a list of preferences, which is - * why [SettingsSectionScreen] hands it over whole. + * In a class it is a section rather than a fourth tab because a tab would + * show a sign-in wall in the bottom bar of everybody without such an + * account, for good — the toolbar never hides a destination. Next to + * «Класс» because the two rows are the same kind of thing: which account + * this phone is signed in to. The page it opens is not a list of + * preferences, which is why [SettingsSectionScreen] hands it over whole: the + * diary itself in a class, the account page on the diary home, where the + * diary already is the home. */ DIARY( R.string.diary_title, @@ -214,19 +222,16 @@ enum class SettingsSection( /** * The pages only an administrator or the owner of the class has. * - * Kept off the root list by [listedOnRoot] and put back by the root page - * itself once the server has said who this phone belongs to — the same - * shape as [PERMISSIONS], for a different reason: that one appears when - * something is wrong, this one when somebody is allowed. + * Listed by [listedOn] only once the server has said who this phone belongs + * to — the same shape as [PERMISSIONS], for a different reason: that one + * appears when something is wrong, this one when somebody is allowed. */ ADMIN( R.string.settings_admin, R.string.settings_admin_summary, Icons.Rounded.AdminPanelSettings, 1, - ) { - override val listedOnRoot: Boolean = false - }, + ), /** * Reached from the notifications page, never from the root list. @@ -234,20 +239,36 @@ enum class SettingsSection( * It is a page about a fault, so it exists only while there is one: a * permanent "Разрешения" row on the landing page would be one more thing to * read past on every visit, and would say nothing on the phones — most of - * them — where everything is granted. [listedOnRoot] is what keeps it off. + * them — where everything is granted. [listedOn] is what keeps it off. */ PERMISSIONS( R.string.permissions_title, R.string.permissions_banner_description, Icons.Rounded.Shield, 5, - ) { - override val listedOnRoot: Boolean = false - }, + ), ; - /** Whether the landing page offers a row for this section. */ - open val listedOnRoot: Boolean = true + /** + * Whether the landing page offers a row for this section, on a phone in + * [mode] — [manager] being whether the server has said this phone may + * manage its class. + * + * One rule for both homes, replacing a flag that could only say «never on + * the root». On the diary home the rows that are about a class go: its + * timetable and widget ([CONTENT]), its alerts ([ALERTS]) — planned from a + * class timetable only, so a switch there would be a promise nothing keeps + * — and the class account itself ([ACCOUNT]), whose `/me` and Telegram link + * need a class token this phone does not have. What stays is what is about + * the phone ([APPEARANCE], [FEEL], [UPDATES], [ABOUT]), the server address + * every diary read goes through ([SYNC]), and the diary. + */ + fun listedOn(mode: ShellMode, manager: Boolean): Boolean = when (this) { + PERMISSIONS -> false + ADMIN -> mode == ShellMode.CLASS && manager + CONTENT, ALERTS, ACCOUNT -> mode != ShellMode.DIARY + APPEARANCE, FEEL, SYNC, DIARY, UPDATES, ABOUT -> true + } companion object { /** `null` for anything this build does not have, including `null` itself. */ @@ -266,6 +287,7 @@ enum class SettingsSection( fun SettingsRootScreen( onOpenSection: (SettingsSection) -> Unit, modifier: Modifier = Modifier, + mode: ShellMode = ShellMode.CLASS, viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory), ) { val state by viewModel.uiState.collectAsStateWithLifecycle() @@ -274,8 +296,11 @@ fun SettingsRootScreen( // management row has to decide whether it exists. The refresh is a no-op // while one is already in flight, and a failure leaves the previous answer // standing, so opening settings repeatedly costs one request and never - // takes the row away again. - LaunchedEffect(Unit) { viewModel.refreshDeviceLink() } + // takes the row away again. Only in a class: without a class token the + // request answers 401 on every visit, about a row that cannot exist. + if (mode == ShellMode.CLASS) { + LaunchedEffect(Unit) { viewModel.refreshDeviceLink() } + } val manager = isClassManager(state.deviceLink.role) @@ -286,21 +311,23 @@ fun SettingsRootScreen( onMessageShown = viewModel::consumeMessage, ) { item(key = "class-card") { - ClassHeroCard( - className = state.session?.className - ?: correctedString(R.string.settings_class_unknown), - school = state.session?.school - ?: correctedString(R.string.settings_class_no_school), - ) + if (mode == ShellMode.DIARY) { + DiaryHeroCard() + } else { + ClassHeroCard( + className = state.session?.className + ?: correctedString(R.string.settings_class_unknown), + school = state.session?.school + ?: correctedString(R.string.settings_class_no_school), + ) + } } item(key = "sections") { Column(modifier = Modifier.fillMaxWidth()) { SectionHeader(title = correctedString(R.string.settings_sections)) RoundedCardContainer { - val sections = SettingsSection.entries.filter { - it.listedOnRoot || (it == SettingsSection.ADMIN && manager) - } + val sections = SettingsSection.entries.filter { it.listedOn(mode, manager) } sections.forEach { section -> GroupLinkItem( title = correctedString(section.titleRes), @@ -326,6 +353,7 @@ fun SettingsRootScreen( fun SettingsSectionScreen( section: SettingsSection, modifier: Modifier = Modifier, + mode: ShellMode = ShellMode.CLASS, onOpenSection: (SettingsSection) -> Unit = {}, onOpenDocs: () -> Unit = {}, viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory), @@ -337,15 +365,13 @@ fun SettingsSectionScreen( val state by viewModel.uiState.collectAsStateWithLifecycle() if (section == SettingsSection.DIARY) { - // A blank address is not «insecure», it is «not configured»: nothing - // can be sent at all, so the warning would be about a request that - // never happens. - val address = state.settings.baseUrl - DiaryScreen( - insecureServer = address.isNotBlank() && - !address.startsWith("https://", ignoreCase = true), - modifier = modifier, - ) + // On the diary home the diary is already on screen behind this page; + // what the section adds is the account and the way out of it. + if (mode == ShellMode.DIARY) { + DiaryAccountPage(modifier = modifier) + } else { + DiaryScreen(insecureServer = isInsecure(state.settings.baseUrl), modifier = modifier) + } return } val submitState by viewModel.translationSubmit.collectAsStateWithLifecycle() @@ -444,10 +470,12 @@ fun SettingsSectionScreen( when (section) { SettingsSection.APPEARANCE -> appearanceRows(state, viewModel) - SettingsSection.FEEL -> feelRows(state, viewModel) + SettingsSection.FEEL -> feelRows(state, viewModel, tabs = mode != ShellMode.DIARY) SettingsSection.CONTENT -> contentRows(state, viewModel) SettingsSection.ALERTS -> notificationRows(state, viewModel, onOpenSection) - SettingsSection.SYNC -> syncRows(state, viewModel) { showServerSheet = true } + SettingsSection.SYNC -> syncRows(state, viewModel, classSync = mode != ShellMode.DIARY) { + showServerSheet = true + } SettingsSection.ACCOUNT -> { classRows( state = state, @@ -561,6 +589,23 @@ private fun SettingsPage( } } +/** + * The card at the top of the root page on the diary home: the pupil and the + * school, from the diary view model the home already holds (the activity's). + */ +@Composable +private fun DiaryHeroCard(viewModel: DiaryViewModel = viewModel(factory = DiaryViewModel.Factory)) { + val diary by viewModel.uiState.collectAsStateWithLifecycle() + val student = diary.student + ClassHeroCard( + className = student?.fullName ?: correctedString(R.string.diary_title), + school = student?.let { listOfNotNull(it.className, it.school).joinToString(" · ") } + ?.ifBlank { null } + ?: diary.signInTarget.schoolName + ?: correctedString(R.string.settings_class_no_school), + ) +} + /** The card at the top of the root page, naming the class the app is signed into. */ @Composable private fun ClassHeroCard( @@ -736,9 +781,14 @@ private val AppFont.labelRes: Int AppFont.SYSTEM -> R.string.settings_font_system } +/** + * @param tabs whether the phone has the class tabs these rows are about — the + * swipe between them and the one it opens on. The diary home has neither. + */ private fun LazyListScope.feelRows( state: SettingsUiState, viewModel: SettingsViewModel, + tabs: Boolean, ) { item(key = "haptics") { SettingsGroup(title = correctedString(R.string.settings_haptics_group)) { @@ -764,7 +814,7 @@ private fun LazyListScope.feelRows( } } - item(key = "navigation") { + if (tabs) item(key = "navigation") { SettingsGroup(title = correctedString(R.string.settings_navigation_group)) { GroupSwitchItem( title = correctedString(R.string.settings_swipe_tabs), @@ -1088,20 +1138,30 @@ private val WeekStart.labelRes: Int } +/** + * @param classSync whether the phone has a class for the background sync to + * refresh. Without one — the diary home — the interval and «Обновить сейчас» + * drive a worker that syncs a class only, so they would be switches that do + * nothing; the server address stays, because every diary read goes through + * it. + */ private fun LazyListScope.syncRows( state: SettingsUiState, viewModel: SettingsViewModel, + classSync: Boolean, onEditServer: () -> Unit, ) = item(key = "sync") { SettingsGroup(title = correctedString(R.string.settings_sync_group)) { - SyncIntervalRow( - selectedMinutes = state.settings.syncIntervalMinutes, - onSelect = viewModel::setSyncInterval, - ) + if (classSync) { + SyncIntervalRow( + selectedMinutes = state.settings.syncIntervalMinutes, + onSelect = viewModel::setSyncInterval, + ) + } GroupLinkItem( title = correctedString(R.string.settings_server_url), subtitle = state.settings.baseUrl.takeIf { it.isNotBlank() } - ?: correctedString(R.string.settings_server_url_default), + ?: correctedString(R.string.settings_server_url_unset), icon = Icons.Rounded.Dns, tone = accentTone(0), onClick = onEditServer, @@ -1110,12 +1170,14 @@ private fun LazyListScope.syncRows( // the one thing on this page that *does* something the moment it is // pressed rather than storing a preference. Essentials closes its own // updates group with the same shape. - GroupActionItem( - label = correctedString(R.string.settings_refresh_now), - icon = Icons.Rounded.Refresh, - busy = state.isRefreshing, - onClick = viewModel::refreshNow, - ) + if (classSync) { + GroupActionItem( + label = correctedString(R.string.settings_refresh_now), + icon = Icons.Rounded.Refresh, + busy = state.isRefreshing, + onClick = viewModel::refreshNow, + ) + } } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsViewModel.kt index 8d4ba627..8da922c4 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/SettingsViewModel.kt @@ -355,16 +355,6 @@ class SettingsViewModel( */ fun setDebugMode(enabled: Boolean) = update { it.copy(debugMode = enabled) } - /** - * Records that the first-run introduction has been seen. - * - * Written when the introduction reaches the class-code step rather than when - * a class is actually joined: a pupil who backs out at the code field has - * still read the four screens, and making them read them again is a - * punishment for hesitating. - */ - fun setOnboardingDone() = update { it.copy(onboardingDone = true) } - /** * Everything the app is allowed to interrupt the user about. * diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt index 7800e62c..7efbef57 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/translate/TranslationXml.kt @@ -178,6 +178,7 @@ internal object TranslationXml { "strings_docs.xml", "strings_github.xml", "strings_legal.xml", + "strings_onboarding.xml", "strings_telegram.xml", "strings_translate.xml", "strings_updates.xml", diff --git a/android/app/src/main/res/values-en/strings.xml b/android/app/src/main/res/values-en/strings.xml index d3b592c5..d11b97a0 100644 --- a/android/app/src/main/res/values-en/strings.xml +++ b/android/app/src/main/res/values-en/strings.xml @@ -23,14 +23,12 @@ Back - Step %1$d of %2$d Welcome to %1$s Your class timetable, its substitutions and its homework — in the app and on the home screen. - Let\'s begin Confirmation - The app shows the timetable of whichever class you join. The data comes from the school server: the app only reads it and changes nothing in the school register. + The app shows your class\'s timetable — with a code from the bot — or your electronic diary, if you sign in to it yourself. It only reads that data and changes nothing in the school register or in the diary. -The access key you were given and a copy of the timetable stay on the device, so that the app and the widget work without a network. All of it is deleted when you leave the class. +The phone keeps an access key and copies of the timetable and the diary, so the app works offline. Leaving the class or signing out of the diary erases them from the phone; what the server keeps is in the privacy policy. The timetable may have been changed later than the app managed to fetch it. Before a test or a substitution, check it against what you were told at school. If the app behaves strangely, an error report helps work out why. It stays on the phone until you send it yourself. Error reports @@ -60,6 +58,7 @@ The access key you were given and a copy of the timetable stay on the device, so Join The code is %1$d to %2$d characters long Could not join: %1$s + No server address is set. Tap “Server address” below and type the address the class admin gave you. Could not join. Check the code and your network connection. No such code. Check it with whoever gave it to you. Server address - Change this only if the school runs its own server. + The address of the server the class and the diary go through. No server is built into the app: the class admin, or whoever set the server up, has the address. Address https://… @@ -315,7 +314,7 @@ The access key you were given and a copy of the timetable stay on the device, so Sync How often to update Server address - Default + Not set Update now Class No class chosen diff --git a/android/app/src/main/res/values-en/strings_diary.xml b/android/app/src/main/res/values-en/strings_diary.xml index 545cec83..e0849c0d 100644 --- a/android/app/src/main/res/values-en/strings_diary.xml +++ b/android/app/src/main/res/values-en/strings_diary.xml @@ -1,6 +1,6 @@ Diary - Timetable, homework and marks from the Petersburg electronic diary + Timetable, homework and marks from your school\'s electronic diary Sign in to the diary - The same login and password as on the Petersburg diary website + The same login and password as on your electronic diary\'s website Login Password Show the password Hide the password Sign in - The password is stored nowhere. It is used for exactly one request - signing in to the diary - and then forgotten by both this phone and the server. When the diary session eventually ends, the app will ask for it again. + The password goes straight to the diary, over HTTPS, and nowhere else: not to our server and not to this phone\'s storage. The server is handed only the session the diary issued. When that ends, the app will ask for the password again. The diary session has ended @@ -29,14 +29,14 @@ That did not work - Wrong login or password - This diary sign-in is no longer valid. Please sign in again. - The diary is not answering. Try again later. - The diary answered in a way the server could not read: the service changed, and that is fixed on the server rather than in the app. - No connection to the server. Check the network and the server address under “Sync”. + Wrong login or password + This diary sign-in is no longer valid. Please sign in again. + The diary is not answering. Try again later. + The diary answered in a way the server could not read: the service changed, and that is fixed on the server rather than in the app. + No connection to the server. Check the network and the server address under “Sync”. That date range is too wide - the diary serves at most 62 days at a time. This account has no such pupil. - It did not work: %1$s + It did not work: %1$s Try again + The password goes only to %1$s - over HTTPS, straight to the diary. + Diary: %1$s + + + The diary said: “%1$s”. + In this region the diary lets people in through Gosuslugi only. The app does not sign in there - open the diary\'s website in a browser. + %1$s is not answering. Try again later. + %1$s is refusing this phone. If a VPN is on, turn it off and try again. + The diary is refusing this phone. If a VPN is on, turn it off and try again. + This phone does not trust the certificate of %1$s, and the app will not work around that check. + This phone does not trust the diary\'s certificate, and the app will not work around that check. + %1$s answered in a way the app cannot read - most likely its sign-in page changed. An app update fixes that, not another password. + Cannot reach %1$s. Check the network. + Cannot reach the diary. Check the network. + %1$s did not answer in time. Try again. + No answer came in time. Try again. + The diary let you in, but the server cannot be reached right now. Try again - no need to type the password. + No server address is set. Set one under “Sync”. + This server cannot take a sign-in opened on the phone. It needs a newer server, or another address. + The diary is switched off on this server. Only whoever runs the server can switch it on. + This server does not work with your region\'s diary. + The diary let you in, but refused the sign-in from the server\'s address. It is not the password, and trying again will not help. You can join a class by its code instead. + The diary is not answering the server: it refuses requests from its address. It is not the password. + The diary shows no pupil for this account. + Too many attempts. Wait a little and try again. + + Too many attempts. Try again in %1$d minute. + Too many attempts. Try again in %1$d minutes. + + Signing in took too long and the diary closed the session. Please sign in again. + The login is too short - it needs at least three characters. + The diary closed the session. Type the password again. + + + No connection - showing what was saved on this phone. %1$s + Region + System + School + Join a class by code + If an administrator sets up your school\'s class in the bot, its code adds the class timetable, the widget and the bell reminders. + The phone goes back to the start. Lessons and marks saved on the phone are deleted, and the server forgets its copy of the sign-in. + + + Choose a diary + Your region and school tell the app which diary to sign in to. + Region, city or code + No such region in the list. Try the name of a city. + School name or number + Type at least two characters and the region\'s diary will list matching schools. + No school by that name. + The app cannot sign in to a diary in this region yet. + In this region the diary lets people in through Gosuslugi or its own website only. The app does not sign in there, but the website can be opened in a browser. + Open the diary\'s website + Change diff --git a/android/app/src/main/res/values-en/strings_onboarding.xml b/android/app/src/main/res/values-en/strings_onboarding.xml new file mode 100644 index 00000000..45208c79 --- /dev/null +++ b/android/app/src/main/res/values-en/strings_onboarding.xml @@ -0,0 +1,179 @@ + + + + + %1$s: step %2$d of %3$d + Introduction + Your school + The class\'s diary + The diary + + Continue + Try again + + How do you want to start? + Choose where the app takes your timetable from. You can add the other way later. + With a class code + Quick + The class admin gives out the code in the Telegram bot. The class\'s shared timetable, changes and homework — and the bot itself. + Find your school + On your own + Region, school and a sign-in to the electronic diary. Only your own data from the school\'s diary, without the bot. The password goes straight to the diary. + Not set — you will be asked when it is needed + Enter the code + Find the school + + Your region + A region, a city or a school name + Region, city or school + Clear + All regions + Regions + City: %1$s + Also called %1$s + Region code: %1$s + %1$s · sign in here + %1$s · Gosuslugi only + %1$s · opens the diary\'s site + %1$s · the app cannot read it yet + No electronic diary + Nothing found + Try a region or a large city — or the school, if you remember its whole name. + Where the school “%1$s” may be + Looking the school up by name… + + %1$d school + %1$d schools + + %1$s: %2$s + There are more matches than shown. If your region is not here, pick it from the list. + Schools with this name are all over the country. Pick the region from the list — the next step finds the school. + No such school in the company register. Pick the region from the list. + + The school-name search is resting for another %1$d minute. Pick the region from the list. + The school-name search is resting for another %1$d minutes. Pick the region from the list. + + The school-name search is resting for now. Pick the region from the list. + The server looks schools up by name, and none is set. Pick the region from the list. + The server cannot be reached, so the school cannot be looked up by name. Pick the region from the list — it works offline. + This server cannot look schools up by name. Pick the region from the list. + + Your school + %1$s · %2$s + A number or a word of the name + + Type at least %1$d character. + Type at least %1$d characters. + + The region\'s diary has no school by that name. Try the number alone. + My school is not listed + Choose the school + + The electronic diary + What schools use: %1$s + Recommended + Why? + Why %1$s is recommended + The region\'s main one + Runs alongside the main one + The region is moving to it + %1$s · %2$s + sign in here + choose the school first + the diary takes the school from your account + Gosuslugi only, in the browser + the app cannot read it; opens the site + the app cannot read this diary yet + no electronic diary + Not your diary? + Use a class code + If the class is run in the bot, its admin has a code + Sign in + Open Gosuslugi + Open the diary\'s site + + %1$s will open + This diary opens only through Gosuslugi. The app never asks for a Gosuslugi password and never takes its sign-in, so it cannot show this diary. The page opens in the browser — or in whichever app the phone offers for it. Sign in there as usual. + The app cannot read this diary yet. Its site will open — sign in there the way your school does. A class code still brings the class timetable into the app. + Open + Nothing on this phone can open the link. + + Why %1$s + In the %3$s school year the main electronic diary of schools in %1$s is %2$s. + %1$s keeps its diary in %2$s, which opens only through Gosuslugi. + Schools in %1$s show their marks in %2$s, while the diary itself is %3$s. The app cannot sign in there, so it recommends what opens for everyone. + %1$s is moving to %2$s school by school. If yours already has, choose this one. + The diary of schools in %1$s takes no secure connections, and the app sends no password without one. So it recommends %2$s. + Schools in %1$s use %2$s. The app cannot read it yet; a class code still brings the class timetable. + In the %2$s school year schools in %1$s keep paper registers — there is no electronic diary. + A regional portal, the ministry or the diary\'s operator confirms it. + This comes from news and school sites; no official page was found. + This is unconfirmed — it may hold only for some schools. + This diary lets you in only through Gosuslugi, and the app does not take a Gosuslugi sign-in. + Signing in to this diary has never yet been tried on a real account. If it fails, a class code works regardless. + You type the password here, in the app, and it goes only to %1$s. Our server gets the session the diary hands out after sign-in — not the password. + From the survey of every region\'s diary, %1$s. + + Sign in to %1$s + %1$s · %2$s + The diary takes the school and class from your account + Your class\'s diary + Class %1$s keeps its diary in %2$s. Sign in to see your marks and homework from it in the app. + Where the password goes + Email + Checking the server… + Signing in to %1$s… + Handing the session to the server… + Forgot the password? Open the diary\'s site + Not now + Try again without the password + Set the server + It is unclear which diary to sign in to. Go back a step and choose it again. + To keep you signed in and to load the diary, the app needs a server. Whoever set one up for your school, or for you, has its address. The password never goes there — only the session the diary hands out. + + Loading the diary + It takes up to a minute. Keep the app open until it finishes. + %1$d%% loaded + Student + Terms + Timetable for two weeks + Homework + Marks + Waiting + Loading… + Done + Did not load — the next refresh tries again + The load stopped here + + %1$d lesson + %1$d lessons + + + %1$d assignment + %1$d assignments + + Whose diary should the app show? + The account has several students and the app shows one. You can switch in settings. + The load stopped: %1$s + The diary ended the session during the load. Sign in again — the load carries on where it stopped. + Sign in again + Sign out of the diary and start over + + All set + This is what the app will show. All of it can be changed in settings. + Student + Diary + Class + No class + The bot does not know about you: the app shows only your diary. The widget, the notifications and the Today and Calendar tabs run on a class. If an admin sets your class up in the bot, join with its code in settings. + + The diary stays signed in while you open the app. After %1$d day without it you will have to sign in again — the widget does not extend it. + The diary stays signed in while you open the app. After %1$d days without it you will have to sign in again — the widget does not extend it. + + The Petersburg diary may end the session sooner — the app then asks for the password again. + Settings + Notifications + Allowed + Not all allowed — some reminders will not come + Open the app + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index a4e030da..df1edf55 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -19,14 +19,12 @@ Назад - Шаг %1$d из %2$d Добро пожаловать в «%1$s» Расписание, замены и домашние задания вашего класса — в приложении и на главном экране. - Давайте начнём Подтверждение - Приложение показывает расписание того класса, к которому вы подключитесь. Данные приходят с сервера школы: приложение только читает их и ничего не меняет в школьном журнале. + Приложение показывает расписание вашего класса — по коду из бота — или ваш электронный дневник, если вы войдёте в него сами. Оно только читает эти данные и ничего не меняет ни в школьном журнале, ни в дневнике. -На устройстве остаются выданный вам ключ доступа и копия расписания — чтобы приложение и виджет работали без сети. Всё это удаляется, когда вы выходите из класса. +На телефоне остаются ключ доступа и копии расписания и дневника, чтобы приложение работало без сети. Выход из класса или из дневника стирает их с телефона; что хранит сервер, сказано в политике конфиденциальности. Расписание могли изменить позже, чем приложение успело его забрать. Перед контрольной или заменой сверяйтесь с тем, что сказали в школе. Если приложение поведёт себя странно, отчёт об ошибке поможет разобраться. Он остаётся на телефоне, пока вы сами его не отправите. Отчёты об ошибках @@ -52,6 +50,7 @@ Подключиться В коде от %1$d до %2$d символов Не удалось подключиться: %1$s + Не указан адрес сервера. Нажмите «Адрес сервера» ниже и введите адрес, который дал администратор класса. Не удалось подключиться. Проверьте код и подключение к сети. Такого кода нет. Проверьте его у того, кто его дал. Этот класс подключает телефоны только по личному приглашению. Возьмите личный код в боте: меню → «📱 Подключить телефон». @@ -70,11 +69,11 @@ Виджет на главном экране Текущий урок и сколько до звонка — без открытия приложения. Сервер - По умолчанию — сервер класса + Не задан — адрес даёт администратор класса Адрес сервера - Меняйте только если школа использует свой сервер. + Адрес сервера, через который работают класс и дневник. Встроенного в приложение сервера нет: адрес даёт администратор класса или тот, кто поднял сервер. Адрес https://… @@ -315,7 +314,7 @@ Синхронизация Как часто обновлять Адрес сервера - По умолчанию + Не задан Обновить сейчас Класс Класс не выбран diff --git a/android/app/src/main/res/values/strings_diary.xml b/android/app/src/main/res/values/strings_diary.xml index e4c1e1ae..1717f605 100644 --- a/android/app/src/main/res/values/strings_diary.xml +++ b/android/app/src/main/res/values/strings_diary.xml @@ -1,6 +1,6 @@ Дневник - Расписание, задания и оценки из электронного дневника Петербурга + Расписание, задания и оценки из электронного дневника школы Вход в дневник - Те же логин и пароль, что на сайте электронного дневника Петербурга + Те же логин и пароль, что на сайте вашего электронного дневника Логин Пароль Показать пароль Скрыть пароль Войти - Пароль нигде не сохраняется. Он нужен ровно на один запрос — вход в дневник, — после чего его забывают и телефон, и сервер. Когда сессия дневника всё-таки закончится, приложение спросит пароль ещё раз. + Пароль уходит прямо в дневник, по HTTPS, и больше никуда: ни на наш сервер, ни на диск телефона. Серверу телефон передаёт только сессию, которую выдал дневник. Когда она закончится, приложение спросит пароль ещё раз. Сессия дневника закончилась @@ -29,14 +29,14 @@ Не получилось - Неверный логин или пароль - Вход в дневник больше не действует. Войдите заново. - Дневник не отвечает. Попробуйте позже. - Дневник ответил непонятно: сервис изменился, и это чинится на сервере, а не в приложении. - Нет связи с сервером. Проверьте интернет и адрес сервера в разделе «Синхронизация». + Неверный логин или пароль + Вход в дневник больше не действует. Войдите заново. + Дневник не отвечает. Попробуйте позже. + Дневник ответил непонятно: сервис изменился, и это чинится на сервере, а не в приложении. + Нет связи с сервером. Проверьте интернет и адрес сервера в разделе «Синхронизация». Слишком широкий промежуток дат — дневник отдаёт не больше 62 дней за раз. Этого ученика нет в аккаунте. - Не получилось: %1$s + Не получилось: %1$s Повторить + Пароль уйдёт только на %1$s — по HTTPS, прямо в дневник. + Дневник: %1$s + + + Дневник ответил: «%1$s». + В этом регионе дневник впускает только через Госуслуги. Приложение туда не входит — откройте сайт дневника в браузере. + %1$s не отвечает. Попробуйте позже. + %1$s не пускает этот телефон. Если включён VPN, выключите его и попробуйте ещё раз. + Дневник не пускает этот телефон. Если включён VPN, выключите его и попробуйте ещё раз. + Телефон не доверяет сертификату %1$s, и приложение не станет обходить эту проверку. + Телефон не доверяет сертификату дневника, и приложение не станет обходить эту проверку. + %1$s ответил непонятно — скорее всего, у дневника изменилась страница входа. Это чинится обновлением приложения, а не паролем. + Не получается связаться с %1$s. Проверьте интернет. + Не получается связаться с дневником. Проверьте интернет. + %1$s не ответил вовремя. Попробуйте ещё раз. + Ответа не дождались. Попробуйте ещё раз. + Дневник вас впустил, но сервер сейчас недоступен. Повторите — пароль вводить заново не нужно. + Не указан адрес сервера. Задайте его в разделе «Синхронизация». + Этот сервер не умеет принимать вход, открытый на телефоне. Нужен сервер новее или другой адрес. + Дневник выключен на этом сервере. Включить его может только тот, кто обслуживает сервер. + Этот сервер не работает с дневником вашего региона. + Дневник вас впустил, но не принял вход с адреса сервера. Пароль тут ни при чём, и повтор не поможет. Можно подключиться к классу по коду. + Дневник не отвечает серверу: запросы с его адреса он отклоняет. Пароль тут ни при чём. + Для этого аккаунта дневник не показывает ни одного ученика. + Слишком много попыток. Подождите немного и попробуйте снова. + + Слишком много попыток. Попробуйте снова через %1$d минуту. + Слишком много попыток. Попробуйте снова через %1$d минуты. + Слишком много попыток. Попробуйте снова через %1$d минут. + Слишком много попыток. Попробуйте снова через %1$d минуты. + + Вход занял слишком много времени, и дневник закрыл сессию. Войдите ещё раз. + Логин слишком короткий — в нём должно быть хотя бы три знака. + Дневник закрыл сессию. Нужно ввести пароль ещё раз. + + + Нет связи — показано сохранённое на телефоне. %1$s + Регион + Система + Школа + Подключиться к классу по коду + Если администратор заведёт класс вашей школы в боте, его код добавит расписание класса, виджет и напоминания о звонках. + Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер забудет свою копию входа. + + + Выбрать дневник + Регион и школа — по ним приложение поймёт, в какой дневник входить. + Регион, город или код + Такого региона нет в списке. Попробуйте название города. + Название или номер школы + Введите хотя бы два знака, и дневник региона покажет подходящие школы. + Школ с таким названием не нашлось. + В этом регионе приложение пока не умеет входить в дневник. + В этом регионе дневник впускает только через Госуслуги или свой сайт. Приложение туда не входит, но сайт можно открыть в браузере. + Открыть сайт дневника + Сменить diff --git a/android/app/src/main/res/values/strings_onboarding.xml b/android/app/src/main/res/values/strings_onboarding.xml new file mode 100644 index 00000000..509fa53a --- /dev/null +++ b/android/app/src/main/res/values/strings_onboarding.xml @@ -0,0 +1,218 @@ + + + + + + %1$s: шаг %2$d из %3$d + Знакомство + Своя школа + Дневник класса + Дневник + + Продолжить + Повторить + + + Как подключиться? + Выберите, откуда приложение возьмёт расписание. Второй способ можно подключить и потом. + По коду класса + Быстро + Код даёт администратор класса в Telegram-боте. Общее расписание, замены и задания класса — и сам бот. + Найти свою школу + Самостоятельно + Регион, школа и вход в электронный дневник. Только ваши данные из дневника школы, без бота. Пароль уходит прямо в дневник. + Не задан — его спросят, когда он понадобится + Ввести код + Найти школу + + + Ваш регион + Название региона, города или школы + Регион, город или школа + Очистить + Все регионы + Регионы + Город: %1$s + Ещё называют: %1$s + Код региона: %1$s + %1$s · вход в приложении + %1$s · только через Госуслуги + %1$s · откроется сайт дневника + %1$s · приложение пока не читает + Электронного дневника нет + Ничего не нашлось + Попробуйте название региона или крупного города — или школы, если помните его целиком. + Где может быть школа «%1$s» + Ищем школу по названию… + + %1$d школа + %1$d школы + %1$d школ + %1$d школы + + + %1$s: %2$s + Совпадений больше, чем показано. Если вашего региона здесь нет, выберите его из списка. + Школ с таким названием много по всей стране. Выберите регион из списка — школу найдём на следующем шаге. + В реестре организаций такой школы нет. Выберите регион из списка. + + Поиск школ по названию отдыхает ещё %1$d минуту. Выберите регион из списка. + Поиск школ по названию отдыхает ещё %1$d минуты. Выберите регион из списка. + Поиск школ по названию отдыхает ещё %1$d минут. Выберите регион из списка. + Поиск школ по названию отдыхает ещё %1$d минуты. Выберите регион из списка. + + Поиск школ по названию сейчас отдыхает. Выберите регион из списка. + Школу по названию ищет сервер, а он не задан. Выберите регион из списка. + Нет связи с сервером, и школу по названию найти не получится. Выберите регион из списка — он работает и без сети. + Поиск школ по названию на этом сервере не работает. Выберите регион из списка. + + + Ваша школа + %1$s · %2$s + Номер или слово из названия + + Введите хотя бы %1$d символ. + Введите хотя бы %1$d символа. + Введите хотя бы %1$d символов. + Введите хотя бы %1$d символа. + + В дневнике региона нет школы с таким названием. Попробуйте только номер. + Моей школы нет в списке + Выбрать школу + + + Электронный дневник + Чем пользуются школы: %1$s + Рекомендуем + Почему? + Почему рекомендуем «%1$s» + Основной в регионе + Работает рядом с основным + Регион переходит на него + + %1$s · %2$s + вход в приложении + сначала выберите школу + школу дневник возьмёт из аккаунта + только через Госуслуги, в браузере + приложение не читает, откроется сайт + приложение пока не читает этот дневник + электронного дневника нет + Нет вашего дневника? + Войти по коду класса + Если класс ведут в боте, код даст его администратор + Войти + Открыть Госуслуги + Открыть сайт дневника + + + Откроется «%1$s» + Этот дневник открывается только через Госуслуги. Приложение не просит пароль от Госуслуг и не берёт их вход, поэтому показать этот дневник здесь не может. Страница откроется в браузере — или в приложении, которое телефон предложит для неё. Войдите там, как обычно. + Приложение пока не читает этот дневник. Откроется его сайт — войдите там так, как принято в вашей школе. Расписание класса в приложении можно получить по коду класса. + Открыть + На телефоне нет приложения, которое открыло бы эту ссылку. + + + Почему «%1$s» + В %3$s учебном году основной электронный дневник школ региона «%1$s» — «%2$s». + Регион «%1$s» ведёт дневник в «%2$s»: он открывается только через Госуслуги. + Оценки школ региона «%1$s» видны в «%2$s», а сам дневник — «%3$s». Приложение туда войти не может, поэтому рекомендуем то, что открывается у всех. + Регион «%1$s» переходит на «%2$s» по частям. Если ваша школа уже перешла — выбирайте этот вариант. + Дневник школ региона «%1$s» не принимает защищённые соединения, а приложение без них пароль не отправляет. Поэтому рекомендуем «%2$s». + Дневник школ региона «%1$s» — «%2$s». Приложение пока не умеет его читать; расписание класса можно получить по коду. + В %2$s учебном году школы региона «%1$s» ведут бумажные журналы — электронного дневника нет. + Это подтверждает региональный портал, министерство или оператор дневника. + Это известно из новостей и сайтов школ; официальной страницы не нашлось. + Это не подтверждено — возможно, так только в отдельных школах. + В этот дневник пускают только через Госуслуги, а их вход приложение не берёт. + Вход в этот дневник ещё ни разу не проверяли на настоящем аккаунте. Если он не получится, код класса работает и так. + Пароль вводится здесь, в приложении, и уходит только на %1$s. Наш сервер получает сессию, которую дневник выдаст после входа, — не пароль. + По обзору дневников всех регионов, %1$s. + + + Вход в «%1$s» + + %1$s · %2$s + Школу и класс дневник возьмёт из вашего аккаунта + Дневник вашего класса + Класс «%1$s» ведёт дневник в «%2$s». Войдите, чтобы видеть в приложении свои оценки и задания оттуда. + Куда уйдёт пароль + Электронная почта + Проверяем сервер… + Входим в «%1$s»… + Передаём сессию серверу… + Забыли пароль? Откройте сайт дневника + Не сейчас + Повторить без пароля + Указать сервер + Непонятно, в какой дневник входить. Вернитесь на шаг назад и выберите его ещё раз. + Чтобы держать вход в дневник и загружать его, приложению нужен сервер. Адрес даёт тот, кто поднял сервер для вашей школы или для вас. Пароль туда не попадёт — только сессия, которую выдаст дневник. + + + Загружаем дневник + Это займёт до минуты. Пока идёт загрузка, не закрывайте приложение. + Загружено %1$d%% + Ученик + Учебные периоды + Расписание на две недели + Домашние задания + Оценки + В очереди + Загружается… + Готово + Не загрузилось — попробуем при следующем обновлении + Здесь загрузка остановилась + + %1$d урок + %1$d урока + %1$d уроков + %1$d урока + + + %1$d задание + %1$d задания + %1$d заданий + %1$d задания + + Чей дневник показывать? + В аккаунте несколько учеников, а приложение показывает одного. Сменить можно в настройках. + Загрузка остановилась: %1$s + Дневник закрыл вход, пока шла загрузка. Войдите ещё раз — загрузка продолжится с того же места. + Войти ещё раз + Выйти из дневника и начать заново + + + Всё готово + Вот что будет в приложении. Всё это меняется в настройках. + Ученик + Дневник + Класс + Без класса + Бот о вас не знает: приложение показывает только ваш дневник. Виджет, уведомления и вкладки «Сегодня» и «Календарь» работают от класса. Если администратор заведёт ваш класс в боте, подключитесь по его коду в настройках. + + Вход в дневник держится, пока вы открываете приложение. После %1$d дня без этого войти придётся заново — виджет вход не продлевает. + Вход в дневник держится, пока вы открываете приложение. После %1$d дней без этого войти придётся заново — виджет вход не продлевает. + Вход в дневник держится, пока вы открываете приложение. После %1$d дней без этого войти придётся заново — виджет вход не продлевает. + Вход в дневник держится, пока вы открываете приложение. После %1$d дня без этого войти придётся заново — виджет вход не продлевает. + + Дневник Петербурга может закончить вход и раньше — тогда приложение попросит пароль ещё раз. + Настройки + Уведомления + Разрешены + Не все разрешены — часть напоминаний не придёт + Открыть приложение + diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml index 7ced20dc..93380355 100644 --- a/android/app/src/main/res/xml/network_security_config.xml +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -10,21 +10,31 @@ private network - which public CAs do not issue - so the practical effect would not be "encrypted", it would be "the app does not work". - What crosses the wire is NOT bounded the way this comment used to claim. It - said "no credentials, no personal data, nothing that identifies a pupil", and - that was true when it was written and stopped being true when the app grew - its own diary sign-in. DiaryApi.login posts a dnevnik2 login and password to - /api/v1/diary/login, through the same OkHttp client and to whatever address - the reader typed in settings - so on a plain http:// deployment, anyone on - the same school Wi-Fi reads a parent's password for a third party's service, - the diary bearer that opens a child's marks and attendance, and a class - bearer that is frequently a WRITE token since personal connect codes exist. + What crosses the wire to that server is NOT harmless, and this comment once + said it was ("no credentials, no personal data, nothing that identifies a + pupil"). The diary's password is not among it: the app never sends it to our + server. It goes only to the diary's own origin, taken from the catalog bundled + with the app, https-only - an origin that is not is dropped from the + allow-list - and enforced on every request by OriginGuard, with no redirect + followed. So the cleartext permitted here never carries it: the allow-list + holds https origins only, and there is no http:// address the sign-in may + send to. + + What does cross a plain http:// server, readable by anyone on the same school + Wi-Fi, is: + - the diary session the diary hands back, which the phone registers with + our server at POST /api/v1/diary/session - a working credential for the + child's diary until it expires; + - the diary bearer that opens the child's marks and attendance through us; + - the class bearer, which is frequently a WRITE token since personal + connect codes exist. It is still permitted, because the premise above is real: demanding HTTPS on a LAN address would mean "the app does not work" rather than "encrypted". - What changed is that the app now says so where it matters. DiarySignInScreen - warns before the password is typed when the server address is not https://, - which is the one screen where the cost is a password rather than a timetable. + What changed is that the app says so where it matters: the diary sign-in form + warns before anything is typed when the server address is not https:// + (diary_insecure_server), and the warning is about the session, not the + password. A school that does terminate TLS simply enters an https:// address and this configuration stops applying to it; nothing here downgrades a secure URL. diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/DeviceClockTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/DeviceClockTest.kt index a65975a0..dca8a3b1 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/DeviceClockTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/DeviceClockTest.kt @@ -22,8 +22,10 @@ import org.junit.Test * somebody who knew the rule. * * The rule is not "never": a read that has no timetable to take a zone from has - * nowhere else to go, and the diary keeps Moscow time because it is one city's - * service. So a line may say so. It must say so *on the line above it*, which + * nowhere else to go. The diary is not such a read — it has a zone of its own, + * the one the server named at registration (`DiaryTarget.zoneId()`), and cuts + * its days there rather than in the phone's zone or a fixed Moscow. So a line + * that truly has no zone may say so. It must say so *on the line above it*, which * is the point — the comment is what makes the next reader stop, and a reviewer * who cannot write one has found a defect rather than an exception. */ diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/SyncArmingTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/SyncArmingTest.kt new file mode 100644 index 00000000..4db33021 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/SyncArmingTest.kt @@ -0,0 +1,98 @@ +package com.lumenpearson.lessons + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.SyncArming +import com.lumenpearson.lessons.core.data.repository.syncArmingFor +import java.io.File +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * #152: every cold start armed the fifteen-minute background sync, on a phone + * in no class too. + * + * `LessonsApplication.observeSyncInterval` collected the interval alone and + * scheduled the worker on its first emission, so a phone that had left its + * last class — whose sign-out had just cancelled the worker — was woken again + * from its next launch on, for ever, for a run that found no class and + * returned. A diary-only phone would have been woken the same way. What the + * application runs now is [driveSyncScheduler] over `shellMode.syncArming`. + */ +class SyncArmingTest { + + private class Recorder { + val calls = mutableListOf() + fun schedule(minutes: Int) { + calls += "schedule $minutes" + } + fun cancel() { + calls += "cancel" + } + } + + @Test + fun `a cold start in no class or on the diary cancels rather than arms`() { + for (mode in listOf(ShellMode.NONE, ShellMode.DIARY)) { + val recorder = Recorder() + runBlocking { + flowOf(syncArmingFor(mode, intervalMinutes = 15)) + .driveSyncScheduler(recorder::schedule, recorder::cancel) + } + assertEquals(mode.name, listOf("cancel"), recorder.calls) + } + } + + @Test + fun `a class is armed at its interval and re-armed when it changes`() { + val recorder = Recorder() + runBlocking { + flowOf( + SyncArming.Armed(15), + SyncArming.Armed(60), + SyncArming.Disarmed, + ).driveSyncScheduler(recorder::schedule, recorder::cancel) + } + assertEquals(listOf("schedule 15", "schedule 60", "cancel"), recorder.calls) + } + + /** + * The application's own source, because what it collects is the defect: + * a collector of the interval alone compiles, runs and arms a phone in no + * class, and nothing but reading what it collects can tell the two apart. + */ + @Test + fun `the application arms the worker from the mode, not from the interval alone`() { + val source = applicationSource().readText() + assertTrue( + "LessonsApplication must collect shellMode.syncArming", + Regex("""shellMode\s*\.\s*syncArming""").containsMatchIn(source), + ) + assertFalse( + "LessonsApplication collects the interval on its own again (#152)", + Regex("""syncIntervalMinutes""").containsMatchIn(source), + ) + // One way to the scheduler: through the driver, whose only input is + // the mode-and-interval rule. + val direct = Regex("""SyncScheduler\.schedulePeriodic""").findAll(source).count() + assertEquals(1, direct) + assertTrue(Regex("""driveSyncScheduler\(""").containsMatchIn(source)) + } + + private fun applicationSource(): File { + var directory: File? = File("").absoluteFile + while (directory != null) { + val candidates = listOf( + File(directory, "src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt"), + File(directory, "app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt"), + File(directory, "android/app/src/main/kotlin/com/lumenpearson/lessons/LessonsApplication.kt"), + ) + candidates.firstOrNull { it.isFile }?.let { return it } + directory = directory.parentFile + } + error("LessonsApplication.kt not found from ${File("").absolutePath}") + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/RootGateTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/RootGateTest.kt new file mode 100644 index 00000000..44c72d50 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/navigation/RootGateTest.kt @@ -0,0 +1,69 @@ +package com.lumenpearson.lessons.navigation + +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.data.repository.shellModeOf +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The gate below the theme: splash, the way in, or a home — and which home. + * + * Nothing composes `LessonsApp` in a test, so this rule is what holds the gate. + * It is kept pure for that reason, and the shell only carries it out. + */ +class RootGateTest { + + private val petersburg = DiaryTarget.petersburg("parent@example.com") + private val seventhA = Session(classId = 7, className = "7А", school = null, token = "t") + + /** + * #151. A family signed in to their diary leaves their last class: no class, + * a diary. The gate used to ask only «is there a class session» and sent + * the phone to the join screen, where neither the diary nor its sign-out + * could be reached, while the diary's session went on being kept alive for + * a month. + */ + @Test + fun `a phone with a diary and no class opens on the diary home`() { + val mode = shellModeOf(classSession = null, diaryTarget = petersburg) + val shell = ShellState(mode, held = false) + + assertEquals(RootScreen.HOME, rootScreen(shell)) + assertEquals(ShellHome.DIARY, shellHome(shell.mode)) + } + + @Test + fun `a class outranks a diary`() { + val mode = shellModeOf(classSession = seventhA, diaryTarget = petersburg) + + assertEquals(RootScreen.HOME, rootScreen(ShellState(mode, held = false))) + assertEquals(ShellHome.TIMETABLE, shellHome(mode)) + } + + @Test + fun `nothing stored is the way in`() { + assertEquals(RootScreen.ONBOARDING, rootScreen(ShellState(ShellMode.NONE, held = false))) + assertNull(shellHome(ShellMode.NONE)) + } + + @Test + fun `nothing read yet is the splash`() { + assertEquals(RootScreen.SPLASH, rootScreen(null)) + } + + /** + * K3: the class-code and sign-in steps write their credential before the + * flow has finished, and the hold keeps the flow on screen through the + * write — whichever home the write has just made. + */ + @Test + fun `a hold keeps the way in on screen whatever the mode`() { + for (mode in ShellMode.entries) { + assertEquals(mode.name, RootScreen.ONBOARDING, rootScreen(ShellState(mode, held = true))) + } + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellLanguageTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellLanguageTest.kt index 3a794b5b..95071e49 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellLanguageTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellLanguageTest.kt @@ -1,6 +1,8 @@ package com.lumenpearson.lessons.ui import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellState import com.lumenpearson.lessons.core.model.AppLanguage import org.junit.Assert.assertEquals import org.junit.Assert.assertNull @@ -59,19 +61,22 @@ class AppShellLanguageTest { } /** - * `signedIn` is a different question and must not be mistaken for this one. + * `shell` is a different question and must not be mistaken for this one. * It happens to be `null` for as long as the settings are unread, but only * because two independent reads are racing in the same view model, and a * gate built on that is a gate held up by an accident. */ @Test - fun `being signed in decides nothing about the language`() { - val notLoaded = AppShellUiState(signedIn = true, settingsLoaded = false) + fun `having a home decides nothing about the language`() { + val notLoaded = AppShellUiState( + shell = ShellState(ShellMode.CLASS, held = false), + settingsLoaded = false, + ) assertNull(notLoaded.languageToApply) val loaded = AppShellUiState( settings = AppSettings(language = AppLanguage.ENGLISH), - signedIn = null, + shell = null, settingsLoaded = true, ) assertEquals(AppLanguage.ENGLISH, loaded.languageToApply) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellViewModelTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellViewModelTest.kt new file mode 100644 index 00000000..6d713924 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/AppShellViewModelTest.kt @@ -0,0 +1,119 @@ +package com.lumenpearson.lessons.ui + +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.SettingsRepository +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.data.repository.SyncArming +import com.lumenpearson.lessons.navigation.RootScreen +import com.lumenpearson.lessons.navigation.ShellHome +import com.lumenpearson.lessons.navigation.rootScreen +import com.lumenpearson.lessons.navigation.shellHome +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.onStart +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * The shell's state holder: the stored mode, read after the cold start has been + * settled, and followed from then on. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class AppShellViewModelTest { + + private class FakeShellMode(initial: ShellState) : ShellModeSource { + val stored = MutableStateFlow(initial) + val calls = mutableListOf() + + override val state: Flow = stored.onStart { calls += "state" } + override suspend fun current(): ShellState = stored.value.also { calls += "current" } + override val syncArming: Flow = emptyFlow() + override suspend fun hold() { + stored.value = stored.value.copy(held = true) + } + override suspend fun release() { + stored.value = stored.value.copy(held = false) + } + override suspend fun settleColdStart(): ShellState { + calls += "settle" + if (stored.value.mode == ShellMode.NONE) stored.value = stored.value.copy(held = false) + return stored.value + } + } + + private class FakeSettings : SettingsRepository by unused() { + override val settings: Flow = MutableStateFlow(AppSettings()) + } + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + /** #151, end to end through the view model: diary and no class is the diary home. */ + @Test + fun `a diary without a class is the diary home, not the join screen`() { + val source = FakeShellMode(ShellState(ShellMode.DIARY, held = false)) + val model = AppShellViewModel(source, FakeSettings(), AppShellViewModel.ColdStart()) + + val shell = model.uiState.value.shell + assertEquals(RootScreen.HOME, rootScreen(shell)) + assertEquals(ShellHome.DIARY, shell?.mode?.let(::shellHome)) + } + + @Test + fun `leaving the last class with a diary signed in moves to the diary home`() { + val source = FakeShellMode(ShellState(ShellMode.CLASS, held = false)) + val model = AppShellViewModel(source, FakeSettings(), AppShellViewModel.ColdStart()) + assertEquals(ShellMode.CLASS, model.uiState.value.shell?.mode) + + source.stored.value = ShellState(ShellMode.DIARY, held = false) + + assertEquals(ShellMode.DIARY, model.uiState.value.shell?.mode) + assertEquals(RootScreen.HOME, rootScreen(model.uiState.value.shell)) + } + + /** + * A hold left by a flow whose credential never landed is dropped before the + * gate reads anything — and only once per process: the activity is rebuilt + * on every rotation, and the hold a running onboarding has just set must + * survive that. + */ + @Test + fun `the cold start is settled once per process, before the first read`() { + val source = FakeShellMode(ShellState(ShellMode.NONE, held = true)) + val process = AppShellViewModel.ColdStart() + + val first = AppShellViewModel(source, FakeSettings(), process) + assertEquals("settle", source.calls.first()) + assertEquals(ShellState(ShellMode.NONE, held = false), first.uiState.value.shell) + + source.stored.value = ShellState(ShellMode.NONE, held = true) + val rebuilt = AppShellViewModel(source, FakeSettings(), process) + + assertEquals(1, source.calls.count { it == "settle" }) + assertEquals(ShellState(ShellMode.NONE, held = true), rebuilt.uiState.value.shell) + assertEquals(RootScreen.ONBOARDING, rootScreen(rebuilt.uiState.value.shell)) + } +} + +/** A delegate for the members a fake does not override: a call to one is a test bug. */ +private inline fun unused(): T = java.lang.reflect.Proxy.newProxyInstance( + T::class.java.classLoader, + arrayOf(T::class.java), +) { _, method, _ -> error("${T::class.simpleName}.${method.name} was not expected here") } as T diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalogTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalogTest.kt new file mode 100644 index 00000000..2afc40c3 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCatalogTest.kt @@ -0,0 +1,96 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * What the screens read out of the bundled catalog — against the real file, + * `server/app/catalog/data/regions.json`, the one the APK carries. + * + * The host is the part that matters: the sign-in form names the one host the + * password will go to, the privacy policy promises that it does, and a host + * read differently from how the sign-in's allow-list reads it would be a + * promise about a server the password never reaches. + */ +class DiaryCatalogTest { + + private val catalog: RegionCatalog by lazy { RegionCatalog.parse(catalogFile().readText()) } + + @Test + fun `the form names Petersburg's diary host`() { + val place = diaryPlaceOf(catalog, DiaryTarget.petersburg("parent@example.com")) + assertEquals("dnevnik2.petersburgedu.ru", place.host) + assertEquals("Санкт-Петербург", place.regionRu) + assertEquals("Петербургское образование", place.systemRu) + } + + @Test + fun `the form names a «Сетевой город» region's own host`() { + val target = DiaryTarget.netschool("samara", 1, "Школа № 1", "ivanova", "Europe/Samara") + val place = diaryPlaceOf(catalog, target) + assertEquals("asurso.ru", place.host) + assertEquals("Samara Oblast", place.regionEn) + } + + @Test + fun `a region the catalog does not know names no host`() { + val target = DiaryTarget.netschool("atlantis", 1, null, "x", "Europe/Moscow") + assertNull(diaryPlaceOf(catalog, target).host) + } + + /** The allow-list's own rule: https, and nothing after the authority. */ + @Test + fun `only an origin the allow-list would keep names a host`() { + assertEquals("asurso.ru", httpsHostOf("https://asurso.ru")) + assertEquals("sakh.example:11111", httpsHostOf("https://sakh.example:11111")) + assertNull(httpsHostOf("http://asurso.ru")) + assertNull(httpsHostOf("https://asurso.ru/")) + assertNull(httpsHostOf("https://asurso.ru/login")) + assertNull(httpsHostOf("https://user@asurso.ru")) + assertNull(httpsHostOf("https://asurso.ru?x=1")) + assertNull(httpsHostOf("not a url")) + } + + @Test + fun `what each kind of region offers`() { + assertEquals(DiaryRegionChoice.Petersburg, diaryChoiceOf(region("saint-petersburg"))) + assertEquals(DiaryRegionChoice.NetSchool("samara", "Europe/Samara"), diaryChoiceOf(region("samara"))) + + // Госуслуги only: the browser, to the region's own site, never a form. + val tula = diaryChoiceOf(region("tula")) + assertTrue("$tula", tula is DiaryRegionChoice.Elsewhere && tula.gosuslugi) + assertEquals("https://sgo1.edu71.ru", (tula as DiaryRegionChoice.Elsewhere).url) + + // A system this app does not speak: not a form either. + assertTrue(diaryChoiceOf(region("moscow")) is DiaryRegionChoice.Elsewhere) + } + + /** + * Exactly the regions the sign-in can serve open a form — the design's + * count, one Petersburg and sixteen «Сетевой город» regions that take a + * password — so the picker never offers a form the sign-in would refuse. + */ + @Test + fun `the regions that open a form are exactly the signable ones`() { + val choices = catalog.regions.map(::diaryChoiceOf) + assertEquals(1, choices.count { it == DiaryRegionChoice.Petersburg }) + assertEquals(16, choices.count { it is DiaryRegionChoice.NetSchool }) + } + + private fun region(key: String) = checkNotNull(catalog.region(key)) { "no region $key" } + + private fun catalogFile(): File { + var directory: File? = File("").absoluteFile + while (directory != null) { + val file = File(directory, "server/app/catalog/data/regions.json") + if (file.isFile) return file + directory = directory.parentFile + } + error("regions.json not found from ${File("").absolutePath}") + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt new file mode 100644 index 00000000..1c885b40 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt @@ -0,0 +1,138 @@ +package com.lumenpearson.lessons.ui.diary + +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onLast +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The diary as a home, composed: what the home leaves out, what the account + * page in settings holds instead, and the sentences a failed read now says. + * + * #151 is the reason the account page matters. A phone signed in to a diary + * and in no class used to land on the join screen, where neither the diary nor + * «Выйти из дневника» could be reached; now it lands on the diary, and the way + * out of it is this page's. + */ +// marquee clock: this one *cannot* hold it. It reaches the account page's rows +// and the section's sign-out with `performScrollTo`, which drives the list's own +// animation and moves nothing while the clock is held — every row below the +// fold would then read as absent, which is the thing these tests assert about. +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp-h1200dp") +class DiaryHomeScreenTest { + + @get:Rule val compose = createComposeRule() + + private val pupil = DiaryStudent( + id = 1, + firstName = "Пётр", + lastName = "Иванов", + middleName = null, + fullName = "Иванов Пётр Сергеевич", + school = "Школа № 5", + className = "7А", + ) + + private val repository = FakeDiaryRepository().apply { + students = listOf(pupil) + sessions.value = DiarySession( + login = "ivanova", + token = "t", + target = DiaryTarget.netschool("samara", 5, "Школа № 5", "ivanova", "Europe/Samara"), + ) + } + + private fun model() = DiaryViewModel(repository) + + @Test + fun `the diary home carries no tab switch and no sign-out of its own`() { + val model = model() + compose.setContent { + LessonsTheme { DiaryScreen(asHome = true, viewModel = model) } + } + + compose.onNodeWithText("Иванов Пётр Сергеевич").assertIsDisplayed() + // The toolbar carries «Расписание» and «Оценки» on the home. + compose.onAllNodesWithText("Оценки").assertCountEquals(0) + compose.onAllNodesWithText("Выйти из дневника").assertCountEquals(0) + } + + @Test + fun `the section in a class keeps both`() { + val model = model() + compose.setContent { + LessonsTheme { DiaryScreen(asHome = false, viewModel = model) } + } + + compose.onAllNodesWithText("Оценки").assertCountEquals(1) + compose.onNodeWithText("Выйти из дневника").performScrollTo().assertIsDisplayed() + } + + @Test + fun `the account page reaches the sign-out, and says the phone goes back to the start`() { + val model = model() + compose.setContent { + LessonsTheme { DiaryAccountPage(viewModel = model) } + } + + compose.onNodeWithText("ivanova").performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Подключиться к классу по коду").performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Выйти из дневника").performScrollTo().performClick() + compose.onNodeWithText("Телефон вернётся к началу", substring = true).assertIsDisplayed() + + compose.onAllNodesWithText("Выйти из дневника").onLast().performClick() + compose.waitForIdle() + assertNull(repository.sessions.value) + } + + /** + * The card under a week that could not be read. It said «Дневник не + * отвечает. Попробуйте позже.» for a throttle and for a diary switched off + * on the server alike (#153), and offered «Повторить» for both. + */ + @Test + fun `a throttled read says so, and offers no retry`() { + compose.setContent { + LessonsTheme { DiaryFailureCard(DiaryFailure.Throttled(retryAfterSeconds = 120), onRetry = {}) } + } + + compose.onNodeWithText("Слишком много попыток. Попробуйте снова через 2 минуты.").assertIsDisplayed() + compose.onAllNodesWithText("Повторить").assertCountEquals(0) + } + + @Test + fun `a diary switched off on the server says so, and offers no retry`() { + compose.setContent { + LessonsTheme { DiaryFailureCard(DiaryFailure.Disabled, onRetry = {}) } + } + + compose.onNodeWithText("Дневник выключен на этом сервере", substring = true).assertIsDisplayed() + compose.onAllNodesWithText("Повторить").assertCountEquals(0) + } + + @Test + fun `a diary that is down still offers a retry`() { + compose.setContent { + LessonsTheme { DiaryFailureCard(DiaryFailure.Unavailable, onRetry = {}) } + } + + compose.onNodeWithText("Дневник не отвечает. Попробуйте позже.").assertIsDisplayed() + compose.onNodeWithText("Повторить").assertIsDisplayed() + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOfflineSeedTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOfflineSeedTest.kt new file mode 100644 index 00000000..78f8f908 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOfflineSeedTest.kt @@ -0,0 +1,249 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiaryLesson +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.io.IOException +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZoneOffset +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The diary drawn from what the phone saved: before the network answers, + * instead of asking again while the save is fresh, and in place of a failure + * card when the diary cannot be reached. + * + * This is what makes the diary a home a phone can open on a train. Before the + * cache, every visit was a live read, so a family with no signal saw «Нет + * связи» over a week they had looked at an hour earlier; and the import that + * fills the phone would have been repeated, request for request, by the first + * screen it landed on. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DiaryOfflineSeedTest { + + private val now: Instant = Instant.parse("2026-09-23T09:00:00Z") + private val clock: Clock = Clock.fixed(now, ZoneOffset.UTC) + private val monday: LocalDate = LocalDate.of(2026, 9, 21) + + private val pupil = DiaryStudent( + id = 1, + firstName = "Пётр", + lastName = "Иванов", + middleName = null, + fullName = "Иванов Пётр", + school = null, + className = null, + ) + + private fun lesson(subject: String) = DiaryLesson( + date = monday, + number = 1, + subject = subject, + startsAt = null, + endsAt = null, + room = null, + teacher = null, + homework = null, + topic = null, + ) + + private val repository = FakeDiaryRepository().apply { + students = listOf(pupil) + sessions.value = DiarySession( + login = "parent@example.com", + token = "t", + target = DiaryTarget.petersburg("parent@example.com"), + ) + } + private val cache = FakeDiaryCache() + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun model() = DiaryViewModel(repository, cache = cache, clock = clock) + + private fun subjects(model: DiaryViewModel) = + model.uiState.value.days.flatMap { day -> day.lessons.map { it.subject } } + + @Test + fun `the home draws what was saved before the network answers`() { + cache.saveStudents(listOf(pupil), at = now.minus(Duration.ofHours(3))) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = now.minus(Duration.ofHours(3))) + repository.lessons = listOf(lesson("Физика")) + val gate = CompletableDeferred() + repository.scheduleGate = gate + + val model = model() + + assertEquals(listOf("Алгебра"), subjects(model)) + assertEquals(false, model.uiState.value.scheduleLoading) + + gate.complete(Unit) + assertEquals(listOf("Физика"), subjects(model)) + } + + @Test + fun `a save younger than half an hour is not fetched again`() { + cache.saveStudents(listOf(pupil), at = now.minus(Duration.ofMinutes(5))) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = now.minus(Duration.ofMinutes(5))) + + val model = model() + + assertEquals(listOf("Алгебра"), subjects(model)) + assertEquals("the saved week was fresh", 0, repository.reloads) + assertEquals("so were the saved pupils", 0, repository.studentReads) + } + + @Test + fun `offline with a save keeps the rows and says when they were saved`() { + val savedAt = now.minus(Duration.ofHours(2)) + cache.saveStudents(listOf(pupil), at = now.minus(Duration.ofMinutes(1))) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = savedAt) + repository.scheduleFailure = DiaryFailure.Offline(IOException("no route")) + + val model = model() + + assertEquals(1, repository.reloads) + assertEquals(listOf("Алгебра"), subjects(model)) + assertNull(model.uiState.value.scheduleError) + assertEquals(savedAt, model.uiState.value.savedAt) + } + + @Test + fun `offline with nothing saved shows the failure card`() { + repository.scheduleFailure = DiaryFailure.Offline(IOException("no route")) + + val model = model() + + assertTrue(model.uiState.value.scheduleError is DiaryFailure.Offline) + assertNull(model.uiState.value.savedAt) + } + + /** + * Not every failure may hide behind the save: a diary switched off on the + * server will not come back by waiting, and saying «нет связи» over old + * rows would be the wrong sentence about the wrong problem. + */ + @Test + fun `a switched-off diary is said even over a save`() { + cache.saveStudents(listOf(pupil), at = now) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = now.minus(Duration.ofHours(2))) + repository.scheduleFailure = DiaryFailure.Disabled + + val model = model() + + assertEquals(DiaryFailure.Disabled, model.uiState.value.scheduleError) + } + + /** + * A correction is applied by the server, so the read that follows a save + * has to reach it — a fresh save holds the rows from before the correction. + */ + @Test + fun `a refresh goes to the diary even when the save is fresh`() { + cache.saveStudents(listOf(pupil), at = now) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = now) + val model = model() + assertEquals(0, repository.reloads) + + model.refresh() + + assertEquals(1, repository.reloads) + } + + @Test + fun `the pupil shown is the one chosen before`() { + val sister = pupil.copy(id = 2, firstName = "Анна", fullName = "Иванова Анна") + repository.students = listOf(pupil, sister) + cache.saveStudents(listOf(pupil, sister), at = now) + cache.selected.value = sister.id + + val model = model() + + assertEquals(sister.id, model.uiState.value.selectedStudentId) + } + + @Test + fun `a child picked on screen is kept for the next launch`() { + val sister = pupil.copy(id = 2, firstName = "Анна", fullName = "Иванова Анна") + repository.students = listOf(pupil, sister) + val model = model() + + model.selectStudent(sister.id) + + assertEquals(sister.id, cache.selected.value) + } + + /** + * The home's start refresh and the screen's own load would otherwise both + * read this week on every cold start. The load waits for the refresh and + * finds the week it saved fresh. + */ + @Test + fun `the start refresh and the screen do not both read the week`() { + // A dispatcher that runs nothing until told: on a phone the screen's + // load suspends on the database before it reaches the network, and the + // start effect registers the refresh in that gap. + val main = StandardTestDispatcher() + Dispatchers.setMain(main) + cache.saveStudents(listOf(pupil), at = now) + cache.saveWeek(pupil.id, monday, listOf(lesson("Алгебра")), at = now.minus(Duration.ofHours(2))) + val refresh = CompletableDeferred>() + val model = model() + model.refreshOnStart { refresh.await() } + main.scheduler.runCurrent() + assertEquals("the load waits for the refresh", 0, repository.reloads) + + // What `refreshIfStale` does: read the week, which writes it through. + cache.saveWeek(pupil.id, monday, listOf(lesson("Физика")), at = now) + refresh.complete(Result.success(true)) + main.scheduler.advanceUntilIdle() + + assertEquals("nothing read the week a second time", 0, repository.reloads) + assertEquals(listOf("Физика"), subjects(model)) + } + + @Test + fun `the week is the session's week, in the session's zone`() { + // 20:00 UTC on Sunday is already Monday in Tomsk (UTC+7). + val sundayEvening = Clock.fixed(Instant.parse("2026-09-27T20:00:00Z"), ZoneOffset.UTC) + repository.sessions.value = DiarySession( + login = "pupil", + token = "t", + target = DiaryTarget.netschool("tomsk", 1, null, "pupil", "Asia/Tomsk"), + ) + + val model = DiaryViewModel(repository, cache = cache, clock = sundayEvening) + + assertEquals(ZoneId.of("Asia/Tomsk"), model.uiState.value.zone) + assertEquals(LocalDate.of(2026, 9, 28), model.uiState.value.weekStart) + assertNotNull(model.uiState.value.session) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerViewModelTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerViewModelTest.kt new file mode 100644 index 00000000..42dc2af2 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPickerViewModelTest.kt @@ -0,0 +1,132 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.catalog.CatalogNetSchool +import com.lumenpearson.lessons.core.data.catalog.CatalogRecommendation +import com.lumenpearson.lessons.core.data.catalog.CatalogRegion +import com.lumenpearson.lessons.core.data.catalog.CatalogSystem +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.data.upstream.DiarySchoolSearch +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * The diary picker: a region, then — for a «Сетевой город» region — a school, + * and the answer is the diary to sign in to, with no login and nothing secret. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DiaryPickerViewModelTest { + + private val main = StandardTestDispatcher() + + private val petersburg = CatalogRegion( + key = "saint-petersburg", + nameRu = "Санкт-Петербург", + nameEn = "Saint Petersburg", + recommended = CatalogRecommendation(platform = "petersburg", system = 0), + systems = listOf(CatalogSystem(platform = "petersburg", action = "signin")), + ) + private val samara = CatalogRegion( + key = "samara", + nameRu = "Самарская область", + nameEn = "Samara Oblast", + zone = "Europe/Samara", + recommended = CatalogRecommendation(platform = "netschool", system = 0), + systems = listOf( + CatalogSystem( + platform = "netschool", + action = "signin", + netschool = CatalogNetSchool("samara", "https://asurso.ru", password = true, zone = "Europe/Samara"), + ), + ), + ) + + private val asked = mutableListOf>() + private var answer: Result> = Result.success(listOf(DiarySchool(77, "Школа № 7", "ул. Ленина, 1"))) + + private fun model() = DiaryPickerViewModel( + regions = { query -> listOf(petersburg, samara).filter { query.isBlank() || it.nameRu.contains(query) } }, + schools = { region, query -> + asked += region to query + answer + }, + ) + + @Before + fun setUp() { + Dispatchers.setMain(main) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `Petersburg is answered the moment it is tapped`() { + val model = model() + main.scheduler.advanceUntilIdle() + + model.pickRegion(model.state.value.regions.first { it.key == "saint-petersburg" }) + + assertEquals(DiaryTarget.petersburg(""), model.state.value.picked) + } + + @Test + fun `a «Сетевой город» region asks its own server for schools, after the typing stops`() { + val model = model() + main.scheduler.advanceUntilIdle() + model.pickRegion(model.state.value.regions.first { it.key == "samara" }) + assertNull(model.state.value.picked) + + model.searchSchools("Ш") + model.searchSchools("Шк") + model.searchSchools("Школа 7") + main.scheduler.advanceTimeBy(DiarySchoolSearch.DEBOUNCE_MILLIS - 1) + main.scheduler.runCurrent() + assertEquals("nothing asked while typing", emptyList>(), asked) + + main.scheduler.advanceUntilIdle() + assertEquals(listOf("samara" to "Школа 7"), asked) + + model.pickSchool(model.state.value.schools.single()) + assertEquals( + DiaryTarget.netschool("samara", 77, "Школа № 7", login = "", zone = "Europe/Samara"), + model.state.value.picked, + ) + } + + @Test + fun `a one-letter query asks nobody`() { + val model = model() + main.scheduler.advanceUntilIdle() + model.pickRegion(model.state.value.regions.first { it.key == "samara" }) + + model.searchSchools("Ш") + main.scheduler.advanceUntilIdle() + + assertEquals(emptyList>(), asked) + } + + @Test + fun `a region server that refuses the phone is said in the diary's words`() { + answer = Result.failure(DiarySignInProblem.ProviderRefusesPhone("asurso.ru")) + val model = model() + main.scheduler.advanceUntilIdle() + model.pickRegion(model.state.value.regions.first { it.key == "samara" }) + + model.searchSchools("Школа") + main.scheduler.advanceUntilIdle() + + assertEquals(DiarySignInProblem.ProviderRefusesPhone("asurso.ru"), model.state.value.problem) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentationTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentationTest.kt index 7bb11665..094e0b10 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentationTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryPresentationTest.kt @@ -6,10 +6,12 @@ import com.lumenpearson.lessons.core.data.repository.DiaryLesson import com.lumenpearson.lessons.core.data.repository.DiaryMark import com.lumenpearson.lessons.core.data.repository.DiaryMarkKind import com.lumenpearson.lessons.core.data.repository.DiaryPeriod +import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.Clock import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime +import java.time.ZoneId import java.time.ZoneOffset import org.junit.Assert.assertEquals import org.junit.Assert.assertNull @@ -196,18 +198,41 @@ class DiaryPresentationTest { // device's own clock, on a phone left in another zone, has not reached — // and the server cuts its default window at the same boundary, so a // screen that disagreed would look like the diary had lost a day. + val moscow = ZoneId.of("Europe/Moscow") val justAfterMidnightThere = Clock.fixed( LocalDateTime.of(2026, 9, 7, 21, 30).toInstant(ZoneOffset.UTC), ZoneOffset.UTC, ) - assertEquals(LocalDate.of(2026, 9, 8), diaryToday(justAfterMidnightThere)) + assertEquals(LocalDate.of(2026, 9, 8), diaryToday(moscow, justAfterMidnightThere)) // And the hours on either side of it still resolve the ordinary way. val teaTimeThere = Clock.fixed( LocalDateTime.of(2026, 9, 7, 12, 0).toInstant(ZoneOffset.UTC), ZoneOffset.UTC, ) - assertEquals(LocalDate.of(2026, 9, 7), diaryToday(teaTimeThere)) + assertEquals(LocalDate.of(2026, 9, 7), diaryToday(moscow, teaTimeThere)) + } + + /** + * The zone is the session's, not Moscow's: a «Сетевой город» pupil in Tomsk + * (UTC+7) is past midnight four hours before Moscow is, and a diary that + * cut the day in Moscow opened on yesterday for those four hours. + */ + @Test + fun `a Tomsk session cuts the day at Tomsk midnight`() { + val tomsk = DiaryTarget.netschool( + region = "tomsk", + schoolId = 1, + schoolName = null, + login = "pupil", + zone = "Asia/Tomsk", + ).zoneId() + val eveningInMoscow = Clock.fixed( + LocalDateTime.of(2026, 9, 7, 18, 30).toInstant(ZoneOffset.UTC), + ZoneOffset.UTC, + ) + assertEquals(LocalDate.of(2026, 9, 8), diaryToday(tomsk, eveningInMoscow)) + assertEquals(LocalDate.of(2026, 9, 7), diaryToday(ZoneId.of("Europe/Moscow"), eveningInMoscow)) } // -- the marks window --------------------------------------------------- diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt new file mode 100644 index 00000000..abb18fe3 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt @@ -0,0 +1,148 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.Counted +import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.Line +import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.WithUpstream +import java.io.IOException +import java.net.SocketTimeoutException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Which sentence each way of not getting into the diary gets. + * + * The screen half of #153: the data layer had learnt to tell a throttle, a + * diary switched off on the server and a server the diary refuses from «не + * отвечает», and the screen still said «Дневник не отвечает. Попробуйте позже.» + * for all three, because the bridge it went through had no member for them. The + * one mapping is now `diaryProblemMessage`, and these are its cases. + */ +class DiaryProblemTextTest { + + private val host = "asurso.ru" + + @Test + fun `too many attempts reads as too many attempts, with the wait when there is one`() { + assertEquals(Line(R.string.diary_problem_too_many), diaryProblemMessage(DiarySignInProblem.TooManyAttempts(null))) + assertEquals( + Counted(R.plurals.diary_problem_too_many_wait, 2), + diaryProblemMessage(DiarySignInProblem.TooManyAttempts(retryAfterSeconds = 61)), + ) + // Forty seconds is «через 1 минуту», never «через 0 минут». + assertEquals( + Counted(R.plurals.diary_problem_too_many_wait, 1), + diaryProblemMessage(DiarySignInProblem.TooManyAttempts(retryAfterSeconds = 40)), + ) + } + + @Test + fun `a diary switched off on the server reads as switched off`() { + assertEquals(Line(R.string.diary_problem_server_disabled), diaryProblemMessage(DiarySignInProblem.ServerDisabled)) + } + + @Test + fun `a refused server address reads as the diary refusing our server`() { + assertEquals( + Line(R.string.diary_problem_server_address_refused), + diaryProblemMessage(DiarySignInProblem.ServerAddressRefused), + ) + } + + @Test + fun `a timeout reads as a timeout, naming the diary when it was the diary`() { + assertEquals(Line(R.string.diary_problem_host_timeout, listOf(host)), diaryProblemMessage(DiarySignInProblem.Timeout(host))) + assertEquals(Line(R.string.diary_problem_timeout), diaryProblemMessage(DiarySignInProblem.Timeout(null))) + } + + @Test + fun `every problem that carries the diary's host says it`() { + val hosted = listOf( + DiarySignInProblem.ProviderUnavailable(host), + DiarySignInProblem.ProviderRefusesPhone(host), + DiarySignInProblem.ProviderUntrusted(host), + DiarySignInProblem.ProviderUnreadable(host), + DiarySignInProblem.ProviderOffline(host), + DiarySignInProblem.Timeout(host), + ) + for (problem in hosted) { + val message = diaryProblemMessage(problem) + assertTrue("$problem names no host: $message", message is Line && message.args == listOf(host)) + } + } + + /** + * Every member, and no two sharing a sentence unless they mean the same + * thing to the person reading. A new member fails to compile in the + * mapping; this is what says its sentence is its own. + */ + @Test + fun `every problem has a sentence of its own`() { + val all = listOf( + DiarySignInProblem.WrongPassword(null), + DiarySignInProblem.GosuslugiOnly(null), + DiarySignInProblem.ProviderUnavailable(null), + DiarySignInProblem.ProviderRefusesPhone(null), + DiarySignInProblem.ProviderUntrusted(null), + DiarySignInProblem.ProviderUnreadable(null), + DiarySignInProblem.ProviderOffline(null), + DiarySignInProblem.Timeout(null), + DiarySignInProblem.Offline, + DiarySignInProblem.RegisterUnreachable, + DiarySignInProblem.ServerMissing, + DiarySignInProblem.ServerTooOld, + DiarySignInProblem.ServerDisabled, + DiarySignInProblem.RegionNotServed, + DiarySignInProblem.ServerRefusedSession, + DiarySignInProblem.ServerAddressRefused, + DiarySignInProblem.NoStudent, + DiarySignInProblem.TooManyAttempts(null), + DiarySignInProblem.SessionAgedOut, + DiarySignInProblem.LoginTooShort, + DiarySignInProblem.ReauthRequired, + DiarySignInProblem.SignInRequired, + ) + val ids = all.map { (diaryProblemMessage(it) as Line).id } + assertEquals("two problems share a sentence: $all", ids.size, ids.toSet().size) + } + + @Test + fun `what the diary said about a refused password is shown beside it`() { + assertEquals(Line(R.string.diary_problem_wrong_password), diaryProblemMessage(DiarySignInProblem.WrongPassword(null))) + assertEquals( + WithUpstream(Line(R.string.diary_problem_wrong_password), "Учётная запись заблокирована"), + diaryProblemMessage(DiarySignInProblem.WrongPassword(" Учётная запись заблокирована ")), + ) + } + + /** + * The read side: a failed read of a week goes through the same mapping, so + * the failure card under a week says what the sign-in form would. + */ + @Test + fun `a failed read is the problem it means`() { + assertEquals(DiarySignInProblem.TooManyAttempts(30), DiaryFailure.Throttled(30).asProblem()) + assertEquals(DiarySignInProblem.ServerDisabled, DiaryFailure.Disabled.asProblem()) + assertEquals(DiarySignInProblem.ServerAddressRefused, DiaryFailure.ServerAddressRefused.asProblem()) + assertEquals(DiarySignInProblem.Timeout(null), DiaryFailure.Offline(SocketTimeoutException("slow")).asProblem()) + assertEquals(DiarySignInProblem.Offline, DiaryFailure.Offline(IOException("no route")).asProblem()) + // What this app asked wrongly keeps its own sentence. + assertNull(DiaryFailure.BadRange.asProblem()) + assertNull(DiaryFailure.Rejected.asProblem()) + assertNull(DiaryFailure.UnknownStudent.asProblem()) + } + + @Test + fun `retry is offered only where the data layer says it can help`() { + assertTrue(DiarySignInProblem.Offline.offersRetry) + assertTrue(DiarySignInProblem.Timeout(host).offersRetry) + assertFalse(DiarySignInProblem.ServerDisabled.offersRetry) + assertFalse(DiarySignInProblem.ServerAddressRefused.offersRetry) + assertFalse(DiarySignInProblem.TooManyAttempts(60).offersRetry) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt index ed275647..4f544c1e 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiarySignInOutcomeTest.kt @@ -1,11 +1,14 @@ package com.lumenpearson.lessons.ui.diary +import com.lumenpearson.lessons.core.data.repository.DiaryBinding import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryTarget import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -61,12 +64,12 @@ class DiarySignInOutcomeTest { val outcome = model.uiState.value.signInOutcome assertTrue("expected a failure, got $outcome", outcome is DiarySignInOutcome.Failed) assertEquals( - DiaryFailure.SignInRequired, - (outcome as DiarySignInOutcome.Failed).failure, + DiarySignInProblem.WrongPassword(null), + (outcome as DiarySignInOutcome.Failed).problem, ) // And the form still knows to paint itself red, which is the half that // survives dismissing the pop-up. - assertEquals(DiaryFailure.SignInRequired, model.uiState.value.signInError) + assertEquals(DiarySignInProblem.WrongPassword(null), model.uiState.value.signInError) } @Test @@ -80,7 +83,7 @@ class DiarySignInOutcomeTest { model.signIn("parent@example.com", "correct-horse") assertEquals( - DiarySignInOutcome.Failed(DiaryFailure.Unavailable), + DiarySignInOutcome.Failed(DiarySignInProblem.ProviderUnavailable("dnevnik2.petersburgedu.ru")), model.uiState.value.signInOutcome, ) } @@ -113,7 +116,7 @@ class DiarySignInOutcomeTest { assertNull(model.uiState.value.signInOutcome) // Dismissing the pop-up is not the same as fixing the form: the fields // stay red until something is typed into them. - assertEquals(DiaryFailure.SignInRequired, model.uiState.value.signInError) + assertEquals(DiarySignInProblem.WrongPassword(null), model.uiState.value.signInError) } @Test @@ -126,7 +129,7 @@ class DiarySignInOutcomeTest { model.signIn("parent@example.com", "wrong") assertEquals( - DiarySignInOutcome.Failed(DiaryFailure.SignInRequired), + DiarySignInOutcome.Failed(DiarySignInProblem.WrongPassword(null)), model.uiState.value.signInOutcome, ) } @@ -162,6 +165,12 @@ class DiarySignInOutcomeTest { assertEquals(listOf(kept), repository.signedInTo) } + /** + * The problem arrives whole, not squeezed into the older failure type: a + * throttle, a diary switched off on the server and a server refused by the + * diary each used to read «дневник не отвечает» here (#153), because the + * bridge this replaced had no member for them. + */ @Test fun `too many attempts is not reported as a wrong password`() { repository.signInResult = Result.failure(DiarySignInProblem.TooManyAttempts(retryAfterSeconds = 60)) @@ -170,8 +179,62 @@ class DiarySignInOutcomeTest { model.signIn("parent@example.com", "wrong") assertEquals( - DiarySignInOutcome.Failed(DiaryFailure.Throttled(retryAfterSeconds = 60)), + DiarySignInOutcome.Failed(DiarySignInProblem.TooManyAttempts(retryAfterSeconds = 60)), model.uiState.value.signInOutcome, ) } + + @Test + fun `a diary switched off on the server stays switched off, not unavailable`() { + for (problem in listOf(DiarySignInProblem.ServerDisabled, DiarySignInProblem.ServerAddressRefused)) { + repository.signInResult = Result.failure(problem) + val model = model() + + model.signIn("parent@example.com", "correct-horse") + + assertEquals(DiarySignInOutcome.Failed(problem), model.uiState.value.signInOutcome) + } + } + + /** + * A diary picked on the form wins over everything the phone knew before — + * that is what picking is for — and is forgotten once the sign-in lands, so + * the next form is about the account that is now stored. + */ + @Test + fun `a diary picked on the form is the one signed in to`() { + val picked = DiaryTarget.netschool( + region = "samara", + schoolId = 77, + schoolName = "Школа № 7", + login = "", + zone = "Europe/Samara", + ) + repository.targets.value = DiaryTarget.petersburg("someone@example.com") + val model = model() + + model.startPicking() + model.choose(picked) + assertEquals(picked, model.uiState.value.signInTarget) + model.signIn("ivanova", "correct-horse") + + assertEquals(listOf(picked.copy(login = "ivanova")), repository.signedInTo) + assertEquals(false, model.uiState.value.picking) + } + + /** A class whose join named its diary is signed in to without searching (r11 gap 2). */ + @Test + fun `a class bound to a diary signs in to that diary`() { + val binding = DiaryBinding( + provider = DiaryProviderKey.NETSCHOOL, + region = "samara", + schoolId = 5, + schoolName = "Лицей", + ) + val model = DiaryViewModel(repository, binding = flowOf(binding)) + + model.signIn("ivanova", "correct-horse") + + assertEquals(listOf(binding.targetFor("ivanova")), repository.signedInTo) + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryCache.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryCache.kt new file mode 100644 index 00000000..aeba505b --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryCache.kt @@ -0,0 +1,69 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.diary.DiaryCache +import com.lumenpearson.lessons.core.data.diary.DiaryCachedMarks +import com.lumenpearson.lessons.core.data.diary.DiaryCachedPeriods +import com.lumenpearson.lessons.core.data.diary.DiaryCachedStudents +import com.lumenpearson.lessons.core.data.diary.DiaryCachedWeek +import com.lumenpearson.lessons.core.data.repository.DiaryHomework +import com.lumenpearson.lessons.core.data.repository.DiaryLesson +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import java.time.Instant +import java.time.LocalDate +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map + +/** + * What the phone saved, as the diary view model reads it — set by hand. + * + * The real cache is written only by the repository's reads (write-through), + * and `:core:data`'s own tests hold that; what the screen's tests ask is what + * the view model does with a save it is handed, so the save is arranged here + * directly. + */ +internal class FakeDiaryCache : DiaryCache { + + val saved = MutableStateFlow(DiaryCachedStudents(emptyList(), loadedAt = null)) + val selected = MutableStateFlow(null) + val weeks = mutableMapOf, DiaryCachedWeek>() + var savedMarks: DiaryCachedMarks = DiaryCachedMarks(null, null, emptyList(), null) + var savedPeriods: DiaryCachedPeriods = DiaryCachedPeriods(emptyList(), null) + + fun saveStudents(students: List, at: Instant) { + saved.value = DiaryCachedStudents(students, at) + } + + fun saveWeek( + studentId: Long, + monday: LocalDate, + lessons: List, + at: Instant, + homework: List = emptyList(), + ) { + weeks[studentId to monday] = DiaryCachedWeek(monday, lessons, homework, at, at) + } + + override val students: Flow = saved + override val selectedStudentId: Flow = selected + + override suspend fun selectStudent(id: Long?) { + selected.value = id + } + + override fun week(studentId: Long, monday: LocalDate): Flow = + saved.map { + weeks[studentId to monday] ?: DiaryCachedWeek(monday, emptyList(), emptyList(), null, null) + } + + override fun marks(studentId: Long): Flow = flowOf(savedMarks) + + override fun periods(studentId: Long): Flow = flowOf(savedPeriods) + + override suspend fun clear() { + saved.value = DiaryCachedStudents(emptyList(), null) + weeks.clear() + selected.value = null + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt index cf8c2943..f918c9f4 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/FakeDiaryRepository.kt @@ -12,6 +12,7 @@ import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiaryStudent import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.LocalDate +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -37,6 +38,12 @@ internal data class Written( * pull the state holder into a load whose answers would have to be arranged. * @property failAfter the number of writes that succeed before [failure] is * answered instead; `null` never fails a write. + * @property lessons what a schedule read answers, when it answers. + * @property scheduleFailure when set, schedule and homework reads answer it and + * the others do not — the diary unreachable on a screen whose pupils were + * saved. + * @property scheduleGate when set, schedule reads wait for it: the network + * that has not answered yet. */ internal class FakeDiaryRepository : DiaryRepository { @@ -45,6 +52,10 @@ internal class FakeDiaryRepository : DiaryRepository { var failAfter: Int? = null var failure: DiaryFailure = DiaryFailure.Unavailable var reloads: Int = 0 + var lessons: List = emptyList() + var scheduleFailure: DiaryFailure? = null + var scheduleGate: CompletableDeferred? = null + var studentReads: Int = 0 /** What a sign-in answers; a success is also stored as the session. */ var signInResult: Result? = null @@ -97,7 +108,10 @@ internal class FakeDiaryRepository : DiaryRepository { return Result.success(Unit) } - override suspend fun students(): Result> = read(students) + override suspend fun students(): Result> { + studentReads += 1 + return read(students) + } override suspend fun schedule( studentId: Long, @@ -105,14 +119,19 @@ internal class FakeDiaryRepository : DiaryRepository { to: LocalDate, ): Result> { reloads += 1 - return read(emptyList()) + scheduleGate?.await() + scheduleFailure?.let { return Result.failure(it) } + return read(lessons) } override suspend fun homework( studentId: Long, from: LocalDate, to: LocalDate, - ): Result> = read(emptyList()) + ): Result> { + scheduleFailure?.let { return Result.failure(it) } + return read(emptyList()) + } override suspend fun grades( studentId: Long, diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt index cb85f56b..25e34a33 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTest.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.ui.join +import com.lumenpearson.lessons.core.data.network.ServerAddressMissingException import com.lumenpearson.lessons.core.data.repository.JoinFailure import java.io.IOException import org.junit.Assert.assertEquals @@ -74,4 +75,21 @@ class JoinErrorTest { assertTrue(error is JoinError.Rejected) assertEquals("airplane mode", (error as JoinError.Rejected).detail) } + + /** + * #154: a blank address used to reach the screen as the interceptor's + * English message under a Russian prefix — «Не удалось подключиться: No + * server address configured» — on a screen that had just said a default + * server was in use. + */ + @Test + fun `a missing server address is its own case, not an English message`() { + val missing = JoinError.of(JoinFailure.Offline(ServerAddressMissingException())) + assertEquals(JoinError.NoServer, missing) + + val wrapped = JoinError.of( + JoinFailure.Offline(IOException("call failed", ServerAddressMissingException())), + ) + assertEquals(JoinError.NoServer, wrapped) + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt index 56f559f7..07dc4823 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinErrorTextTest.kt @@ -86,4 +86,13 @@ class JoinErrorTextTest { // And does not invent one. compose.onNodeWithText("через", substring = true).assertDoesNotExist() } + + /** #154: the cure is the row under the button, and the sentence says so, in Russian. */ + @Test + fun `a missing server address points at the address row`() { + show(JoinError.NoServer) + + compose.onNodeWithText("Не указан адрес сервера", substring = true).assertIsDisplayed() + compose.onNodeWithText("«Адрес сервера»", substring = true).assertIsDisplayed() + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt new file mode 100644 index 00000000..bb75b0c4 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt @@ -0,0 +1,190 @@ +package com.lumenpearson.lessons.ui.onboarding + +import com.lumenpearson.lessons.core.data.catalog.MatchVia +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The region, school and provider steps against the catalog the APK carries. + * + * The screens read the generator's answers — `recommended`, `action`, `role` — + * and only filter and name them (K18). These tests hold the filtering and the + * few rules the phone adds: where a school step is shown, what can be signed + * into, where a handoff goes, and that none of it names anything but https. + */ +class OnboardingCatalogTest { + + @Test + fun `the school step is shown only where the signable diary lists its schools`() { + val shown = realCatalog.regions.filter { regionPlanOf(it).showsSchool }.map { it.key } + assertEquals(16, shown.size) + assertTrue("samara" in shown) + assertFalse("saint-petersburg" in shown) + assertFalse("tula" in shown) + assertEquals(realCatalog.regions.size - 16, realCatalog.regions.count { !regionPlanOf(it).showsSchool }) + } + + @Test + fun `only Petersburg and the sixteen password regions can be signed into`() { + val signable = realCatalog.regions.filter { regionPlanOf(it).signable }.map { it.key } + assertEquals(17, signable.size) + assertTrue("saint-petersburg" in signable) + } + + @Test + fun `no region has more than one signable diary`() { + for (entry in realCatalog.regions) { + assertTrue(entry.key, entry.systems.count(::isSignable) <= 1) + } + } + + @Test + fun `at most one row is recommended, and every page builds`() { + for (entry in realCatalog.regions) { + val page = providerPageOf(realCatalog, entry, school = null) + assertTrue(entry.key, page.rows.count { it.recommended } <= 1) + assertTrue(entry.key, page.rows.isNotEmpty()) + } + } + + @Test + fun `TOR is never offered where the catalog says the region is not on it`() { + for (entry in realCatalog.regions.filter { it.tor == "absent" }) { + val page = providerPageOf(realCatalog, entry, school = null) + assertTrue(entry.key, page.rows.none { it.platform == "tor-myschool" && !it.recommended }) + } + } + + @Test + fun `legacy, unclear, portal and admissions rows are dropped`() { + for (entry in realCatalog.regions) { + val page = providerPageOf(realCatalog, entry, school = null) + for (row in page.rows.filterNot { it.recommended }) { + assertTrue("${entry.key}/${row.platform}", row.role in setOf("primary", "secondary", "migrating_to")) + val kind = realCatalog.platforms[row.platform]?.kind + assertFalse("${entry.key}/${row.platform}", kind == "portal" || kind == "admissions") + } + } + } + + @Test + fun `every link a row opens is https`() { + for (entry in realCatalog.regions) { + for (row in providerPageOf(realCatalog, entry, school = null).rows) { + row.url?.let { assertTrue("${entry.key}: $it", it.startsWith("https://")) } + if (row.kind == ProviderRowKind.HANDOFF || row.kind == ProviderRowKind.SITE) { + assertNotNull("${entry.key}/${row.platform}", row.url) + } + } + } + } + + @Test + fun `the three Gosuslugi-only regions hand off to their own origin`() { + for (key in listOf("tula", "primorye", "altai-krai")) { + val row = providerPageOf(realCatalog, region(key), school = null).rows.single { it.platform == "netschool" } + assertEquals(key, ProviderRowKind.HANDOFF, row.kind) + assertTrue(key, row.gosuslugi) + assertFalse(key, row.url.orEmpty().contains("gosuslugi.ru")) + } + val tula = providerPageOf(realCatalog, region("tula"), school = null).rows.single { it.platform == "netschool" } + assertEquals("https://sgo1.edu71.ru", tula.url) + } + + @Test + fun `TOR rows hand off to the Gosuslugi school page`() { + val row = providerPageOf(realCatalog, region("volgograd"), school = null).rows.single { it.platform == "tor-myschool" } + assertEquals(ProviderRowKind.HANDOFF, row.kind) + assertEquals("https://www.gosuslugi.ru/school", row.url) + assertTrue(row.gosuslugi) + } + + @Test + fun `the main action is the recommended row's`() { + val samara = region("samara") + val withoutSchool = providerPageOf(realCatalog, samara, school = null) + assertEquals(ProviderRowKind.NEEDS_SCHOOL, withoutSchool.main?.kind) + val withSchool = providerPageOf(realCatalog, samara, school = PickedSchool(1, "School 1")) + assertEquals(ProviderRowKind.SIGN_IN, withSchool.main?.kind) + assertEquals("asurso.ru", withSchool.main?.host) + + val petersburg = providerPageOf(realCatalog, region("saint-petersburg"), school = null) + assertEquals(ProviderRowKind.SIGN_IN, petersburg.main?.kind) + assertEquals("dnevnik2.petersburgedu.ru", petersburg.main?.host) + + // Moscow's diary is one the app cannot read; its site is what the + // main button can open. + val moscow = providerPageOf(realCatalog, region("moscow"), school = null).main + assertEquals(ProviderRowKind.SITE, moscow?.kind) + assertEquals("https://school.mos.ru", moscow?.url) + + // Paper registers leave nothing to open: the main button is the class code. + assertNull(providerPageOf(realCatalog, region("sevastopol"), school = null).main) + } + + @Test + fun `every reason and modifier the catalog uses has a sentence`() { + for (entry in realCatalog.regions) { + val recommendation = entry.recommended ?: continue + assertTrue(entry.key, WhyReason.entries.any { it.code == recommendation.reason }) + for (modifier in recommendation.modifiers) { + assertTrue("${entry.key}: $modifier", WhyModifier.entries.any { it.code == modifier }) + } + } + } + + @Test + fun `the why names a host only where the password could go`() { + assertEquals("asurso.ru", providerPageOf(realCatalog, region("samara"), null).why?.host) + assertNull(providerPageOf(realCatalog, region("tula"), null).why?.host) + assertNull(providerPageOf(realCatalog, region("moscow"), null).why?.host) + } + + @Test + fun `a class's diary is a target only where this build can sign in`() { + val petersburg = classTargetOf(realCatalog, DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + assertEquals(DiaryProviderKey.PETERSBURG, petersburg?.provider) + + val samara = classTargetOf(realCatalog, DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 12L, "School 12")) + assertEquals("Europe/Samara", samara?.zone) + assertEquals(12L, samara?.schoolId) + + assertNull(classTargetOf(realCatalog, DiaryBinding(DiaryProviderKey.NETSCHOOL, "tula", 12L, "School 12"))) + assertNull(classTargetOf(realCatalog, DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", null, null))) + assertNull(classTargetOf(realCatalog, null)) + } + + @Test + fun `a region row says why it matched and what can be done there`() { + val byCity = realSearch.search("Togliatti").ifEmpty { realSearch.search("tolyatti") } + val samaraMatch = realSearch.search("63").first { it.region.key == "samara" } + val row = regionRowOf(realCatalog, samaraMatch) + assertEquals(MatchVia.CODE, row.via) + assertEquals("63", row.matched) + assertEquals(OfferKind.SIGN_IN, row.offer.kind) + byCity.firstOrNull { it.via == MatchVia.CITY }?.let { match -> + assertTrue(regionRowOf(realCatalog, match).matched in match.region.cities) + } + + assertEquals(OfferKind.GOSUSLUGI, regionOfferOf(realCatalog, region("tula")).kind) + assertEquals(OfferKind.PAPER, regionOfferOf(realCatalog, region("sevastopol")).kind) + assertEquals(OfferKind.UNSUPPORTED, regionOfferOf(realCatalog, region("moscow")).kind) + } + + @Test + fun `the school query keeps the number, else the longest distinctive word`() { + val words = realCatalog.search.schoolWords + assertEquals("239", schoolQueryFromHint("GBOU lyceum N 239", words)) + assertEquals("", schoolQueryFromHint(null, words)) + assertEquals("", schoolQueryFromHint(" ", words)) + // Words every school has are not what tells one school from another. + val typed = words.first() + " Lomonosova" + assertEquals("Lomonosova", schoolQueryFromHint(typed, words)) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlowTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlowTest.kt new file mode 100644 index 00000000..df2f8d12 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFlowTest.kt @@ -0,0 +1,194 @@ +package com.lumenpearson.lessons.ui.onboarding + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.ACKNOWLEDGEMENT +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.CLASS_CODE +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.IMPORT +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.PERMISSIONS +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.PREFERENCES +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.PROVIDER +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.REGION +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.SCHOOL +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.SIGN_IN +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.SUMMARY +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.WAY_IN +import com.lumenpearson.lessons.ui.onboarding.OnboardingStep.WELCOME +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The flow's rules, as pure functions of its path: where it starts, how far back + * it goes, which way a step slides, and what the dots promise. + * + * The dots are the part most worth pinning. They count a chapter and they may + * only shrink as answers come in — a count that grew at the chooser would be + * the flow getting longer in front of the reader, which is exactly what the old + * five-dot row was written never to do. + */ +class OnboardingFlowTest { + + private fun path(vararg steps: OnboardingStep, floor: Int = 0, choices: OnboardingChoices = OnboardingChoices()) = + OnboardingState(path = steps.toList(), floor = floor, choices = choices) + + @Test + fun `a fresh install starts at the welcome and an introduced one at the chooser`() { + assertEquals(listOf(WELCOME), OnboardingFlow.initial(introduced = false).path) + assertEquals(listOf(WAY_IN), OnboardingFlow.initial(introduced = true).path) + } + + @Test + fun `back never goes below the floor`() { + val committed = OnboardingFlow.commit(path(WAY_IN, REGION, PROVIDER, SIGN_IN), IMPORT) + assertEquals(4, committed.floor) + assertFalse(committed.canGoBack) + assertEquals(committed, OnboardingFlow.back(committed)) + // Twice, as two back events drained in one pass would ask. + assertEquals(committed, OnboardingFlow.back(OnboardingFlow.back(committed))) + } + + @Test + fun `back on the first step is left to the system`() { + assertFalse(OnboardingFlow.initial(introduced = false).canGoBack) + assertFalse(OnboardingFlow.initial(introduced = true).canGoBack) + assertEquals(listOf(WELCOME), OnboardingFlow.back(path(WELCOME, ACKNOWLEDGEMENT)).path) + } + + @Test + fun `direction follows depth, not ordinal`() { + val provider = path(WAY_IN, REGION, PROVIDER) + val code = OnboardingFlow.push(provider, CLASS_CODE) + assertTrue(CLASS_CODE.ordinal < PROVIDER.ordinal) + assertTrue(OnboardingFlow.isForward(provider.depth, code.depth)) + assertFalse(OnboardingFlow.isForward(code.depth, OnboardingFlow.back(code).depth)) + } + + @Test + fun `the introduction is five dots and the chooser closes it`() { + val welcome = OnboardingFlow.progress(path(WELCOME), plan = null) + assertEquals(StepProgress(Chapter.INTRO, 1, 5), welcome) + + val chooser = path(WELCOME, ACKNOWLEDGEMENT, PREFERENCES, PERMISSIONS, WAY_IN) + assertEquals(StepProgress(Chapter.INTRO, 5, 5), OnboardingFlow.progress(chooser, null)) + // Answering the chooser must not grow the introduction's count. + for (way in WayIn.entries) { + val answered = chooser.copy(choices = OnboardingChoices(wayIn = way)) + assertEquals(StepProgress(Chapter.INTRO, 5, 5), OnboardingFlow.progress(answered, null)) + } + } + + @Test + fun `an introduced phone gets no dots on the chooser`() { + assertNull(OnboardingFlow.progress(OnboardingFlow.initial(introduced = true), null)) + } + + @Test + fun `an unknown region projects the longest chapter`() { + val region = path(WAY_IN, REGION) + assertEquals(StepProgress(Chapter.SCHOOL, 1, 6), OnboardingFlow.progress(region, null)) + } + + @Test + fun `choosing a region never lengthens the chapter`() { + val unknown = OnboardingFlow.progress(path(WAY_IN, REGION), null)!!.n + for (entry in realCatalog.regions) { + val plan = regionPlanOf(entry) + val n = OnboardingFlow.progress(path(WAY_IN, REGION), plan)!!.n + assertTrue("${entry.key}: $n > $unknown", n <= unknown) + } + } + + @Test + fun `an unsupported region ends the chapter at the provider step`() { + val plan = regionPlanOf(region("moscow")) + assertEquals(RegionPlan(showsSchool = false, signable = false), plan) + assertEquals(StepProgress(Chapter.SCHOOL, 1, 2), OnboardingFlow.progress(path(WAY_IN, REGION), plan)) + assertEquals(StepProgress(Chapter.SCHOOL, 2, 2), OnboardingFlow.progress(path(WAY_IN, REGION, PROVIDER), plan)) + } + + @Test + fun `k is one-based and never exceeds n along every route`() { + val routes = listOf( + listOf(WELCOME, ACKNOWLEDGEMENT, PREFERENCES, PERMISSIONS, WAY_IN, REGION, SCHOOL, PROVIDER, SIGN_IN, IMPORT, SUMMARY), + listOf(WAY_IN, REGION, PROVIDER, CLASS_CODE, SIGN_IN, IMPORT, SUMMARY), + listOf(WAY_IN, CLASS_CODE, SIGN_IN, IMPORT, SUMMARY), + listOf(IMPORT, SUMMARY), + ) + val plans = listOf(null) + realCatalog.regions.map(::regionPlanOf).distinct() + for (route in routes) { + for (plan in plans) { + for (depth in route.indices) { + val progress = OnboardingFlow.progress(OnboardingState(route.take(depth + 1)), plan) ?: continue + assertTrue("$route@$depth: $progress", progress.k in 1..progress.n) + } + } + } + } + + @Test + fun `the class-code step is uncounted and hides the hero`() { + assertNull(OnboardingFlow.progress(path(WAY_IN, CLASS_CODE), null)) + assertEquals(HeroMode.HIDDEN, OnboardingFlow.heroMode(CLASS_CODE)) + val afterJoin = OnboardingFlow.commit(path(WAY_IN, CLASS_CODE), SIGN_IN) + assertEquals(StepProgress(Chapter.CLASS, 1, 3), OnboardingFlow.progress(afterJoin, null)) + } + + @Test + fun `the search and form steps keep the dots and drop the badge`() { + for (step in listOf(REGION, SCHOOL, PROVIDER, SIGN_IN)) { + assertEquals(step.name, HeroMode.COMPACT, OnboardingFlow.heroMode(step)) + } + for (step in listOf(WELCOME, WAY_IN, IMPORT, SUMMARY)) { + assertEquals(step.name, HeroMode.FULL, OnboardingFlow.heroMode(step)) + } + } + + @Test + fun `a flow the process lost resumes from what the hold was waiting for`() { + assertEquals(listOf(IMPORT), OnboardingFlow.resume(ShellMode.DIARY, bindingUsable = false, hasDiarySession = true)?.path) + val signIn = OnboardingFlow.resume(ShellMode.CLASS, bindingUsable = true, hasDiarySession = false) + assertEquals(listOf(SIGN_IN), signIn?.path) + assertTrue(signIn!!.choices.classBound) + assertNull(OnboardingFlow.resume(ShellMode.CLASS, bindingUsable = true, hasDiarySession = true)) + assertNull(OnboardingFlow.resume(ShellMode.CLASS, bindingUsable = false, hasDiarySession = false)) + assertNull(OnboardingFlow.resume(ShellMode.NONE, bindingUsable = true, hasDiarySession = false)) + } + + @Test + fun `an import the diary ended reopens the sign-in with the floor lowered to it`() { + val importing = OnboardingFlow.commit(path(WAY_IN, REGION, PROVIDER, SIGN_IN), IMPORT) + val reopened = OnboardingFlow.reopenSignIn(importing) + assertEquals(listOf(WAY_IN, REGION, PROVIDER, SIGN_IN), reopened.path) + assertEquals(3, reopened.floor) + assertFalse(reopened.canGoBack) + + val resumed = OnboardingFlow.reopenSignIn(path(IMPORT)) + assertEquals(listOf(SIGN_IN), resumed.path) + assertEquals(0, resumed.floor) + } + + @Test + fun `the badge trail keeps a popped step until the path goes elsewhere`() { + val deep = listOf(WAY_IN, REGION, PROVIDER) + val popped = listOf(WAY_IN, REGION) + assertEquals(deep, OnboardingFlow.badgeTrail(deep, popped)) + val elsewhere = listOf(WAY_IN, REGION, SCHOOL) + assertEquals(elsewhere, OnboardingFlow.badgeTrail(deep, elsewhere)) + assertEquals(listOf(WAY_IN, CLASS_CODE), OnboardingFlow.badgeTrail(popped, listOf(WAY_IN, CLASS_CODE))) + } + + @Test + fun `a region's tail follows what it can do`() { + assertEquals( + listOf(SCHOOL, PROVIDER, SIGN_IN, IMPORT, SUMMARY), + OnboardingFlow.regionTail(regionPlanOf(region("samara"))), + ) + assertEquals( + listOf(PROVIDER, SIGN_IN, IMPORT, SUMMARY), + OnboardingFlow.regionTail(regionPlanOf(region("saint-petersburg"))), + ) + assertEquals(listOf(PROVIDER), OnboardingFlow.regionTail(regionPlanOf(region("tula")))) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt new file mode 100644 index 00000000..57e92682 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt @@ -0,0 +1,112 @@ +package com.lumenpearson.lessons.ui.onboarding + +import com.lumenpearson.lessons.core.data.repository.AppSettings +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +/** + * What the first run and its neighbours say about the app, held against what + * the app is. + * + * Read out of the source tree, as `ResourceTranslationTest` does: the question + * is about the words written, and nothing at run time would notice them being + * wrong — the screens draw a false sentence as happily as a true one. + */ +class OnboardingPromisesTest { + + private val modules = listOf("app", "core/data", "core/designsystem", "widget") + + /** Every `` and `` item in every module and language, as name to text. */ + private val shipped: List> by lazy { + modules.flatMap { module -> + File("../$module/src/main/res").listFiles { file -> file.isDirectory && file.name.startsWith("values") } + .orEmpty() + .flatMap { folder -> folder.listFiles { file -> file.name.startsWith("strings") }.orEmpty().toList() } + .flatMap { file -> + val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) + val strings = document.getElementsByTagName("string") + val items = document.getElementsByTagName("item") + (0 until strings.length).map { strings.item(it) as Element }.map { + "${file.parentFile.name}/${it.getAttribute("name")}" to it.textContent + } + (0 until items.length).map { items.item(it) as Element }.map { + "${file.parentFile.name}/plural" to it.textContent + } + } + } + } + + /** + * #154. The APK carries no server address — deliberately, no address is + * right for a second user — and three places said otherwise: the join + * screen's «По умолчанию — сервер класса», the sheet's «Меняйте только если + * школа использует свой сервер», and the settings row's «По умолчанию». A + * pupil who believed them pressed «Подключиться» on a blank address. + */ + @Test + fun `no string promises a server the app does not have`() { + assertEquals("the premise: no address is built in", "", AppSettings.DEFAULT_BASE_URL) + assertTrue("the strings were not found from ${File("").absolutePath}", shipped.size > 500) + + val promises = listOf( + "По умолчанию — сервер", + "только если школа использует свой сервер", + "прошит в сборке", + "Default — the class server", + "only if the school runs its own server", + "built into this APK", + ) + val offenders = shipped.filter { (_, text) -> promises.any { it in text } } + assertTrue("These promise a default server: $offenders", offenders.isEmpty()) + + val unset = shipped.filter { (name, _) -> + name.endsWith("/join_server_unset") || name.endsWith("/settings_server_url_unset") + } + assertEquals("both languages, both rows", 4, unset.size) + for ((name, text) in unset) { + assertTrue("$name: $text", "умолчани" !in text.lowercase() && "default" !in text.lowercase()) + } + } + + /** + * #157. The first run is not four screens or five any more and the class + * code is not six characters; the comments that counted either were a + * wrong map for the next change, which is what CLAUDE.md sends a reader to + * them for. + */ + @Test + fun `no comment counts the first run's screens or calls the class code six characters`() { + val stale = listOf( + Regex("""\b(four|five) screens\b"""), + Regex("""\bone of four\b"""), + Regex("""six-character (class )?code (from|is)"""), + Regex("""six-character class code"""), + ) + val sources = File("src/main").walkTopDown() + .filter { it.isFile && (it.extension == "kt" || it.extension == "xml") } + .toList() + assertTrue("the sources were not found from ${File("").absolutePath}", sources.size > 50) + val offenders = sources.flatMap { file -> + file.readLines().mapIndexedNotNull { index, line -> + "${file.path}:${index + 1}: ${line.trim()}".takeIf { stale.any { it.containsMatchIn(line) } } + } + } + assertTrue("Stale counts:\n${offenders.joinToString("\n")}", offenders.isEmpty()) + } + + /** + * The owner's line under the first screen's button — accepting the terms + * and the privacy policy — is drawn always, whatever the build says about + * where its documents are: with no address it opens the bundled copies. + */ + @Test + fun `the welcome step always draws the legal line`() { + val source = File("src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt").readText() + val welcome = source.substringAfter("private fun WelcomeStep(").substringBefore("\n}\n") + assertTrue("WelcomeStep has no legal footer", "footer = { LegalAcceptanceLine() }" in welcome) + assertTrue("the line must not depend on the build", "BuildConfig" !in welcome) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt new file mode 100644 index 00000000..3e6b2fe2 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt @@ -0,0 +1,203 @@ +package com.lumenpearson.lessons.ui.onboarding + +import com.lumenpearson.lessons.core.data.catalog.DirectoryProblem +import com.lumenpearson.lessons.core.data.catalog.RegionLookupResult +import com.lumenpearson.lessons.core.data.catalog.SchoolDirectory +import com.lumenpearson.lessons.core.data.catalog.SchoolLookup +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The step holders on their own: the sign-in's held session, the import's + * rows and chooser, and the region search's two speeds. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class OnboardingStepsTest { + + private val target = DiaryTarget.netschool("samara", 239L, "Lyceum 239", login = "", zone = "Europe/Samara") + private val password = "correct horse battery staple" + + // --- Sign-in --------------------------------------------------------------------------- + + @Test + fun `the password is never a field of the sign-in step`() = runTest { + val signIn = FakeSignIn().apply { registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + step.submit(target, password) {} + advanceUntilIdle() + assertTrue("the session is held for the retry", step.state.value.sessionHeld) + + val kept = SignInStep::class.java.declaredFields.map { field -> + field.isAccessible = true + field.get(step) + } + for (value in kept + step.state.value) { + assertFalse("$value", password in value.toString()) + } + } + + @Test + fun `a failure that discarded the session offers no retry`() = runTest { + val signIn = FakeSignIn().apply { + registerResults += Result.failure(DiarySignInProblem.ServerRefusedSession) + } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + var registered = false + step.submit(target, password) { registered = true } + advanceUntilIdle() + + assertFalse(registered) + assertFalse(step.state.value.sessionHeld) + assertEquals(DiarySignInProblem.ServerRefusedSession, step.state.value.problem) + step.retry { registered = true } + advanceUntilIdle() + assertEquals("no second registration without a session", 1, signIn.registered.size) + } + + @Test + fun `a new password discards the session still held`() = runTest { + val signIn = FakeSignIn().apply { registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + step.submit(target, password) {} + advanceUntilIdle() + val first = signIn.registered.single() + + step.submit(target, "another") {} + advanceUntilIdle() + + assertEquals(listOf(first), signIn.discarded) + assertEquals(2, signIn.opened.size) + assertEquals("ivan", signIn.opened.last().first.login) + } + + @Test + fun `a failed preflight sends nothing to the diary`() = runTest { + val signIn = FakeSignIn().apply { preflightResult = Result.failure(DiarySignInProblem.ServerMissing) } + val step = SignInStep(this, signIn) + step.submit(target, password) {} + advanceUntilIdle() + + assertTrue(signIn.opened.isEmpty()) + assertEquals(DiarySignInProblem.ServerMissing, step.state.value.problem) + assertTrue(step.state.value.dialog) + step.edited() + assertNull(step.state.value.problem) + } + + // --- Import ---------------------------------------------------------------------------- + + @Test + fun `stage rows follow the phase under way`() { + val running = ImportUi(phase = DiaryImportPhase.SCHEDULE) + assertEquals(StageState.DONE, stageStateOf(running, DiaryImportPhase.STUDENTS)) + assertEquals(StageState.DONE, stageStateOf(running, DiaryImportPhase.PERIODS)) + assertEquals(StageState.RUNNING, stageStateOf(running, DiaryImportPhase.SCHEDULE)) + assertEquals(StageState.WAITING, stageStateOf(running, DiaryImportPhase.MARKS)) + + val failed = ImportUi(failed = ImportFailure(DiaryImportPhase.HOMEWORK, DiarySignInProblem.Offline, true)) + assertEquals(StageState.DONE, stageStateOf(failed, DiaryImportPhase.SCHEDULE)) + assertEquals(StageState.FAILED, stageStateOf(failed, DiaryImportPhase.HOMEWORK)) + assertEquals(StageState.WAITING, stageStateOf(failed, DiaryImportPhase.MARKS)) + + val done = ImportUi(done = ImportDone(1, 1, 1, setOf(DiaryImportPhase.MARKS))) + assertEquals(StageState.DONE, stageStateOf(done, DiaryImportPhase.HOMEWORK)) + assertEquals(StageState.SKIPPED, stageStateOf(done, DiaryImportPhase.MARKS)) + } + + @Test + fun `the bar never goes backwards`() = runTest { + val import = FakeImport( + steps = listOf( + DiaryImportProgress.Running(DiaryImportPhase.SCHEDULE, 0.5f, 0.8f), + DiaryImportProgress.Running(DiaryImportPhase.HOMEWORK, 0.3f, 0.9f), + DiaryImportProgress.Failed(DiaryImportPhase.HOMEWORK, DiarySignInProblem.Offline, true, 0.4f), + ), + ) + val runner = ImportRunner(this, import) + runner.start() + advanceUntilIdle() + + assertEquals(0.5f, runner.state.value.completed) + assertEquals(DiaryImportPhase.HOMEWORK, runner.state.value.failed?.phase) + } + + @Test + fun `several pupils pause the import until one is picked`() = runTest { + val sister = pupil.copy(id = 8, firstName = "Anna", fullName = "Petrova Anna") + val import = FakeImport(choosing = listOf(pupil, sister)) + val runner = ImportRunner(this, import) + runner.start() + runCurrent() + + assertEquals(listOf(7L, 8L), runner.state.value.choosing?.map { it.id }) + assertNull(runner.state.value.done) + + runner.choose(8) + advanceUntilIdle() + assertNull(runner.state.value.choosing) + assertEquals(1f, runner.state.value.completed) + } + + // --- Region search --------------------------------------------------------------------- + + @Test + fun `typing searches the catalog at once and the directory only after a pause`() = runTest { + val asked = mutableListOf() + val finder = RegionFinder( + scope = this, + catalog = { realCatalog }, + byName = { realSearch.search(it) }, + find = { query -> + asked += query + RegionLookupResult(query, realSearch.search(query), SchoolLookup.Generic) + }, + ) + + finder.type("Sa") + runCurrent() + assertTrue(finder.state.value.rows.isNotEmpty()) + advanceUntilIdle() + assertTrue("under the directory's minimum nothing is asked", asked.isEmpty()) + + finder.type("Sam") + finder.type("Sama") + finder.type("Samar") + runCurrent() + assertTrue(asked.isEmpty()) + advanceTimeBy(SchoolDirectory.DEBOUNCE_MILLIS + 1) + runCurrent() + assertEquals("one request for one pause in the typing", listOf("Samar"), asked) + assertEquals(SchoolAnswer.Generic, finder.state.value.school) + + finder.submit() + runCurrent() + assertEquals(listOf("Samar", "Samar"), asked) + } + + @Test + fun `every directory failure says pick the region, and waiting is counted in minutes`() { + fun failed(problem: DirectoryProblem) = answerOf(SchoolLookup.Failed(problem)) as SchoolAnswer.Failed + assertEquals(SchoolAnswer.Failed(DirectoryFailure.WAIT, 2), failed(DirectoryProblem.Throttled(61))) + assertEquals(SchoolAnswer.Failed(DirectoryFailure.WAIT, 1), failed(DirectoryProblem.Spent(1))) + assertEquals(SchoolAnswer.Failed(DirectoryFailure.WAIT, null), failed(DirectoryProblem.Throttled(null))) + assertEquals(DirectoryFailure.NO_SERVER, failed(DirectoryProblem.ServerMissing).reason) + assertEquals(DirectoryFailure.OFFLINE, failed(DirectoryProblem.Offline).reason) + assertEquals(DirectoryFailure.OFF, failed(DirectoryProblem.Disabled).reason) + assertEquals(DirectoryFailure.OFF, failed(DirectoryProblem.ServerTooOld).reason) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt new file mode 100644 index 00000000..cda95a06 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt @@ -0,0 +1,191 @@ +package com.lumenpearson.lessons.ui.onboarding + +import androidx.lifecycle.SavedStateHandle +import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.catalog.RegionLookupResult +import com.lumenpearson.lessons.core.data.catalog.RegionSearch +import com.lumenpearson.lessons.core.data.catalog.SchoolLookup +import com.lumenpearson.lessons.core.data.diary.DiaryImport +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress +import com.lumenpearson.lessons.core.data.repository.AppSettings +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryRegistration +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.SettingsRepository +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.data.repository.SyncArming +import com.lumenpearson.lessons.core.data.upstream.DiarySchool +import com.lumenpearson.lessons.core.model.AppLanguage +import com.lumenpearson.lessons.ui.diary.FakeDiaryCache +import java.io.File +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flow + +/** The catalog the APK carries, read from the source tree rather than a copy that could drift. */ +internal val realCatalog: RegionCatalog by lazy { + var directory: File? = File("").absoluteFile + while (directory != null) { + val file = File(directory, "server/app/catalog/data/regions.json") + if (file.isFile) return@lazy RegionCatalog.parse(file.readText()) + directory = directory.parentFile + } + error("regions.json not found from ${File("").absolutePath}") +} + +internal val realSearch: RegionSearch by lazy { RegionSearch(realCatalog) } + +internal fun region(key: String) = checkNotNull(realCatalog.region(key)) { "no region $key" } + +internal class FakeShellMode(initial: ShellState = ShellState(ShellMode.NONE, held = false)) : ShellModeSource { + val stored = MutableStateFlow(initial) + override val state: Flow = stored + override suspend fun current(): ShellState = stored.value + override val syncArming: Flow = emptyFlow() + override suspend fun hold() { + stored.value = stored.value.copy(held = true) + } + override suspend fun release() { + stored.value = stored.value.copy(held = false) + } + override suspend fun settleColdStart(): ShellState = stored.value +} + +internal class FakeSettings(initial: AppSettings = AppSettings()) : SettingsRepository { + val stored = MutableStateFlow(initial) + override val settings: Flow = stored + override suspend fun update(transform: (AppSettings) -> AppSettings) { + stored.value = transform(stored.value) + } + override fun languageBlocking(): AppLanguage = stored.value.language +} + +/** A diary session the fake sign-in hands over; nothing in it is a secret. */ +internal class TestHeld(override val target: DiaryTarget) : HeldUpstream + +/** + * The sign-in, scripted: what each step answers, and every call it was asked. + * The password is recorded only to prove, elsewhere, that nothing else kept it. + */ +internal class FakeSignIn : OnboardingSignIn { + var preflightResult: Result = Result.success(Unit) + var openResult: (DiaryTarget) -> Result = { Result.success(TestHeld(it)) } + val registerResults = ArrayDeque>() + val calls = mutableListOf() + val opened = mutableListOf>() + val registered = mutableListOf() + val discarded = mutableListOf() + + override suspend fun preflight(target: DiaryTarget): Result { + calls += "preflight" + return preflightResult + } + + override suspend fun open(target: DiaryTarget, password: String): Result { + calls += "open" + opened += target to password + return openResult(target) + } + + override suspend fun register(held: HeldUpstream): Result { + calls += "register" + registered += held + return registerResults.removeFirstOrNull() ?: Result.success(registration(held.target)) + } + + override suspend fun discard(held: HeldUpstream) { + calls += "discard" + discarded += held + } +} + +internal fun registration(target: DiaryTarget) = + DiaryRegistration(DiarySession(login = target.login, token = "bearer", target = target), emptyList()) + +internal val pupil = DiaryStudent( + id = 7, + firstName = "Ivan", + lastName = "Petrov", + middleName = null, + fullName = "Petrov Ivan", + school = "School 239", + className = "9A", +) + +/** An import that answers with [steps], or waits for the chooser when [choosing] is set. */ +internal class FakeImport( + var steps: List = listOf( + DiaryImportProgress.Running(DiaryImportPhase.STUDENTS, 0f, 0.1f), + DiaryImportProgress.Done(pupil, emptySet(), lessons = 10, homework = 3, marks = 4), + ), + var choosing: List? = null, +) : DiaryImport { + val runs = mutableListOf() + + override fun run( + resumeFrom: DiaryImportPhase?, + choose: suspend (List) -> DiaryStudent, + ): Flow = flow { + runs += resumeFrom + choosing?.let { students -> + emit(DiaryImportProgress.ChoosingStudent(students, 0.1f)) + val picked = choose(students) + emit(DiaryImportProgress.Done(picked, emptySet(), 1, 1, 1)) + return@flow + } + steps.forEach { emit(it) } + } + + override suspend fun refreshIfStale(): Result = Result.success(false) +} + +/** Everything the view model reaches, as fakes a test can set before or after it starts. */ +internal class OnboardingRig( + val shell: FakeShellMode = FakeShellMode(), + val settings: FakeSettings = FakeSettings(), + val signIn: FakeSignIn = FakeSignIn(), + val import: FakeImport = FakeImport(), + val cache: FakeDiaryCache = FakeDiaryCache(), + val saved: SavedStateHandle = SavedStateHandle(), +) { + var classSession: Session? = null + var diarySession: DiarySession? = null + var storedTarget: DiaryTarget? = null + var signedOut = 0 + val directoryAsked = mutableListOf() + var schools: List = listOf(DiarySchool(id = 239, name = "Lyceum 239", address = null)) + + fun deps() = OnboardingDeps( + settings = settings, + shellMode = shell, + currentClass = { classSession }, + currentDiary = { diarySession }, + storedTarget = { storedTarget }, + signOutDiary = { + signedOut += 1 + diarySession = null + Result.success(Unit) + }, + signIn = signIn, + diaryImport = import, + cache = cache, + catalog = { realCatalog }, + regionsByName = { realSearch.search(it) }, + findRegions = { query -> + directoryAsked += query + RegionLookupResult(query, realSearch.search(query), SchoolLookup.NotAsked) + }, + schools = { _, _ -> Result.success(schools) }, + ) + + fun joinedClass(binding: DiaryBinding?) { + classSession = Session(classId = 1, className = "9A", school = "School", token = "t", diary = binding) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt new file mode 100644 index 00000000..7b03dd92 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt @@ -0,0 +1,127 @@ +package com.lumenpearson.lessons.ui.onboarding + +import android.content.Context +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.onRoot +import androidx.test.core.app.ApplicationProvider +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.ui.legal.LegalAcceptanceLine +import java.util.Locale +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * The words of the provider step's «Почему?», and where the welcome step's + * legal line lands — the two parts of the flow a pure test cannot read. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp-h1200dp") +class OnboardingTextTest { + + @get:Rule + val compose = createComposeRule() + + private val context get() = ApplicationProvider.getApplicationContext() + + private fun inEnglish(): Context { + val configuration = android.content.res.Configuration(context.resources.configuration) + configuration.setLocale(Locale.ENGLISH) + return context.createConfigurationContext(configuration) + } + + private fun why(reason: WhyReason) = WhyUi( + reason = reason, + modifiers = WhyModifier.entries.toSet(), + confidence = "medium", + regionRu = "Region", + regionEn = "Region", + systemRu = "System", + systemEn = "System", + mainSystemRu = "Main", + mainSystemEn = "Main", + schoolYear = "2026/27", + surveyMonth = "2026-09", + host = "diary.example", + ) + + /** + * Every reason the catalog can give, in both languages: the sentence formats + * with the arguments it is handed, and names the region — a placeholder the + * translation lost, or one it added, would print a bare `%2$s` on a page + * whose whole job is to explain. + */ + @Test + fun `every reason reads whole in both languages`() { + for (language in listOf(context, inEnglish())) { + for (reason in WhyReason.entries) { + val lines = whyLines(why(reason), "Region", "System", "Main", "September 2026") + val text = lines.joinToString("\n") { line -> language.getString(line.id, *line.args.toTypedArray()) } + assertFalse("$reason: $text", "%" in text) + assertTrue("$reason: $text", "Region" in text) + assertTrue("$reason names the host", "diary.example" in text) + assertTrue("$reason cites the survey", "September 2026" in text) + } + } + } + + @Test + fun `a sign-in reason names the system and the school year`() { + val text = whyLines(why(WhyReason.PRIMARY), "Region", "System", null, null) + .first() + .let { line -> context.getString(line.id, *line.args.toTypedArray()) } + assertTrue(text, "System" in text && "2026/27" in text) + } + + @Test + fun `the survey month is written out in the reader's language`() { + assertTrue(surveyMonthText("2026-09", Locale.ENGLISH).orEmpty().startsWith("September")) + assertTrue(surveyMonthText("2026-09", Locale.forLanguageTag("ru")).orEmpty().startsWith("сентябрь")) + assertFalse(surveyMonthText("autumn", Locale.ENGLISH) != null) + } + + /** + * The legal line sits under the button, inside the same inset: below the + * button, and not under the gesture bar — which is where a line placed + * after the row, rather than in it, would have gone. + */ + @Test + fun `the legal line is drawn under the button, inside the page`() { + compose.setContent { + LessonsTheme { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { + OnboardingActions( + label = "Continue", + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onClick = {}, + modifier = Modifier.testTag("actions"), + footer = { LegalAcceptanceLine(modifier = Modifier.testTag("legal")) }, + ) + } + } + } + + compose.onNodeWithText("Continue").assertIsDisplayed() + compose.onNodeWithTag("legal").assertIsDisplayed() + val button = compose.onNodeWithText("Continue").getBoundsInRoot() + val legal = compose.onNodeWithTag("legal").getBoundsInRoot() + val root = compose.onRoot().getBoundsInRoot() + assertTrue("the line starts at ${legal.top}, the button ends at ${button.bottom}", legal.top >= button.bottom) + assertTrue("the line runs off the page", legal.bottom <= root.bottom) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt new file mode 100644 index 00000000..853a642c --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt @@ -0,0 +1,339 @@ +package com.lumenpearson.lessons.ui.onboarding + +import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase +import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress +import com.lumenpearson.lessons.core.data.repository.DiaryBinding +import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.ui.diary.DiarySchoolRow +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The first run's state holder, driven through its steps with fakes: what it + * writes, what it holds, what it commits, and what it never keeps. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class OnboardingViewModelTest { + + private val dispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private val login = "ivan.petrov" + private val password = "correct horse battery staple" + + private fun OnboardingRig.model() = OnboardingViewModel(saved, deps()) + + private val OnboardingViewModel.state get() = checkNotNull(flow.value) { "the flow has not started" } + + @Test + fun `reaching the chooser writes onboardingDone`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = false) + advanceUntilIdle() + repeat(3) { + model.next() + advanceUntilIdle() + } + assertEquals(OnboardingStep.PERMISSIONS, model.state.current) + assertFalse(rig.settings.stored.value.onboardingDone) + + model.next() + advanceUntilIdle() + assertEquals(OnboardingStep.WAY_IN, model.state.current) + assertTrue(rig.settings.stored.value.onboardingDone) + } + + @Test + fun `the class-code step holds the shell and a join with no diary finishes`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.chooseWay(WayIn.CLASS_CODE) + model.proceedFromWayIn() + advanceUntilIdle() + assertEquals(OnboardingStep.CLASS_CODE, model.state.current) + assertTrue("the join must not swap the flow for a home", rig.shell.stored.value.held) + + rig.joinedClass(binding = null) + rig.shell.stored.value = rig.shell.stored.value.copy(mode = ShellMode.CLASS) + model.onJoined() + advanceUntilIdle() + + assertFalse(rig.shell.stored.value.held) + assertTrue("finish clears what was saved", rig.saved.keys().all { rig.saved.get(it) == null }) + } + + @Test + fun `a join whose class has a usable diary commits its sign-in`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.chooseWay(WayIn.CLASS_CODE) + model.proceedFromWayIn() + advanceUntilIdle() + + rig.joinedClass(DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 239L, "Lyceum 239")) + model.onJoined() + advanceUntilIdle() + + val state = model.state + assertEquals(OnboardingStep.SIGN_IN, state.current) + assertTrue(state.choices.classBound) + assertFalse("the join screen cannot be walked back into", state.canGoBack) + val header = checkNotNull(model.signInHeader.value) + assertTrue(header.classBound) + assertEquals("asurso.ru", header.place.host) + assertTrue(rig.shell.stored.value.held) + } + + @Test + fun `a join with a diary already signed in finishes rather than asking again`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + rig.diarySession = DiarySession(login, "bearer", DiaryTarget.petersburg(login)) + rig.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + rig.shell.hold() + + model.onJoined() + advanceUntilIdle() + + assertFalse(rig.shell.stored.value.held) + } + + /** Walks the family's own way to the sign-in step for Samara, school 239. */ + private suspend fun kotlinx.coroutines.test.TestScope.toSamaraSignIn(model: OnboardingViewModel) { + model.start(introduced = true) + advanceUntilIdle() + model.chooseWay(WayIn.FIND_SCHOOL) + model.proceedFromWayIn() + advanceUntilIdle() + assertEquals(OnboardingStep.REGION, model.state.current) + model.pickRegion("samara") + advanceUntilIdle() + model.proceedFromRegion() + advanceUntilIdle() + assertEquals(OnboardingStep.SCHOOL, model.state.current) + model.pickSchool(DiarySchoolRow(239, "Lyceum 239", null)) + model.proceedFromSchool() + advanceUntilIdle() + assertEquals(OnboardingStep.PROVIDER, model.state.current) + val row = checkNotNull(model.provider.value?.main) + assertEquals(ProviderRowKind.SIGN_IN, row.kind) + model.signInWith(row.index) + advanceUntilIdle() + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + } + + @Test + fun `the family's own way signs in to the picked school and commits the import`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + toSamaraSignIn(model) + assertTrue(rig.shell.stored.value.held) + + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + + val (target, sent) = rig.signIn.opened.single() + assertEquals(DiaryProviderKey.NETSCHOOL, target.provider) + assertEquals("samara", target.region) + assertEquals(239L, target.schoolId) + assertEquals(login, target.login) + assertEquals(password, sent) + + val state = model.state + assertEquals(OnboardingStep.IMPORT, state.current) + assertFalse("a second sign-in would mint a second server session", state.canGoBack) + + // The fake import finishes at once; the screen then shows the summary. + assertNotNull(model.importing.state.value.done) + model.importShown() + advanceUntilIdle() + assertEquals(OnboardingStep.SUMMARY, model.state.current) + assertNotNull(model.summary.value) + + model.finish() + advanceUntilIdle() + assertFalse(rig.shell.stored.value.held) + } + + @Test + fun `a failed registration keeps the session for a retry without the password`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.signIn.registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) + val model = rig.model() + toSamaraSignIn(model) + + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + assertTrue(model.signIn.state.value.sessionHeld) + + model.retrySignIn() + advanceUntilIdle() + + assertEquals(listOf("preflight", "open", "register", "register"), rig.signIn.calls) + assertEquals(OnboardingStep.IMPORT, model.state.current) + } + + @Test + fun `backing out of the sign-in says goodbye to a session the server never took`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.signIn.registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + + model.back() + advanceUntilIdle() + + assertEquals(OnboardingStep.PROVIDER, model.state.current) + assertEquals(1, rig.signIn.discarded.size) + assertFalse(model.signIn.state.value.sessionHeld) + } + + @Test + fun `the saved state carries no credential`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.signIn.registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + + for (key in rig.saved.keys()) { + val value = rig.saved.get(key).toString() + assertFalse("$key holds the password", password in value) + assertFalse("$key holds the login", login in value) + } + } + + @Test + fun `a cold start with the hold set resumes where the write left it`() = runTest(dispatcher) { + val diary = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.DIARY, held = true))) + val importing = diary.model() + importing.start(introduced = true) + advanceUntilIdle() + assertEquals(listOf(OnboardingStep.IMPORT), importing.state.path) + + val joined = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.CLASS, held = true))) + joined.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + val signingIn = joined.model() + signingIn.start(introduced = true) + advanceUntilIdle() + assertEquals(listOf(OnboardingStep.SIGN_IN), signingIn.state.path) + assertTrue(signingIn.state.choices.classBound) + + val done = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.CLASS, held = true))) + done.joinedClass(binding = null) + val finishing = done.model() + finishing.start(introduced = true) + advanceUntilIdle() + assertFalse(done.shell.stored.value.held) + } + + @Test + fun `a saved flow comes back as it was, and a finished one starts afresh`() = runTest(dispatcher) { + val rig = OnboardingRig() + val saved = OnboardingState( + path = listOf(OnboardingStep.WAY_IN, OnboardingStep.REGION), + choices = OnboardingChoices(wayIn = WayIn.FIND_SCHOOL, region = "samara"), + ) + saved.toSaved().forEach { (key, value) -> rig.saved[key] = value } + + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + assertEquals(saved, model.state) + + model.finish() + advanceUntilIdle() + model.start(introduced = true) + advanceUntilIdle() + assertEquals(listOf(OnboardingStep.WAY_IN), model.state.path) + } + + @Test + fun `an import the diary ended goes back to the sign-in and resumes its phase`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.import.steps = listOf( + DiaryImportProgress.Running(DiaryImportPhase.SCHEDULE, 0.2f, 0.5f), + DiaryImportProgress.Failed(DiaryImportPhase.SCHEDULE, DiarySignInProblem.ReauthRequired, true, 0.2f), + ) + rig.storedTarget = DiaryTarget.petersburg(login) + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + assertTrue(model.importing.state.value.failed?.needsSignIn == true) + + model.signInAgain() + advanceUntilIdle() + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + assertFalse(model.state.canGoBack) + + rig.import.steps = listOf(DiaryImportProgress.Done(pupil, emptySet(), 1, 1, 1)) + model.submitSignIn(password) + advanceUntilIdle() + assertEquals(OnboardingStep.IMPORT, model.state.current) + assertEquals(listOf(null, DiaryImportPhase.SCHEDULE), rig.import.runs) + assertNull("the resume point is spent once used", model.state.choices.resumeFrom) + } + + @Test + fun `a Gosuslugi-only region never reaches the sign-in`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.chooseWay(WayIn.FIND_SCHOOL) + model.proceedFromWayIn() + model.pickRegion("tula") + advanceUntilIdle() + model.proceedFromRegion() + advanceUntilIdle() + + assertEquals(OnboardingStep.PROVIDER, model.state.current) + val page = checkNotNull(model.provider.value) + assertTrue(page.rows.none { it.kind == ProviderRowKind.SIGN_IN || it.kind == ProviderRowKind.NEEDS_SCHOOL }) + assertEquals(ProviderRowKind.HANDOFF, page.main?.kind) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSectionListingTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSectionListingTest.kt new file mode 100644 index 00000000..c3d838e3 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/settings/SettingsSectionListingTest.kt @@ -0,0 +1,78 @@ +package com.lumenpearson.lessons.ui.settings + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Which rows the settings root offers, per home — `SettingsSection.listedOn`, + * the rule that replaced a flag which could only say «never on the root». + */ +class SettingsSectionListingTest { + + private fun listed(mode: ShellMode, manager: Boolean) = + SettingsSection.entries.filter { it.listedOn(mode, manager) } + + /** Pinned: a phone in a class sees exactly what it saw before the diary home existed. */ + @Test + fun `class mode lists what it lists today`() { + val everyone = listOf( + SettingsSection.APPEARANCE, + SettingsSection.FEEL, + SettingsSection.CONTENT, + SettingsSection.ALERTS, + SettingsSection.SYNC, + SettingsSection.ACCOUNT, + SettingsSection.DIARY, + SettingsSection.UPDATES, + SettingsSection.ABOUT, + ) + assertEquals(everyone, listed(ShellMode.CLASS, manager = false)) + assertEquals( + everyone + SettingsSection.ADMIN, + listed(ShellMode.CLASS, manager = true), + ) + } + + /** + * #151's other half: on the diary home, «Дневник» is on the list — it is + * where the account and «Выйти из дневника» are — and nothing is that + * needs a class token or a class timetable, each of which would be a page + * of switches that do nothing or a request that answers 401. + */ + @Test + fun `diary mode lists the diary and no page that needs a class`() { + for (manager in listOf(false, true)) { + val sections = listed(ShellMode.DIARY, manager) + assertTrue(SettingsSection.DIARY in sections) + for (classOnly in listOf( + SettingsSection.CONTENT, + SettingsSection.ALERTS, + SettingsSection.ACCOUNT, + SettingsSection.ADMIN, + SettingsSection.PERMISSIONS, + )) { + assertTrue("$classOnly listed on the diary home", classOnly !in sections) + } + } + assertEquals( + listOf( + SettingsSection.APPEARANCE, + SettingsSection.FEEL, + SettingsSection.SYNC, + SettingsSection.DIARY, + SettingsSection.UPDATES, + SettingsSection.ABOUT, + ), + listed(ShellMode.DIARY, manager = false), + ) + } + + @Test + fun `permissions is reached from the alerts page, never from the root`() { + for (mode in ShellMode.entries) { + assertTrue(SettingsSection.PERMISSIONS !in listed(mode, manager = true)) + } + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt index 026f7191..d8ca18b9 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/di/SessionEffects.kt @@ -74,18 +74,19 @@ internal class SessionEffects( * class the phone is no longer showing, and tapping it opens the app on the * other one. * - * [startBackgroundSync] is here rather than left to the app module, and the - * reason is that the app module cannot do it. `schedulePeriodic` has one - * caller — `LessonsApplication.observeSyncInterval()`, a - * `distinctUntilChanged()` collector on `syncIntervalMinutes` — so it runs - * when the *interval* moves. A sign-out and a re-join in one process move - * no interval: [onSignedOut] cancels the periodic worker, the collector - * never re-emits, and the class joined a moment later gets [syncNow] and - * then nothing at all until the next cold start. Fresh once and stale - * after, which is indistinguishable on screen from a phone that is syncing. - * The collector cannot see a session change and this table is nothing but - * session changes, so the re-arm belongs on this side of the line; making - * it idempotent is what lets both of them ask. + * [startBackgroundSync] is here as well as in the app module, and both are + * meant. `LessonsApplication` collects `ShellModeSource.syncArming` — the + * mode and the interval, read from one preferences emission — so a sign-out + * followed by a re-join disarms and re-arms from there too. It did not + * always: the collector used to follow the interval alone, a sign-out and a + * re-join move no interval, and the class joined a moment later got + * [syncNow] and then nothing at all until the next cold start — fresh once + * and stale after, which is indistinguishable on screen from a phone that is + * syncing. This table still asks because it acts in the same breath as the + * session write, while the collector waits on a DataStore emission, and + * because a switch between two classes changes neither the mode nor the + * interval and so reaches the collector not at all. `schedulePeriodic` is + * idempotent, which is what lets both of them ask. */ fun onActiveClassChanged() { redrawWidget() diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/StateHeroCard.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/StateHeroCard.kt index 31d7217d..9b47af87 100644 --- a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/StateHeroCard.kt +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/StateHeroCard.kt @@ -1,24 +1,18 @@ package com.lumenpearson.lessons.core.designsystem.component -import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.material3.LinearWavyProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.lumenpearson.lessons.core.designsystem.R @@ -164,7 +158,8 @@ fun StateHeroCard( * * Separated out because it is the only stateful-looking part of the card and the * animation has to survive the card recomposing every minute; keeping it in its - * own composable means only the bar re-runs when the fraction ticks. + * own composable means only the bar re-runs when the fraction ticks. The bar + * itself is [LessonsWavyProgress], shared with every other screen that waits. */ @Composable private fun HeroProgress( @@ -172,22 +167,9 @@ private fun HeroProgress( accent: Color, track: Color, ) { - val animated by animateFloatAsState( - targetValue = progress.coerceIn(0f, 1f), - // Uses the MotionScheme installed by LessonsTheme, which is the point of - // MaterialExpressiveTheme. If MaterialTheme.motionScheme moves, the - // stable fallback is tween(durationMillis = 600). - animationSpec = MaterialTheme.motionScheme.slowSpatialSpec(), - label = "heroProgress", - ) - val description = correctedString(R.string.ds_countdown_progress, progress.asPercent()) - - LinearWavyProgressIndicator( - progress = { animated }, - modifier = Modifier - .fillMaxWidth() - .height(12.dp) - .semantics { contentDescription = description }, + LessonsWavyProgress( + progress = progress, + description = correctedString(R.string.ds_countdown_progress, progress.asPercent()), color = accent, trackColor = track, ) diff --git a/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/WavyProgress.kt b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/WavyProgress.kt new file mode 100644 index 00000000..09fd67ba --- /dev/null +++ b/android/core/designsystem/src/main/kotlin/com/lumenpearson/lessons/core/designsystem/component/WavyProgress.kt @@ -0,0 +1,97 @@ +package com.lumenpearson.lessons.core.designsystem.component + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.snap +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material3.LinearWavyProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.WavyProgressIndicatorDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import com.lumenpearson.lessons.core.designsystem.theme.LocalMotion + +/** + * The app's one wavy progress bar: the countdown under the hero card, and any + * screen that waits on something long enough to draw how far it has got — the + * diary import is the second. + * + * One implementation because the bar is a signature of the app rather than a + * stock control: two copies would drift apart in height, in the spring they + * move by, and in whether they listen to the motion setting, and the first two + * are exactly what a reader notices when one screen hands over to the next. + * + * With animations off the bar **snaps** and lies flat: no wave and no travel. + * A wave that keeps moving under a switch that says «без анимаций» is the one + * motion somebody who turned motion off will still see on every screen that + * waits. + * + * @param progress how much is done, `0..1`; values outside are clamped, so a + * caller that overshoots by a rounding error does not draw past the end. + * @param description what a screen reader says for the bar. `null` leaves the + * indicator's own semantics (a bare percentage), which is right only where + * the text beside the bar already says what the percentage is of. + * @param color the wave; the theme's primary by default. + * @param trackColor the unfilled part; the indicator's own default track. + */ +@Composable +fun LessonsWavyProgress( + progress: Float, + modifier: Modifier = Modifier, + description: String? = null, + color: Color = MaterialTheme.colorScheme.primary, + trackColor: Color = WavyProgressIndicatorDefaults.trackColor, +) { + val motion = LocalMotion.current + val animated by animateFloatAsState( + targetValue = progress.coerceIn(0f, 1f), + // The MotionScheme installed by LessonsTheme, which is the point of + // MaterialExpressiveTheme. If MaterialTheme.motionScheme moves, the + // stable fallback is tween(durationMillis = 600). + animationSpec = if (motion.enabled) { + MaterialTheme.motionScheme.slowSpatialSpec() + } else { + snap() + }, + label = "lessonsWavyProgress", + ) + val semantic = if (description != null) { + Modifier.semantics { contentDescription = description } + } else { + Modifier + } + + if (motion.enabled) { + LinearWavyProgressIndicator( + progress = { animated }, + modifier = modifier + .fillMaxWidth() + .height(WavyBarHeight) + .then(semantic), + color = color, + trackColor = trackColor, + ) + } else { + LinearWavyProgressIndicator( + progress = { animated }, + modifier = modifier + .fillMaxWidth() + .height(WavyBarHeight) + .then(semantic), + color = color, + trackColor = trackColor, + // Flat and still: the amplitude is what draws the wave, and the + // speed is what moves it along the bar. + amplitude = { 0f }, + waveSpeed = 0.dp, + ) + } +} + +/** The countdown's height, which every other bar takes so the two read as one control. */ +private val WavyBarHeight = 12.dp From 9c797a25beb817ce7f8a0e91cc60dde010ed13f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 18:33:11 +0000 Subject: [PATCH 19/30] Hold the phone's diary sign-in to the server's own rules, and make its tests able to fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial review of the new Android data layer (b19e6b2, ce9c749) confirmed twelve findings that are this part's. Each is fixed here with a test that was run against the code before the fix, or against the fix mutated back, and failed there. [0] UpstreamHttp.classify called every SSLHandshakeException Untrusted, so a handshake the network reset («Connection reset by peer», «Connection closed by peer», the JVM's «Remote host terminated the handshake») told the person their phone did not trust the diary and offered no retry. Only a failure that examined the certificate is Untrusted now: a CertificateException, CertPathValidatorException or CertPathBuilderException in the cause chain, or SSLPeerUnverifiedException. UpstreamHttpTest's new «a handshake the network broke is unavailable» failed on the old rule; the trust cases (Android's shape, the JVM's PKIX, an expired certificate, a hostname mismatch) are held beside it. [1] The phone trimmed a login where the server's _clean_login_value also drops every character Python's isprintable refuses, so a login pasted with bidi isolates or a zero-width space went upstream as pasted and read as a wrong password. DiaryLogin.clean is the one port, by code point; both sign-ins, openUpstream, the registration body and the stored target use it. The new «login» block of diary_protocol.json (17 cases) is run by test_login_cleaning_matches_the_vectors (through DiaryLoginIn and PetersburgSessionIn) and by the Kotlin vectors test, which also asks both sign-ins what they sent; that and DiarySignInTest's pasted-login test failed with the sign-ins mutated back to trim(). [2] UpstreamJson.parse took kotlinx's unquoted literals for JSON, so «» on getdata was «unavailable» and {"at": abc} a wrong password where the server says «unexpected». It now refuses any literal json.loads refuses (NaN and Infinity stay, as in Python), walking with its own stack. netschool.raw_answer_cases (11 cases) is run by both sides; the Kotlin run failed on {"schoolLogin": False} before the fix. [3] RegionSearch found nothing for «St Petersburg», «Moscow region», «Chuvashia» and the like. Fixed in the catalog data, regenerated with the generator: [search.synonyms] (st → saint, region → oblast|krai), translit pairs for the English endings (iya, ia, iy, yy, tsk), and «Zabaikalye», «Zabaykalye», «Primorye» as aliases. «oblast» is still not a stop word, and a test says why. RegionSearchTest's fifteen queries failed on «St Petersburg» first; test_region_catalog gains the synonyms and translit checks. [4]+[8] The Tomsk zone test used an instant Moscow also calls Monday. It now uses 19:30 UTC on a Sunday and asserts the absent Moscow plan too, and refreshIfStale has the same test; both failed with the zone hard-coded to Moscow. [7] The refresh-during-import test now asks while the import's schedule request is in flight, with a stored pupil; it failed with the tryLock removed and with run()'s withLock removed. [9] SeedingDiarySignIn is tested through a sign-in that clears the cache first, as the container's does, on both the signIn and register paths; it failed with the generation taken before the registration and with the seed a no-op. [10] DiarySignInTest records forget, select and write in one list and asserts their order; it failed with the write moved first. [11] SyncWorkerSourceTest reads every application, receiver and service the manifests declare, LessonsApplication included, and still passes; it failed with a diaryImport reference added to LessonsApplication.onCreate. [12] BackupRulesTest now fails on any storage root in CrashReporter other than its two known expressions; it failed with a third write to filesDir. [13] The failing-directory test uses «Казань №», which is both a school query and a place, and asserts byName and suggested survive; it failed with RegionLookup dropping the catalog's answer on failure. Not done here: [5] (the diary strings) and [6] (the CI path filter) belong to other parts. The phone does not yet refuse a login longer than the server's 200 characters (a 422 at registration); nothing here has met a live diary, and the TLS shapes are the ones Conscrypt and the JVM are known to throw, not ones observed on a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .../lumenpearson/lessons/BackupRulesTest.kt | 49 +++++++- .../core/data/catalog/RegionCatalog.kt | 1 + .../lessons/core/data/catalog/RegionSearch.kt | 37 +++++- .../core/data/repository/DiaryLogin.kt | 57 +++++++++ .../core/data/repository/DiarySignInImpl.kt | 28 ++--- .../core/data/upstream/NetSchoolSignIn.kt | 6 +- .../core/data/upstream/PetersburgSignIn.kt | 6 +- .../core/data/upstream/UpstreamHttp.kt | 20 ++- .../core/data/upstream/UpstreamJson.kt | 47 ++++++- .../core/data/catalog/RegionSearchTest.kt | 41 +++++++ .../core/data/catalog/SchoolDirectoryTest.kt | 12 +- .../core/data/diary/DiaryImportTest.kt | 115 +++++++++++++++--- .../core/data/repository/DiarySignInTest.kt | 40 +++++- .../core/data/sync/SyncWorkerSourceTest.kt | 67 +++++++++- .../data/upstream/DiaryProtocolVectorsTest.kt | 61 ++++++++++ .../core/data/upstream/UpstreamHttpTest.kt | 57 ++++++++- server/app/catalog/data/regions.json | 36 +++++- server/scripts/region_catalog.py | 16 ++- server/scripts/region_catalog.toml | 27 +++- server/tests/test_diary_protocol_vectors.py | 67 ++++++++++ server/tests/test_region_catalog.py | 21 ++++ server/tests/vectors/diary_protocol.json | 37 ++++++ 22 files changed, 776 insertions(+), 72 deletions(-) create mode 100644 android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt index ff699489..c205fbb2 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/BackupRulesTest.kt @@ -44,14 +44,51 @@ class BackupRulesTest { "where the reports are", name != null, ) - // Both places the reporter writes, so a third one added there is a - // question this test has to be taught rather than one it misses. + assertWritesOnlyToTheReportsFolder(text) + checkNotNull(name) + } + + /** + * The two places the reporter writes, and nowhere else — so a third one + * added there is a question this test has to be taught rather than one it + * misses. A presence check of the two could not fail when a third + * appeared beside them: a `File(context.filesDir, "last_crash.txt")` sits in + * the `file` domain outside `crash_reports`, which the rules do not exclude. + * + * Every storage root Android hands an app is looked for, with comments + * taken out first so a sentence about one is not a write; what remains once + * the two known expressions are removed must name none. A path spelt out as + * a string is refused for the same reason. + */ + private fun assertWritesOnlyToTheReportsFolder(source: String) { + val code = source + .replace(Regex("""/\*.*?\*/""", RegexOption.DOT_MATCHES_ALL), " ") + .replace(Regex("""//[^\n]*"""), " ") + for (known in KNOWN_LOCATIONS) { + assertTrue("CrashReporter no longer writes to $known; teach this test where it writes", known in code) + } + val rest = KNOWN_LOCATIONS.fold(code) { text, known -> text.replace(known, " ") } + val other = STORAGE_ROOTS.findAll(rest).map { it.value }.toList() + LITERAL_PATH.findAll(rest).map { it.value } assertTrue( - "CrashReporter writes somewhere other than getExternalFilesDir and filesDir", - text.contains("getExternalFilesDir(REPORTS_DIR)") && - text.contains("File(context.filesDir, REPORTS_DIR)"), + "CrashReporter writes somewhere other than ${KNOWN_LOCATIONS.joinToString(" and ")}: $other — " + + "the backup rules exclude only the reports folder, so a file anywhere else goes to Google", + other.isEmpty(), ) - checkNotNull(name) + } + + private companion object { + /** Where `CrashReporter.directory` puts the reports folder: external files, else internal. */ + val KNOWN_LOCATIONS = listOf("getExternalFilesDir(REPORTS_DIR)", "File(context.filesDir, REPORTS_DIR)") + + /** Every directory, file and store an app's `Context` or `Environment` can name. */ + val STORAGE_ROOTS = Regex( + """\b(getExternalFilesDirs?|getExternalCacheDirs?|externalCacheDirs?|externalMediaDirs|filesDir|""" + + """cacheDir|noBackupFilesDir|codeCacheDir|dataDir|obbDirs?|getDir|openFileOutput|getDatabasePath|""" + + """getSharedPreferences|getExternalStorageDirectory|getExternalStoragePublicDirectory|dataStore)\b""", + ) + + /** A `File("/…")` or `File("…")` whose root is a literal rather than one of the above. */ + val LITERAL_PATH = Regex("""\bFile\(\s*"""") } /** Every `` under [parent] (or the whole file), as domain to path. */ diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt index 07812912..da777704 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionCatalog.kt @@ -183,4 +183,5 @@ data class CatalogSearch( @SerialName("school_words") val schoolWords: List = emptyList(), @SerialName("stop_words") val stopWords: List = emptyList(), @SerialName("translit") val translit: List> = emptyList(), + @SerialName("synonyms") val synonyms: Map> = emptyMap(), ) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt index bf71604c..f5c755ce 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearch.kt @@ -9,9 +9,10 @@ import java.util.Locale * * Every word it treats specially comes from the catalog's `search` block * ([CatalogSearch]): the fold map, the region type words it ignores, the two - * keyboard layouts, the transliteration table and the words a school's name is - * made of. The server's directory reads the same block (`catalog.school_words`), - * so «a name too common to look up» means one thing on both sides, and no + * keyboard layouts, the transliteration table, the English words that stand + * for others («St», «region») and the words a school's name is made of. The + * server's directory reads the same block (`catalog.school_words`), so «a + * name too common to look up» means one thing on both sides, and no * Russian word is written into this file. * * Ranking, best first — ties go to the constitution's order, which is the @@ -43,6 +44,11 @@ class RegionSearch(val catalog: RegionCatalog) { private val latinToCyrillic: Map = layoutMap(lexicon.latinLayout, lexicon.cyrillicLayout) private val cyrillicToLatin: Map = layoutMap(lexicon.cyrillicLayout, lexicon.latinLayout) + /** A word typed, and the words of a name it may stand for besides itself («st», «saint»). */ + private val synonyms: Map> = lexicon.synonyms + .mapKeys { (typed, _) -> typed.lowercase(Locale.ROOT) } + .mapValues { (_, meant) -> meant.map { it.lowercase(Locale.ROOT) }.filter { it.isNotEmpty() } } + /** Latin sequences, longest first, as the table lists them. */ private val translit: List> = lexicon.translit .filter { it.size == 2 && it[0].isNotEmpty() } @@ -75,7 +81,9 @@ class RegionSearch(val catalog: RegionCatalog) { if (query.isBlank()) { return catalog.regions.sortedBy { it.order }.map { RegionMatch(it, MatchVia.LIST, "", LIST_SCORE) } } - val candidates = candidates(query).map { normalise(it) }.filter { it.isNotEmpty() }.distinct() + val candidates = candidates(query).map { normalise(it) }.filter { it.isNotEmpty() } + .flatMap { variants(it) } + .distinct() val digits = query.trim().takeIf { it.length in 1..3 && it.all(Char::isDigit) }?.toIntOrNull() return index.mapNotNull { entry -> val scored = candidates.mapNotNull { score(entry, it) } @@ -180,6 +188,26 @@ class RegionSearch(val catalog: RegionCatalog) { return null } + /** + * [words], and every way of reading them with a word swapped for what the + * catalog says it may stand for: «st petersburg» is also «saint + * petersburg», «moscow region» also «moscow oblast». A handful at most — + * the table is short and a query is a few words — but capped anyway, so a + * pasted paragraph of «st st st» cannot multiply without bound. + */ + private fun variants(words: List): List> { + var out = listOf(words) + for ((at, word) in words.withIndex()) { + val meant = synonyms[word] ?: continue + out = out.flatMap { variant -> + listOf(variant) + meant.map { replacement -> + variant.toMutableList().also { it[at] = replacement } + } + }.take(MAX_VARIANTS) + } + return out + } + /** Every word typed starts some word of [target]. */ private fun startsWords(target: List, words: List): Boolean = words.isNotEmpty() && words.all { word -> target.any { it.startsWith(word) } } @@ -220,6 +248,7 @@ class RegionSearch(val catalog: RegionCatalog) { const val CODE_SCORE = 5 const val LIST_SCORE = 7 const val SUBSTRING_MIN = 3 + const val MAX_VARIANTS = 16 /** `№|\d+|[^\W\d_]+`, in Java's spelling; the numero sign is U+2116. */ val SCHOOL_TOKEN = Regex("№|\\p{Nd}+|[\\p{L}\\p{M}]+") diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt new file mode 100644 index 00000000..9a1ed301 --- /dev/null +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt @@ -0,0 +1,57 @@ +package com.lumenpearson.lessons.core.data.repository + +/** + * A diary login as the server cleans it — `_clean_login_value` in + * `server/app/schemas.py`, held to it by the `login` cases of the shared + * vectors. + * + * One cleaning, used everywhere a login leaves the phone: the diary's own + * sign-in and our server's registration. The server keys a family's + * corrections on the login it stores, and it used to receive the password and + * clean the login itself before any upstream call. When the phone signs in on + * its own, a login pasted from a chat with a bidi mark or a zero-width space + * around it went upstream exactly as pasted: the diary compared it to the + * account's name, said no, and the screen asked for the password again, + * however many times it was typed right. + */ +internal object DiaryLogin { + + /** The server's «at least 3 usable characters», counted as Python counts: in code points. */ + const val MIN_CODE_POINTS = 3 + + /** + * [typed] with everything Python's `str.isprintable` refuses taken out — + * controls, format characters (U+200B, U+200E, U+2068, U+FEFF, the soft + * hyphen), surrogates, private use, unassigned code points and every + * separator but the plain space — then trimmed; or `null` when fewer than + * [MIN_CODE_POINTS] are left. + * + * Walked by code point, not by `Char`: half of a pair is a surrogate on its + * own, and dropping both halves of an emoji would count two characters + * fewer than the server does. + */ + fun clean(typed: String): String? { + val kept = buildString(typed.length) { + typed.codePoints().forEach { point -> if (point == SPACE || printable(point)) appendCodePoint(point) } + } + // Nothing but the plain space can be whitespace by now, so this is + // Python's `.strip()` on what is left. + val cleaned = kept.trim { it.code == SPACE } + return cleaned.takeIf { it.codePointCount(0, it.length) >= MIN_CODE_POINTS } + } + + private const val SPACE = 0x20 + + private fun printable(point: Int): Boolean = when (Character.getType(point).toByte()) { + Character.CONTROL, + Character.FORMAT, + Character.SURROGATE, + Character.PRIVATE_USE, + Character.UNASSIGNED, + Character.LINE_SEPARATOR, + Character.PARAGRAPH_SEPARATOR, + Character.SPACE_SEPARATOR, + -> false + else -> true + } +} diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt index 5ec5e438..cf3dcfe1 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt @@ -94,18 +94,18 @@ internal class DiarySignInImpl( } val host = endpoint.origin.host try { - // The server's own rule for a login, checked before anything is - // sent, so a typo costs a sentence rather than an attempt. - val login = target.login.trim() - if (login.codePointCount(0, login.length) < MIN_LOGIN_LENGTH) { - throw DiarySignInProblem.LoginTooShort - } + // The server's own rule for a login, whole — the cleaning as well + // as the length — applied before anything is sent: a typo costs a + // sentence rather than an attempt, and what the diary is sent is + // what the registration will carry. + val login = DiaryLogin.clean(target.login) ?: throw DiarySignInProblem.LoginTooShort if (password.isEmpty()) throw DiarySignInProblem.WrongPassword(upstreamMessage = null) + val cleaned = target.copy(login = login) val session = when (endpoint) { is Endpoint.Petersburg -> - PetersburgSignIn(client(), endpoint.origin, clock).signIn(target, password) + PetersburgSignIn(client(), endpoint.origin, clock).signIn(cleaned, password) is Endpoint.NetSchool -> - NetSchoolSignIn(client(), clock).signIn(endpoint.region, target, password) + NetSchoolSignIn(client(), clock).signIn(endpoint.region, cleaned, password) } Result.success(session) } catch (cancellation: CancellationException) { @@ -255,7 +255,10 @@ internal class DiarySignInImpl( */ private fun requestFor(upstream: UpstreamSession): DiarySessionRequestDto? { val target = upstream.target - val login = target.login.trim() + // Already clean when the session came from `openUpstream`; cleaned + // again rather than trusted, because the server stores the cleaned + // login and refuses, with a 422, one that cleans to under three. + val login = DiaryLogin.clean(target.login) ?: throw DiarySignInProblem.LoginTooShort return when (upstream) { is UpstreamSession.Petersburg -> { val token = upstream.token @@ -302,8 +305,8 @@ internal class DiarySignInImpl( */ private fun sessionFrom(response: DiarySessionResponseDto, sent: DiaryTarget): DiarySession { // The login as the server stored it, which keys the corrections; what - // was typed, trimmed, if it ever stops echoing one. - val login = response.login.trim().ifBlank { sent.login.trim() } + // was sent, cleaned the same way, if it ever stops echoing one. + val login = DiaryLogin.clean(response.login) ?: DiaryLogin.clean(sent.login) ?: sent.login.trim() val target = sent.copy( region = response.region ?: sent.region, schoolId = response.schoolId ?: sent.schoolId, @@ -315,9 +318,6 @@ internal class DiarySignInImpl( } private companion object { - /** `_clean_login_value` in `server/app/schemas.py`. */ - const val MIN_LOGIN_LENGTH = 3 - val DEFAULT_MAX_AGE: Duration = Duration.ofMinutes(10) const val MIN_DECLARED_TIMEOUT_MILLIS = 60_000L diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt index b7ebe5f0..6133d3c4 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSignIn.kt @@ -1,5 +1,7 @@ package com.lumenpearson.lessons.core.data.upstream +import com.lumenpearson.lessons.core.data.repository.DiaryLogin +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.Clock import kotlinx.coroutines.CancellationException @@ -55,7 +57,9 @@ internal class NetSchoolSignIn( // Before any request: a region that takes Госуслуги only is sent nothing. if (!region.password) throw UpstreamFailure.SignInUnsupported() val schoolId = target.schoolId ?: throw UpstreamFailure.Unexpected("no school") - val login = target.login.trim() + // The login the server would have cleaned before any upstream call, + // so a pasted bidi mark is not a wrong password. + val login = DiaryLogin.clean(target.login) ?: throw DiarySignInProblem.LoginTooShort val draft = Draft(region.origin) loginAllowed(draft) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt index c5e49f03..53af1661 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/PetersburgSignIn.kt @@ -1,5 +1,7 @@ package com.lumenpearson.lessons.core.data.upstream +import com.lumenpearson.lessons.core.data.repository.DiaryLogin +import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryTarget import java.time.Clock import kotlinx.serialization.json.JsonNull @@ -32,7 +34,9 @@ internal class PetersburgSignIn( ) { suspend fun signIn(target: DiaryTarget, password: String): UpstreamSession.Petersburg { - val login = target.login.trim() + // The login the server would have cleaned before any upstream call, + // so a pasted bidi mark is not a wrong password. + val login = DiaryLogin.clean(target.login) ?: throw DiarySignInProblem.LoginTooShort val request = Request.Builder() .url(origin.newBuilder().encodedPath(LOGIN_PATH).build()) .header("Accept", "application/json") diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt index 88ef16cd..3d8098ef 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttp.kt @@ -3,9 +3,10 @@ package com.lumenpearson.lessons.core.data.upstream import java.io.IOException import java.net.NoRouteToHostException import java.net.UnknownHostException +import java.security.cert.CertPathBuilderException import java.security.cert.CertPathValidatorException +import java.security.cert.CertificateException import java.util.concurrent.TimeUnit -import javax.net.ssl.SSLHandshakeException import javax.net.ssl.SSLPeerUnverifiedException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @@ -126,12 +127,19 @@ internal object UpstreamHttp { fun classify(failure: IOException): UpstreamFailure { val chain = generateSequence(failure) { it.cause }.take(8).toList() return when { - // A region signed only by a root the phone does not trust. Nothing - // is relaxed to get past it; the screen says so instead. + // A region signed only by a root the phone does not trust, an + // expired certificate, or one for another name. Nothing is relaxed + // to get past it; the screen says so instead. Only a failure that + // examined the certificate counts: a bare SSLHandshakeException is + // also what a reset or a peer hanging up mid-handshake looks like + // (Conscrypt's «Connection reset by peer», the JVM's «Remote host + // terminated the handshake»), and that is a network worth retrying, + // as the server reads the same failure. chain.any { - it is SSLHandshakeException || - it is SSLPeerUnverifiedException || - it is CertPathValidatorException + it is CertificateException || + it is CertPathValidatorException || + it is CertPathBuilderException || + it is SSLPeerUnverifiedException } -> UpstreamFailure.Untrusted(failure) chain.any { it is UnknownHostException || it is NoRouteToHostException } -> UpstreamFailure.Offline(failure) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt index da866d9a..2294e60a 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt @@ -23,11 +23,48 @@ internal object UpstreamJson { private val INTEGER = Regex("-?(0|[1-9][0-9]*)") - /** The parsed body, or `null` for one that is not JSON at all. */ - fun parse(text: String): JsonElement? = try { - json.parseToJsonElement(text) - } catch (_: Exception) { - null + /** + * The same answer as Python's `json.loads`: the literals it reads, and + * nothing else. JavaScript's `NaN` and `Infinity` are among them. + */ + private val LITERAL = Regex("true|false|null|NaN|-?Infinity|-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][-+]?[0-9]+)?") + + /** + * The parsed body, or `null` for one that is not JSON at all — the server's + * `response.json()` raising `ValueError`, held to it by the vectors' + * `raw_answer_cases`. + * + * kotlinx reads any unquoted token as a literal, lenient or not: «», + * «Error» and «01» on their own, `False` or `abc` as a value inside an + * object. Each of those is a refusal to the server, which calls it + * «unexpected»; the phone used to carry on with a word, and then called a + * firewall page a dead diary and a garbled login answer a wrong password. + */ + fun parse(text: String): JsonElement? { + val element = try { + json.parseToJsonElement(text) + } catch (_: Exception) { + return null + } + return element.takeIf(::strict) + } + + /** + * Walked with a stack of its own rather than by recursion: kotlinx parses a + * two-megabyte «[[[[…» without overflowing, and a recursive walk over what + * it built would not. + */ + private fun strict(root: JsonElement): Boolean { + val pending = ArrayDeque().apply { add(root) } + while (pending.isNotEmpty()) { + when (val element = pending.removeLast()) { + is JsonObject -> pending.addAll(element.values) + is JsonArray -> pending.addAll(element) + is JsonNull -> Unit + is JsonPrimitive -> if (!element.isString && !LITERAL.matches(element.content)) return false + } + } + return true } /** diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt index b6deefec..e33e1f5a 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/RegionSearchTest.kt @@ -58,6 +58,47 @@ class RegionSearchTest { assertEquals("moscow", first("moskva")) } + /** + * How the regions are usually written in English, which is neither a word + * of `name_en` nor a clean transliteration: an abbreviation («St»), the + * word «region» where the name says «Oblast» or «Krai», and «-ia» for the + * Russian «-ия». Each of these used to find nothing at all. + */ + @Test + fun `common English spellings find their region first`() { + val expected = listOf( + "St Petersburg" to "saint-petersburg", + "St. Petersburg" to "saint-petersburg", + "st.petersburg" to "saint-petersburg", + "Moscow region" to "moscow-oblast", + "Leningrad region" to "leningrad", + "Krasnodar region" to "krasnodar", + "Chuvashia" to "chuvashia", + "Udmurtia" to "udmurtia", + "Bashkiria" to "bashkortostan", + "Khakasia" to "khakassia", + "Zabaikalye" to "zabaikalsky", + "Primorye" to "primorye", + "Yakutia" to "yakutia", + "Yakutsk" to "yakutia", + "Khanty-Mansiysk" to "khmao", + ) + for ((query, key) in expected) assertEquals(query, key, first(query)) + } + + /** + * «Moscow» still means the city first: «Oblast» is not a word the search + * drops (that would tie the two and hand Moscow Oblast the city's name), + * only a word «region» may stand for. + */ + @Test + fun `region stands for oblast without making oblast a stop word`() { + assertEquals("moscow", first("moscow")) + assertEquals(MatchVia.NAME, search.search("moscow").first().via) + assertEquals("moscow-oblast", first("Moscow Oblast")) + assertFalse("moscow" in keys("Moscow region")) + } + @Test fun `a code finds its region`() { assertEquals(listOf("leningrad"), keys("47")) diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt index 59e07534..7ead39c5 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/catalog/SchoolDirectoryTest.kt @@ -183,12 +183,22 @@ class SchoolDirectoryTest { assertTrue(api.asked.isEmpty()) } + /** + * «Казань №» is both: the numero sign makes it a school's name worth asking + * the directory about, and «Казань» is a city the catalog places on its + * own. A query the catalog knows nothing of would pass whatever became of + * its answer, because that answer is empty either way. + */ @Test fun `a directory that fails leaves the catalog's answer standing`() = runTest { val api = FakeDirectoryApi(failure = statusError(503, DirectoryApi.UNAVAILABLE_HEADER to "spent")) - val result = lookup(api).find("лицей 1535") + val result = lookup(api).find("Казань №") + // The directory really was asked, and really failed. + assertEquals(1, api.asked.size) assertEquals(SchoolLookup.Failed(DirectoryProblem.Spent(null)), result.bySchool) + assertEquals("tatarstan", result.byName.firstOrNull()?.region?.key) + assertEquals("tatarstan", result.suggested.firstOrNull()?.key) } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt index d9acd987..2476153f 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/diary/DiaryImportTest.kt @@ -217,20 +217,43 @@ class DiaryImportTest { assertFalse(failed.resumable) } + /** + * 19:30 UTC on Sunday 27 September is 02:30 on Monday in Tomsk (UTC+7) and + * still 22:30 on Sunday in Moscow (UTC+3): the one kind of instant at which + * the diary's zone and the zone that used to be hard-coded here disagree. + * An instant both call Monday would pass with either. + */ + private val tomskMondayMoscowSunday = java.time.Instant.parse("2026-09-27T19:30:00Z") + + private val tomskSession = DiarySession( + login = "parent", + token = "ours", + target = DiaryTarget.netschool("tomsk", 5, null, "parent", "Asia/Tomsk"), + ) + @Test fun `the weeks are cut in the diary's zone, not the phone's`() = runTest { - // 22:30 UTC on Sunday is already Monday in Tomsk (UTC+7). - val tomsk = DiarySession( - login = "parent", - token = "ours", - target = DiaryTarget.netschool("tomsk", 5, null, "parent", "Asia/Tomsk"), - ) - val rig = DiaryRig(store = MemoryDiaryStore(session = tomsk)) - rig.clock.now = java.time.Instant.parse("2026-09-27T22:30:00Z") + val rig = DiaryRig(store = MemoryDiaryStore(session = tomskSession)) + rig.clock.now = tomskMondayMoscowSunday rig.import.run(choose = neverAsked).toList() - assertTrue(rig.api.calls.contains("schedule 1 2026-09-28..2026-10-11")) + assertTrue(rig.api.calls.toString(), rig.api.calls.contains("schedule 1 2026-09-28..2026-10-11")) + // Moscow's Sunday would have fetched the fortnight before. + assertFalse(rig.api.calls.toString(), rig.api.calls.contains("schedule 1 2026-09-21..2026-10-04")) + } + + @Test + fun `refreshIfStale cuts the weeks in the diary's zone too`() = runTest { + val rig = DiaryRig(store = MemoryDiaryStore(session = tomskSession, student = 1)) + rig.clock.now = tomskMondayMoscowSunday + + assertEquals(true, rig.import.refreshIfStale().getOrThrow()) + + assertEquals( + listOf("schedule 1 2026-09-28..2026-10-11", "homework 1 2026-09-28..2026-10-11"), + rig.api.calls, + ) } @Test @@ -265,18 +288,80 @@ class DiaryImportTest { assertEquals(DiarySignInProblem.ReauthRequired, result.exceptionOrNull()) } + /** + * Asked while the import's own schedule request is in flight — a stored + * pupil, and a week not yet stamped — so a refresh that ignored the import + * would get as far as a second schedule request. Asked any earlier (while + * the pupil is still being chosen) it returns `false` for want of a pupil, + * lock or no lock. + */ @Test fun `refreshIfStale is a no-op while an import is running`() = runTest { - val rig = DiaryRig(api = ScriptedDiaryApi(students = listOf(student(1), student(2)))) + val rig = DiaryRig(store = MemoryDiaryStore(student = 1)) + var asked = false var during: Result? = null + rig.api.duringRequest = { route -> + // Once: a refresh that did get through sends a schedule request of + // its own, which comes back through here. + if (route.startsWith("schedule") && !asked) { + asked = true + during = rig.import.refreshIfStale() + } + } - rig.import.run(choose = { students -> - during = rig.import.refreshIfStale() - students.first() - }).toList() + val last = rig.import.run(choose = neverAsked).toList().last() + assertTrue(last is DiaryImportProgress.Done) + assertTrue(asked) assertEquals(false, during?.getOrThrow()) - assertEquals(1, rig.api.calls.count { it.startsWith("schedule") }) + assertEquals(listOf("schedule 1 $weeks"), rig.api.calls.filter { it.startsWith("schedule") }) + assertEquals(listOf("homework 1 $weeks"), rig.api.calls.filter { it.startsWith("homework") }) + } + + /** + * The container's sign-in seeds the pupils the registration answered, into + * a cache the sign-in has just emptied for a new account — which is exactly + * where taking the generation before the registration, or seeding nothing, + * would leave the import asking for the pupils again. + */ + @Test + fun `the pupils a sign-in registered are seeded after it empties the cache, and not asked for again`() = runTest { + for (path in listOf("signIn", "register")) { + val rig = DiaryRig() + // What the last account left, which a new account's sign-in empties. + rig.cache.putStudents(rig.cache.generation(), listOf(pupil(9))) + val seeding = SeedingDiarySignIn(ClearingSignIn(rig), rig.cache) + + when (path) { + "signIn" -> seeding.signIn(DiaryTarget.petersburg("parent"), "secret").getOrThrow() + else -> seeding.register( + com.lumenpearson.lessons.core.data.upstream.UpstreamSession.Petersburg( + target = DiaryTarget.petersburg("parent"), + token = "never read", + openedAt = rig.clock.now, + ), + ).getOrThrow() + } + assertEquals(path, listOf(1L), rig.cache.students.first().students.map { it.id }) + + rig.import.run(choose = neverAsked).toList() + + assertFalse(path, rig.api.calls.contains("students")) + } + } + + /** A sign-in that does what [com.lumenpearson.lessons.core.data.repository.DiarySignInImpl] does for a new account: empties the cache, then answers. */ + private inner class ClearingSignIn(private val rig: DiaryRig) : + com.lumenpearson.lessons.core.data.repository.DiarySignIn by UnusedSignIn { + private suspend fun registered(): Result { + rig.cache.clear() + val session = rig.store.currentDiarySession()!! + return Result.success(com.lumenpearson.lessons.core.data.repository.DiaryRegistration(session, listOf(pupil(1)))) + } + + override suspend fun register(upstream: com.lumenpearson.lessons.core.data.upstream.UpstreamSession) = registered() + + override suspend fun signIn(target: DiaryTarget, password: String) = registered() } private fun pupil(id: Long) = DiaryStudent( diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt index 909673d0..81e62493 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInTest.kt @@ -24,6 +24,7 @@ import com.lumenpearson.lessons.core.data.upstream.MutableClock import com.lumenpearson.lessons.core.data.upstream.NetSchoolScript import com.lumenpearson.lessons.core.data.upstream.NetSchoolSignIn import com.lumenpearson.lessons.core.data.upstream.PETERSBURG_JWT +import com.lumenpearson.lessons.core.data.upstream.PetersburgSignIn import com.lumenpearson.lessons.core.data.upstream.SCRIPT_SESSION_COOKIE import com.lumenpearson.lessons.core.data.upstream.Vectors import com.lumenpearson.lessons.core.data.upstream.UpstreamHttp @@ -71,7 +72,9 @@ class DiarySignInTest { private lateinit var server: MockWebServer private lateinit var script: NetSchoolScript private val api = ScriptedDiaryApi() - private val store = RecordingStore() + /** Every forget, pupil selection and session write, in the order they happened. */ + private val events = mutableListOf() + private val store = RecordingStore(events) private val clock = MutableClock() private var forgotten = 0 @@ -210,6 +213,27 @@ class DiarySignInTest { assertEquals(0, api.capabilityCalls) } + /** + * A login pasted from a chat carries invisible characters — bidi isolates + * around it, a zero-width space after it. The server always cleaned them + * before any upstream call; the diary is sent, and our server registers, + * the same cleaned login, and one that cleans to under three characters is + * refused with nothing sent anywhere. + */ + @Test + fun `a pasted login goes to the diary and the registration cleaned, as the server cleans it`() = runBlocking { + signIn().signIn(DiaryTarget.petersburg("\u2068parent@example.com\u2069\u200b"), "secret").getOrThrow() + + val sent = Json.parseToJsonElement(script.to(PetersburgSignIn.LOGIN_PATH).single().body!!.utf8()).jsonObject + assertEquals("parent@example.com", sent.getValue("login").jsonPrimitive.content) + assertEquals("parent@example.com", api.registered.single().login) + assertEquals("parent@example.com", store.session!!.target.login) + + val failure = signIn().openUpstream(netschoolTarget(login = "ab\u200b"), "hunter2").exceptionOrNull() + assertEquals(DiarySignInProblem.LoginTooShort, failure) + assertEquals(1, server.requestCount) + } + @Test fun `a login too short fails before anything is sent`() = runBlocking { val failure = signIn().openUpstream(netschoolTarget(login = " ab "), "hunter2").exceptionOrNull() @@ -441,9 +465,14 @@ class DiarySignInTest { assertEquals(0, forgotten) assertEquals(7L, store.student) + events.clear() signIn().signIn(netschoolTarget(login = "other-parent"), "hunter2").getOrThrow() assertEquals(1, forgotten) assertNull(store.student) + // In this order: were the write first, a process dying between the two + // would leave the new account's bearer over the old account's rows, + // and every later sign-in to it would match and keep them. + assertEquals(listOf("forget", "select:null", "write"), events) } @Test @@ -463,7 +492,10 @@ class DiarySignInTest { store = store, directory = { directory }, client = { UpstreamHttp.client { directory.allowedOrigins() } }, - forgetLocal = { forgotten++ }, + forgetLocal = { + forgotten++ + events += "forget" + }, clock = clock, ioDispatcher = Dispatchers.Unconfined, ) @@ -510,7 +542,7 @@ class DiarySignInTest { } /** The store, with nothing in it but what was last written. */ - private class RecordingStore : DiarySessionStore { + private class RecordingStore(private val events: MutableList) : DiarySessionStore { var session: DiarySession? = null var target: DiaryTarget? = null var student: Long? = null @@ -518,6 +550,7 @@ class DiarySignInTest { override val diarySession: Flow get() = MutableStateFlow(session) override suspend fun currentDiarySession(): DiarySession? = session override suspend fun writeDiarySession(value: DiarySession) { + events += "write" session = value target = value.target } @@ -536,6 +569,7 @@ class DiarySignInTest { override suspend fun currentDiaryTarget(): DiaryTarget? = target override val selectedStudentId: Flow get() = MutableStateFlow(student) override suspend fun selectStudent(id: Long?) { + events += "select:$id" student = id } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt index 701192ab..2708f8d0 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorkerSourceTest.kt @@ -17,18 +17,39 @@ import org.junit.Test * * No behaviour test can see a read that is simply never supposed to exist, * so this reads the sources the way `DaoDeletePolicyTest` reads the SQL: the - * sync worker, every file of the widget module, and the alerts — the three - * things the system wakes on its own. What it cannot see: a diary read reached - * through some other name, or a new background entry point outside these - * folders. + * sync worker, every file of the widget module, the alerts, and every class a + * manifest names as the application, a receiver or a service — each of which + * the system starts on its own. The application's `onCreate` is the one most + * easily missed: it runs on every cold start, including the one a widget + * update or an alarm causes with the screen off, and it is the obvious place + * to put an «on app start» refresh. Activities are left out on purpose: they + * are the one kind of entry point with a person in front of it. + * + * What it cannot see: a diary read reached through some other name, or a + * background entry point no manifest declares (a WorkManager worker other than + * the sync worker). */ class SyncWorkerSourceTest { private companion object { /** The types and the container properties that reach the diary. */ val DIARY = Regex("""\b(DiaryRepository|DiaryImport|DiaryCache|DiaryApi|diaryRepository|diaryImport|diaryCache)\b""") + + /** `]*?android:name\s*=\s*"([^"]+)"""") + + val NAMESPACE = Regex("""namespace\s*=\s*"([^"]+)"""") + + /** What the manifests declare today; a missing one means the discovery below broke, not the rule. */ + val KNOWN = setOf( + "com.lumenpearson.lessons.LessonsApplication", + "com.lumenpearson.lessons.core.data.notifications.SchoolAlertReceiver", + "com.lumenpearson.lessons.widget.LessonsWidgetReceiver", + "com.lumenpearson.lessons.widget.tick.WidgetTickReceiver", + ) } + private val android = File("../..") private val worker = File("src/main/kotlin/com/lumenpearson/lessons/core/data/sync/SyncWorker.kt") private val widget = File("../../widget/src/main") private val alerts = File("src/main/kotlin/com/lumenpearson/lessons/core/data/notifications") @@ -36,16 +57,46 @@ class SyncWorkerSourceTest { private fun kotlinUnder(root: File): List = root.walkTopDown().filter { it.isFile && it.extension == "kt" }.toList() + /** Every module's own `src/main`, found rather than listed, so a sixth module is read too. */ + private fun modules(): List = + android.walkTopDown() + .onEnter { it.name !in setOf("build", ".gradle", ".idea", "kotlin", "res", "test", "androidTest") } + .filter { it.isFile && it.invariantSeparatorsPath.endsWith("/src/main/AndroidManifest.xml") } + .map { it.parentFile.parentFile.parentFile } + .toList() + + /** Class name → its source file, for every application, receiver and service a manifest of ours declares. */ + private fun declaredEntryPoints(): Map = modules().flatMap { module -> + val manifest = File(module, "src/main/AndroidManifest.xml").readText() + val namespace = File(module, "build.gradle.kts").takeIf { it.isFile } + ?.let { NAMESPACE.find(it.readText())?.groupValues?.get(1) } + DECLARED.findAll(manifest).mapNotNull { match -> + val name = match.groupValues[2] + val qualified = when { + name.startsWith(".") -> (namespace ?: error("${module.path} declares $name without a namespace")) + name + name.startsWith("com.lumenpearson.") -> name + else -> return@mapNotNull null // a library's class, not ours to read + } + qualified to File(module, "src/main/kotlin/" + qualified.replace('.', '/') + ".kt") + }.toList() + }.toMap() + @Test fun `the sources are where this test thinks they are`() { assertTrue(worker.absolutePath, worker.isFile) assertTrue(widget.absolutePath, kotlinUnder(widget).size >= 5) assertTrue(alerts.absolutePath, kotlinUnder(alerts).size >= 3) + val declared = declaredEntryPoints() + assertTrue("found ${declared.keys}", declared.keys.containsAll(KNOWN)) + for ((name, file) in declared) { + assertTrue("$name is declared, but its source is not at ${file.path}; teach this test where it is", file.isFile) + } } @Test - fun `the worker and the widget never reference the diary`() { - val offenders = (listOf(worker) + kotlinUnder(widget) + kotlinUnder(alerts)) + fun `the worker, the widget and every declared background entry point never reference the diary`() { + val offenders = (listOf(worker) + kotlinUnder(widget) + kotlinUnder(alerts) + declaredEntryPoints().values) + .distinctBy { it.canonicalPath } .flatMap { file -> file.readLines().mapIndexedNotNull { index, line -> DIARY.find(line)?.let { "${file.path}:${index + 1}: ${line.trim()}" } @@ -65,5 +116,9 @@ class SyncWorkerSourceTest { assertTrue(DIARY.containsMatchIn("Graph.container.diaryRepository.students()")) assertTrue(DIARY.containsMatchIn("val import: DiaryImport")) assertTrue(!DIARY.containsMatchIn("DiaryRepositoryImplementation")) + val application = """""" + assertEquals(".LessonsApplication", DECLARED.find(application)?.groupValues?.get(2)) } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt index 36b09514..f70402ec 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/DiaryProtocolVectorsTest.kt @@ -1,6 +1,7 @@ package com.lumenpearson.lessons.core.data.upstream import com.lumenpearson.lessons.core.data.catalog.RegionCatalog +import com.lumenpearson.lessons.core.data.repository.DiaryLogin import com.lumenpearson.lessons.core.data.repository.DiarySessionIdleDays import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryTarget @@ -114,6 +115,37 @@ class DiaryProtocolVectorsTest { } } + /** + * The login the diary is sent and our server registers is the one the + * server's `_clean_login_value` would have made of what was typed — asked of + * the cleaner, and then of both sign-ins, which is where a login pasted + * with a bidi mark around it used to go out as pasted. + */ + @Test + fun `login cleaning matches the shared vectors, and both sign-ins send the cleaned login`() = runBlocking { + val login = Vectors.root.getValue("login").jsonObject + assertEquals(login.getValue("min_code_points").jsonPrimitive.int, DiaryLogin.MIN_CODE_POINTS) + for (case in Vectors.cases(login, "cases")) { + val typed = case.getValue("typed").jsonPrimitive.content + val wanted = case.getValue("sent").jsonPrimitive.contentOrNull + assertEquals(typed.quoted(), wanted, DiaryLogin.clean(typed)) + if (wanted == null) continue + + val script = NetSchoolScript() + server.dispatcher = script + val petersburg = PetersburgSignIn(clientFor(server), originOf(server), clock) + .signIn(DiaryTarget.petersburg(typed), "secret") + val body = Json.parseToJsonElement(script.to(PetersburgSignIn.LOGIN_PATH).single().body!!.utf8()) + assertEquals(typed.quoted(), wanted, body.jsonObject.getValue("login").jsonPrimitive.content) + assertEquals(typed.quoted(), wanted, petersburg.target.login) + + val netschool = NetSchoolSignIn(clientFor(server), clock) + .signIn(regionAt(server), netschoolTarget(login = typed), "hunter2") + assertEquals(typed.quoted(), wanted, script.to(NetSchoolSignIn.LOGIN_PATH).single().form()["un"]) + assertEquals(typed.quoted(), wanted, netschool.target.login) + } + } + // ---- Petersburg ----------------------------------------------------------- @Test @@ -313,6 +345,35 @@ class DiaryProtocolVectorsTest { } } + /** + * Bodies no JSON value can stand for, sent as bytes at one step. The + * phone's parser read «» as a word and «{"at": abc}» as an object, + * and so called the first a dead diary and the second a wrong password, + * where the server's `json.loads` calls both unreadable. + */ + @Test + fun `raw answers match the shared vectors`() = runBlocking { + for (case in Vectors.cases(Vectors.netschool, "raw_answer_cases")) { + val step = case.getValue("step").jsonPrimitive.content + val label = "$step ${case["body"]}" + val raw = { + rawAnswer( + status = case.getValue("status").jsonPrimitive.int, + contentType = case.getValue("content_type").jsonPrimitive.content, + body = case.getValue("body").jsonPrimitive.content, + ) + } + val script = when (step) { + "logindata" -> NetSchoolScript(logindata = raw) + "getdata" -> NetSchoolScript(getdata = raw) + "login" -> NetSchoolScript(logins = ArrayDeque(listOf(raw))) + else -> error("unknown step $step") + } + val outcome = signIn(script) + assertEquals(label, case.getValue("expect").jsonPrimitive.content, kindOf(outcome.exceptionOrNull())) + } + } + @Test fun `role pick matches the shared vectors`() { for (case in Vectors.cases(Vectors.netschool, "role_pick")) { diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt index 94d57dca..6a4c093b 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamHttpTest.kt @@ -3,10 +3,17 @@ package com.lumenpearson.lessons.core.data.upstream import com.lumenpearson.lessons.core.data.network.AuthInterceptor import com.lumenpearson.lessons.core.data.network.BaseUrlInterceptor import com.lumenpearson.lessons.core.data.network.DiaryAuthInterceptor +import java.io.EOFException import java.io.IOException +import java.net.SocketException import java.net.UnknownHostException +import java.security.cert.CertPathBuilderException +import java.security.cert.CertPathValidatorException +import java.security.cert.CertificateException +import java.security.cert.CertificateExpiredException import java.util.concurrent.TimeUnit import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException import kotlinx.coroutines.runBlocking import mockwebserver3.MockResponse import mockwebserver3.MockWebServer @@ -148,9 +155,11 @@ class UpstreamHttpTest { } @Test - fun `a TLS failure is untrusted, never offline`() = runBlocking { + fun `a certificate the phone cannot trust is untrusted, never offline`() = runBlocking { + // Android's shape: the handshake fails because a CertificateException + // wraps the path validator's «Trust anchor for certification path not found». val client = clientFor(server).newBuilder() - .addInterceptor { throw SSLHandshakeException("PKIX path building failed") } + .addInterceptor { throw handshake("Trust anchor", CertificateException(CertPathValidatorException("no anchor"))) } .build() val failure = runCatching { @@ -160,6 +169,47 @@ class UpstreamHttpTest { assertTrue("got $failure", failure is UpstreamFailure.Untrusted) } + /** + * Only a failure that examined the certificate is a trust problem. The + * JVM's own «PKIX path building failed» carries a CertificateException + * subclass, an expired certificate is one, and a name the certificate does + * not cover is OkHttp's SSLPeerUnverifiedException. + */ + @Test + fun `every shape of a real trust failure is untrusted`() { + val trust = listOf( + handshake("PKIX path building failed", CertificateException("PKIX", CertPathBuilderException("unable to find path"))), + handshake("expired", CertificateExpiredException("NotAfter: 2020")), + handshake("validator", CertPathValidatorException("revoked")), + SSLPeerUnverifiedException("Hostname region.zabedu.ru not verified"), + IOException("wrapped", SSLPeerUnverifiedException("peer not authenticated")), + ) + for (failure in trust) { + assertTrue("$failure", UpstreamHttp.classify(failure) is UpstreamFailure.Untrusted) + } + } + + /** + * A handshake the network broke never looked at a certificate: Conscrypt + * says «Connection reset by peer» or «Connection closed by peer» for a + * firewall or a flaky link, the JVM «Remote host terminated the handshake» + * over an EOF. Calling that «the phone does not trust the diary» offered no + * retry for something a retry fixes. + */ + @Test + fun `a handshake the network broke is unavailable, not untrusted`() { + val broken = listOf( + handshake("Read error: ssl=0x7b: I/O error during system call, Connection reset by peer", SocketException("Connection reset")), + handshake("Connection closed by peer", null), + handshake("Remote host terminated the handshake", EOFException("SSL peer shut down incorrectly")), + handshake("Received fatal alert: handshake_failure", null), + ) + for (failure in broken) { + val classified = UpstreamHttp.classify(failure) + assertTrue("$failure: $classified", classified is UpstreamFailure.Unavailable) + } + } + @Test fun `a timeout is unavailable and says it timed out`() = runBlocking { server.enqueue(MockResponse.Builder().code(200).headersDelay(2, TimeUnit.SECONDS).build()) @@ -196,6 +246,9 @@ class UpstreamHttpTest { assertTrue(failure is UpstreamFailure.Offline) } + private fun handshake(message: String, cause: Throwable?): SSLHandshakeException = + SSLHandshakeException(message).apply { if (cause != null) initCause(cause) } + @Test fun `a session cookie is read from the last live one of its name`() { val url = "https://region.zabedu.ru/webapi/login".toHttpUrl() diff --git a/server/app/catalog/data/regions.json b/server/app/catalog/data/regions.json index 07011e8c..bff1ae84 100644 --- a/server/app/catalog/data/regions.json +++ b/server/app/catalog/data/regions.json @@ -1870,7 +1870,9 @@ { "aliases": [ "Забайкалье", - "Читинская область" + "Читинская область", + "Zabaikalye", + "Zabaykalye" ], "cities": [ "Чита", @@ -2220,7 +2222,8 @@ }, { "aliases": [ - "Приморье" + "Приморье", + "Primorye" ], "cities": [ "Владивосток", @@ -6134,6 +6137,15 @@ "федерального", "значения" ], + "synonyms": { + "region": [ + "oblast", + "krai" + ], + "st": [ + "saint" + ] + }, "translit": [ [ "shch", @@ -6143,6 +6155,14 @@ "sch", "щ" ], + [ + "iya", + "ия" + ], + [ + "tsk", + "тск" + ], [ "zh", "ж" @@ -6179,6 +6199,18 @@ "ye", "е" ], + [ + "ia", + "ия" + ], + [ + "iy", + "ий" + ], + [ + "yy", + "ый" + ], [ "a", "а" diff --git a/server/scripts/region_catalog.py b/server/scripts/region_catalog.py index 0f2e148c..f9b3d99e 100644 --- a/server/scripts/region_catalog.py +++ b/server/scripts/region_catalog.py @@ -522,7 +522,7 @@ def _search(overlay: dict[str, Any]) -> dict[str, Any]: _fields( search, {"fold", "stop_words", "latin_layout", "cyrillic_layout", "translit", "school_words"}, - set(), + {"synonyms"}, "[search]", ) latin, cyrillic = search["latin_layout"], search["cyrillic_layout"] @@ -537,6 +537,19 @@ def _search(overlay: dict[str, Any]) -> dict[str, Any]: raise CatalogError("[search]: translit is a list of [latin, cyrillic] pairs") if [len(pair[0]) for pair in pairs] != sorted((len(pair[0]) for pair in pairs), reverse=True): raise CatalogError("[search]: translit must list longer Latin spellings first") + synonyms = search.get("synonyms", {}) + # One lower-case Latin word for another: the phone compares them after it has + # folded case and cut the query at every punctuation mark, so anything else + # here could never be typed. + word = re.compile(r"[a-z]+") + if any( + not word.fullmatch(typed) + or not isinstance(meant, list) + or not meant + or any(not isinstance(each, str) or not word.fullmatch(each) for each in meant) + for typed, meant in synonyms.items() + ): + raise CatalogError("[search]: synonyms map a lower-case Latin word to a list of them") return { "fold": dict(search["fold"]), "stop_words": list(search["stop_words"]), @@ -544,6 +557,7 @@ def _search(overlay: dict[str, Any]) -> dict[str, Any]: "cyrillic_layout": cyrillic, "translit": [list(pair) for pair in pairs], "school_words": list(search["school_words"]), + "synonyms": {typed: list(meant) for typed, meant in synonyms.items()}, } diff --git a/server/scripts/region_catalog.toml b/server/scripts/region_catalog.toml index 7cef140c..53801a65 100644 --- a/server/scripts/region_catalog.toml +++ b/server/scripts/region_catalog.toml @@ -39,7 +39,8 @@ # after `app.catalog.normalise_name` (case, ё, punctuation, spaces) and must place # exactly one region each. None of them has been checked against a live answer. # - `aliases` are what people type instead of the name: official long forms and the -# informal ones. `cities` are a few large towns, so that «Тольятти» finds Самарская. +# informal ones, and an English spelling where it is neither a word of `name_en` +# nor something `translit` can spell back («Zabaikalye»). `cities` are a few large towns, so that «Тольятти» finds Самарская. # Both are search hints for the phone, never shown as a region's name. # # Nothing in this file may describe signing in on a diary's own page inside the app: @@ -73,10 +74,15 @@ latin_layout = "`qwertyuiop[]asdfghjkl;'zxcvbnm,." cyrillic_layout = "ёйцукенгшщзхъфывапролджэячсмитьбю" # Longest first: the phone takes the first pair that matches at each position. # Best effort, not a standard — «moskva», «kazan», «samara» and «tatarstan» come -# out whole, and a prefix is enough for the search to land. +# out whole, and a prefix is enough for the search to land. The endings are how +# English writes the Russian ones — «Chuvashia», «Bashkiriya», «Khanty-Mansiysk», +# «Yakutsk» — and without them a single letter at a time gives «чувашиа», +# «мансиыск» and «якуцк», which match nothing. translit = [ - ["shch", "щ"], ["sch", "щ"], ["zh", "ж"], ["kh", "х"], ["ts", "ц"], ["ch", "ч"], + ["shch", "щ"], ["sch", "щ"], ["iya", "ия"], ["tsk", "тск"], + ["zh", "ж"], ["kh", "х"], ["ts", "ц"], ["ch", "ч"], ["sh", "ш"], ["yo", "ё"], ["yu", "ю"], ["ya", "я"], ["ye", "е"], + ["ia", "ия"], ["iy", "ий"], ["yy", "ый"], ["a", "а"], ["b", "б"], ["c", "к"], ["d", "д"], ["e", "е"], ["f", "ф"], ["g", "г"], ["h", "х"], ["i", "и"], ["j", "й"], ["k", "к"], ["l", "л"], ["m", "м"], ["n", "н"], ["o", "о"], ["p", "п"], ["q", "к"], ["r", "р"], ["s", "с"], ["t", "т"], ["u", "у"], @@ -92,6 +98,15 @@ school_words = [ "общеобразовательная", "№", "n", "no", "номер", ] +# What an English word typed may stand for among the words of an English name. +# «St» is how «Saint» is abbreviated, and «region» is what English calls an oblast +# or a krai. The word typed is still tried as itself. «oblast» is deliberately not a +# stop word the way «область» is: «moscow» would then tie Moscow Oblast with Moscow, +# and a tie goes to the list's order rather than to the city somebody meant. +[search.synonyms] +st = ["saint"] +region = ["oblast", "krai"] + [search.fold] "ё" = "е" "‐" = " " @@ -615,7 +630,9 @@ code = "75" iso = "RU-ZAB" name_en = "Zabaykalsky Krai" zone = "Asia/Chita" -aliases = ["Забайкалье", "Читинская область"] +# «Zabaikalye» is how English writes «Забайкалье»; no transliteration table +# turns it back, because the soft sign is not written at all. +aliases = ["Забайкалье", "Читинская область", "Zabaikalye", "Zabaykalye"] cities = ["Чита", "Краснокаменск"] dadata_names = ["Забайкальский край", "Забайкальский"] @@ -670,7 +687,7 @@ code = "25" iso = "RU-PRI" name_en = "Primorsky Krai" zone = "Asia/Vladivostok" -aliases = ["Приморье"] +aliases = ["Приморье", "Primorye"] cities = ["Владивосток", "Уссурийск", "Находка"] dadata_names = ["Приморский край", "Приморский"] diff --git a/server/tests/test_diary_protocol_vectors.py b/server/tests/test_diary_protocol_vectors.py index b4a48a13..0743eeb9 100644 --- a/server/tests/test_diary_protocol_vectors.py +++ b/server/tests/test_diary_protocol_vectors.py @@ -27,7 +27,9 @@ import httpx import pytest +from pydantic import ValidationError +from app import schemas from app.api import cron from app.providers.diary import http as diary_http from app.providers.diary.errors import ( @@ -50,6 +52,8 @@ FLOW = NETSCHOOL["flow"] PETERSBURG = VECTORS["petersburg"] REGION = region_for("zabaikalsky") +#: Shaped like the ``X-JWT-Token`` Petersburg issues, which is what a registration takes. +_JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjF9.c2lnbmF0dXJl" @pytest.fixture(autouse=True) @@ -235,6 +239,49 @@ def test_the_login_form_carries_exactly_the_vector_fields(): assert NETSCHOOL["login_form_fields"] == ["loginType", "scid", "un", "pw", "pw2", "lt", "ver"] +@pytest.mark.parametrize( + "case", + NETSCHOOL["raw_answer_cases"], + ids=lambda c: f"{c['step']}-{c['body'].strip()}", +) +async def test_netschool_raw_answers_match_the_vectors(monkeypatch, case): + """Bodies no JSON value can stand for, sent as bytes at one step of an + otherwise ordinary sign-in. A parser more lenient than ``json.loads`` + reads «» as a word and «{"at": abc}» as an object, and then calls + the first a dead diary and the second a wrong password.""" + raw = httpx.Response( + case["status"], + content=case["body"].encode(), + headers={"content-type": case["content_type"]}, + ) + steps = { + "logindata": "/webapi/logindata", + "getdata": "/webapi/auth/getdata", + "login": "/webapi/login", + } + + def handler(request: httpx.Request) -> httpx.Response: + path = request.url.path + if path == steps[case["step"]]: + return raw + if path == "/webapi/logindata": + return _json(200, FLOW["logindata"]) + if path == "/webapi/auth/getdata": + return _json(200, FLOW["getdata"]) + if path == "/webapi/login": + return _json(200, {"at": "x"}) + return _json(404, {}) + + _serve_netschool(monkeypatch, handler) + client = nsclient.NetSchoolClient(REGION, {"v": 1, "region": REGION.key}) + try: + await client.login(FLOW["login"], FLOW["password"], FLOW["school_id"]) + except DiaryError as failure: + assert _kind(failure) == case["expect"] + return + assert case["expect"] == "ok" + + @pytest.mark.parametrize("case", NETSCHOOL["role_pick"], ids=lambda c: json.dumps(c["body"])) def test_netschool_role_pick_matches_the_vectors(case): assert nsclient.NetSchoolClient._pick_parent_role(case["body"]) == case["expect"] @@ -398,6 +445,26 @@ def test_header_token_rule_matches_the_vectors(case): assert (re.fullmatch(pattern, case["value"]) is not None) is case["ok"] +@pytest.mark.parametrize("case", VECTORS["login"]["cases"], ids=lambda c: ascii(c["typed"])) +def test_login_cleaning_matches_the_vectors(case): + """The login the server keys a family's corrections on is the login the + phone sends the diary and registers — one cleaning, on both sides. The + registration body and the password sign-in each run it, so each is asked.""" + wanted = case["sent"] + assert VECTORS["login"]["min_code_points"] == 3 + for model in (schemas.DiaryLoginIn, schemas.PetersburgSessionIn): + fields: dict[str, Any] = {"login": case["typed"]} + if model is schemas.DiaryLoginIn: + fields["password"] = "secret" + else: + fields |= {"provider": "petersburg", "credential": {"token": _JWT}} + if wanted is None: + with pytest.raises(ValidationError): + model.model_validate(fields) + else: + assert model.model_validate(fields).login == wanted + + def test_user_agent_and_petersburg_origin_are_the_vectors(): assert diary_http.USER_AGENT == VECTORS["user_agent"] assert pbclient.USER_AGENT == VECTORS["user_agent"] diff --git a/server/tests/test_region_catalog.py b/server/tests/test_region_catalog.py index 95a9251e..92885648 100644 --- a/server/tests/test_region_catalog.py +++ b/server/tests/test_region_catalog.py @@ -656,3 +656,24 @@ def transliterate(text: str) -> str: assert transliterate("moskva") == "москва" assert transliterate("chelyabinsk") == "челябинск" assert "казань".startswith(transliterate("kazan")) + # The English endings of the Russian ones, which letter by letter came out + # as «чувашиа», «мансиыск» and «якуцк» and matched nothing. + assert transliterate("chuvashia") == "чувашия" + assert transliterate("bashkiriya") == "башкирия" + assert transliterate("mansiysk") == "мансийск" + assert transliterate("yakutsk") == "якутск" + + +def test_the_search_synonyms_are_english_words_for_the_names_words(): + """«St Petersburg» and «Moscow region» are how English writes two regions, + and neither is a word of their names. «oblast» stays out of the stop words: + dropping it would tie Moscow Oblast with Moscow on the query «moscow».""" + search = _committed()["search"] + assert search["synonyms"]["st"] == ["saint"] + assert "oblast" in search["synonyms"]["region"] + assert "oblast" not in search["stop_words"] + names = { + word for region in _committed()["regions"] for word in region["name_en"].lower().split() + } + for meant in search["synonyms"].values(): + assert set(meant) <= names, meant diff --git a/server/tests/vectors/diary_protocol.json b/server/tests/vectors/diary_protocol.json index a946e6d1..744b9ca2 100644 --- a/server/tests/vectors/diary_protocol.json +++ b/server/tests/vectors/diary_protocol.json @@ -91,6 +91,20 @@ {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": false, "expect": {"failure": "unexpected"}}, {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": true, "expect": {"failure": "bad_credentials", "message": null}} ], + "raw_answer_cases_about": "Answers given as the bytes the diary sent, for bodies no JSON value can stand for. The step's answer is replaced and the flow's own answers stand in for the rest. Whatever Python's json.loads refuses is unexpected on both sides, however lenient a parser could be about it: a single unquoted word, a leading zero, a bare word inside an object. NaN and Infinity are JSON to Python, so they are to the phone too.", + "raw_answer_cases": [ + {"step": "logindata", "status": 200, "content_type": "text/html", "body": "", "expect": "unexpected"}, + {"step": "logindata", "status": 200, "content_type": "application/json", "body": "{\"schoolLogin\": False}", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "text/html", "body": "", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "text/plain", "body": "Error", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "application/json", "body": "01", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "application/json", "body": "{\"salt\": \"333\", \"lt\": 1x}", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "application/json", "body": " {\"salt\": \"333\", \"lt\": \"1\", \"ver\": \"2\"}\n", "expect": "ok"}, + {"step": "login", "status": 200, "content_type": "text/plain", "body": "OK", "expect": "unexpected"}, + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": abc}", "expect": "unexpected"}, + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"timeOut\": NaN}", "expect": "ok"}, + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"timeOut\": -Infinity}", "expect": "ok"} + ], "role_pick": [ {"body": {"accountInfo": {"userRoles": [{"role": {"id": 7, "name": "Учитель"}}, {"role": {"id": 12, "name": "Родитель"}}]}}, "expect": "12"}, {"body": {"userRoles": [{"id": 5, "name": "Администратор"}]}, "expect": "5"}, @@ -142,6 +156,29 @@ {"value": "ключ", "ok": false} ] }, + "login": { + "about": "The login as both sides clean it before it goes anywhere: the server's schemas._clean_login_value, the phone's DiaryLogin.clean. Every character Python's str.isprintable refuses is dropped (controls, format characters, surrogates, private use, unassigned, and every separator but the plain space), then the ends are trimmed, and fewer than min_code_points code points left is no login. A sent of null is refused before anything is sent anywhere.", + "min_code_points": 3, + "cases": [ + {"typed": " parent@example.com ", "sent": "parent@example.com"}, + {"typed": "⁨parent@example.com⁩", "sent": "parent@example.com"}, + {"typed": "‎parent", "sent": "parent"}, + {"typed": "parent", "sent": "parent"}, + {"typed": "par­ent", "sent": "parent"}, + {"typed": " parent ", "sent": "parent"}, + {"typed": "\tparent\r\n", "sent": "parent"}, + {"typed": "a\u0000bc", "sent": "abc"}, + {"typed": "
abc
", "sent": "abc"}, + {"typed": "abc", "sent": "abc"}, + {"typed": "ab͸c", "sent": "abc"}, + {"typed": "par ent", "sent": "par ent"}, + {"typed": "Иванов", "sent": "Иванов"}, + {"typed": "😀ab", "sent": "😀ab"}, + {"typed": "ab​", "sent": null}, + {"typed": " ab ", "sent": null}, + {"typed": "​​​", "sent": null} + ] + }, "header_token": { "pattern": "^[A-Za-z0-9._~+/=-]+$", "cases": [ From fb8a70ccb9113341769623e2e02d69b49081c951 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 18:46:05 +0000 Subject: [PATCH 20/30] Let the widget say which way in a phone took, and tell a diary-only phone where its diary is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The widget chose its empty sentence from one flag, whether a class session existed. That was two answers for what is now three states: a phone in no class and no diary, a phone in a class whose timetable has not synced, and a phone that reads its own school's diary and is in no class. The third fell into the first, so a family that had just signed in to its diary was told to «введите код класса» — a way in that is not theirs. The snapshot now carries `ShellMode`, read from `shellMode.current()` (one preferences read, the same rule the app shell uses), and `emptyTextRes(mode, size)` picks the sentence: - NONE: «Откройте приложение и подключитесь по коду класса или через свою школу» / «Откройте приложение». Reworded because there are two ways in now and the old text named only one. - CLASS: unchanged, «Расписание ещё не загружено — … потяните вниз». - DIARY: new «Виджет показывает расписание класса. Дневник — в приложении» / «Дневник — в приложении». Not «потяните вниз», which would promise a timetable no pull will ever bring. A read that throws still draws the CLASS sentence, the least wrong of three when nothing is known. Outside a class the widget no longer asks Room for a timetable at all, and `snapshotOf` ignores one if handed it, so the sentence and the lessons beside it cannot come from two answers to one question. The widget draws nothing from the diary, on purpose (#142): a background read would count as the family's activity and keep a session alive with nobody behind it. `SyncWorkerSourceTest` still scans every widget file and stays green. All twelve `WidgetSizeClass` rungs are untouched; which rungs get the short sentence is the old width rule, lifted into `emptyTextIsCompact` so a test can ask it. Tests: `EmptyTextTest` (12) asks each mode's sentence on NARROW and LARGE, that the three modes never share a sentence on any rung, that every narrow rung and WIDE get the short form, that NONE no longer names only the class code, that DIARY promises no pull-down in either language, that the snapshot carries its mode, and that outside a class a handed-in timetable draws nothing. `UnreadableSnapshotTest` and `BoundedSnapshotParityTest` follow the type change. Removing the class gate in `snapshotOf` fails the suite. Uncovered: nothing here has run on a device or a launcher. Whether the new sentences fit their rungs without a clip is by length only — Glance cannot measure or ellipsize — and the widget redrawing when the mode changes rests on the `DataSyncBroadcast` that `ModeAnnouncingDiaryStore` sends, which no test here composes. `docs/widget.md` does not yet describe the third sentence; that is the docs wave's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .../lessons/widget/LessonsWidget.kt | 45 ++-- .../lessons/widget/WidgetSnapshot.kt | 21 +- .../lessons/widget/ui/LessonsWidgetBody.kt | 68 ++++-- .../widget/src/main/res/values-en/strings.xml | 6 +- .../widget/src/main/res/values/strings.xml | 13 +- .../widget/BoundedSnapshotParityTest.kt | 3 +- .../lessons/widget/UnreadableSnapshotTest.kt | 19 +- .../lessons/widget/ui/EmptyTextTest.kt | 226 ++++++++++++++++++ 8 files changed, 341 insertions(+), 60 deletions(-) create mode 100644 android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt index 4ffc6e40..e5ca47e9 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt @@ -16,6 +16,7 @@ import androidx.glance.appwidget.action.actionStartActivity import androidx.glance.appwidget.provideContent import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.locale.AppLocale +import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.core.model.DayState import com.lumenpearson.lessons.core.model.DeepLink @@ -79,7 +80,7 @@ class LessonsWidget : GlanceAppWidget() { GlanceTheme { LessonsWidgetBody( state = snapshot.state, - signedIn = snapshot.signedIn, + mode = snapshot.mode, today = snapshot.today, homeworkDay = snapshot.homeworkDay, now = snapshot.now, @@ -103,20 +104,20 @@ class LessonsWidget : GlanceAppWidget() { /** * What to draw when the read itself failed. * - * `signedIn = true` on purpose, although nothing was read and nothing is - * known. The flag only chooses between two sentences, and the two are not - * equally wrong: «откройте приложение и потяните вниз» is harmless advice - * for somebody who has not joined a class, while «введите код класса» - * sends somebody who has joined one to the single screen that cannot help - * them — which is the exact failure [Snapshot.signedIn] was added to - * prevent, reintroduced here on the path where it is least visible. + * [ShellMode.CLASS] on purpose, although nothing was read and nothing is + * known. The mode only chooses a sentence, and the three are not equally + * wrong: «откройте приложение и потяните вниз» is harmless advice for + * anybody, while the other two tell somebody who has joined a class either + * to take a way in they have already taken or that the widget does not + * draw their timetable — which is the exact failure [Snapshot.mode] exists + * to prevent, reintroduced here on the path where it is least visible. */ internal fun unreadableSnapshot(): Snapshot = Snapshot( // device clock: the read failed, so there is no timetable to take a zone // from. The empty state this builds names no lesson and no time. now = LocalDateTime.now(), state = null, - signedIn = true, + mode = ShellMode.CLASS, today = null, homeworkDay = null, week = emptyList(), @@ -128,11 +129,12 @@ class LessonsWidget : GlanceAppWidget() { * Everything one render needs, gathered off the composition. * * @property state null whenever there is no cached timetable. - * @property signedIn whether a class session exists. Carried separately - * because a null [state] has two very different causes — nobody has - * entered a class code yet, or a class was joined but nothing has synced — - * and the widget used to tell every one of those users to go and enter a - * code they had already entered. + * @property mode which way this phone came in, if any. Carried separately + * because a null [state] has three very different causes — nobody has + * come in yet, a class was joined but nothing has synced, or the phone + * reads its own school's diary and has no class timetable at all — and + * one sentence for all of them told the families of the second and the + * third to take a way in they had already taken. * @property language the stored language choice, carried here rather than * read again at render time so that one snapshot means one preference * read. It is not a `WidgetOption`: the options decide *what* is drawn and @@ -141,7 +143,7 @@ class LessonsWidget : GlanceAppWidget() { data class Snapshot( val now: LocalDateTime, val state: DayState?, - val signedIn: Boolean, + val mode: ShellMode, val today: SchoolDay?, val homeworkDay: SchoolDay?, val week: List, @@ -198,9 +200,16 @@ class LessonsWidget : GlanceAppWidget() { // across it as the timetable's `nextSchoolDay`. The difference is some // two hundred days of lessons, events and homework read off Room on // every redraw, and a redraw happens on every tick of a countdown. - val timetable: Timetable? = container.timetableRepository.snapshotAroundToday() + // + // The mode first, and the timetable only in a class. The widget draws + // nothing from the diary on purpose (#142): a background read would + // count as the family's activity and keep a session alive with nobody + // behind it. Outside a class there is no class timetable to read, so + // Room is not asked at all. + val mode = container.shellMode.current().mode + val timetable: Timetable? = + if (mode == ShellMode.CLASS) container.timetableRepository.snapshotAroundToday() else null val settings = container.settingsRepository.settings.first() - val signedIn = container.sessionRepository.current() != null // The school's wall clock, not the phone's. These differ whenever the // device has travelled, and permanently for anyone following a school @@ -211,7 +220,7 @@ class LessonsWidget : GlanceAppWidget() { return snapshotOf( timetable = timetable, now = now, - signedIn = signedIn, + mode = mode, options = WidgetOptions( showProgress = settings.widgetShowProgress, showTeacher = settings.showTeacher, diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetSnapshot.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetSnapshot.kt index 463611bd..4a4972e9 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetSnapshot.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/WidgetSnapshot.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.widget +import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.core.model.ScheduleEngine import com.lumenpearson.lessons.core.model.Timetable @@ -36,27 +37,35 @@ private const val DAYS_IN_WEEK = 7 * Anything added here that reaches a further date has to be checked against * that bound first; a widget that silently draws an empty week is worse than * one that reads too much. + * + * Outside [ShellMode.CLASS] a [timetable] is ignored, whatever was handed in. + * The repository already answers null without an active class, so today this + * changes nothing; it is here so that the rule «no class, no timetable» is + * this function's rather than a property of a read three modules away, and so + * the sentence [mode] picks and the lessons drawn beside it can never come + * from two different answers to the same question. */ internal fun snapshotOf( timetable: Timetable?, now: LocalDateTime, - signedIn: Boolean, + mode: ShellMode, options: WidgetOptions, language: AppLanguage, ): LessonsWidget.Snapshot { + val drawn = timetable.takeIf { mode == ShellMode.CLASS } val today = now.toLocalDate() - val state = timetable?.let { ScheduleEngine.stateAt(it, now) } + val state = drawn?.let { ScheduleEngine.stateAt(it, now) } val monday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) return LessonsWidget.Snapshot( now = now, state = state, - signedIn = signedIn, + mode = mode, week = (0 until DAYS_IN_WEEK).map { offset -> val date = monday.plusDays(offset.toLong()) - DayLoad(date = date, lessons = timetable?.day(date)?.activeLessons?.size ?: 0) + DayLoad(date = date, lessons = drawn?.day(date)?.activeLessons?.size ?: 0) }, - today = timetable?.day(today), - homeworkDay = homeworkDayFor(state, timetable, today), + today = drawn?.day(today), + homeworkDay = homeworkDayFor(state, drawn, today), language = language, options = options, ) diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt index 5efdfe09..cbfca073 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/ui/LessonsWidgetBody.kt @@ -18,6 +18,7 @@ import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.padding import androidx.glance.layout.width +import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.model.DayState import com.lumenpearson.lessons.core.model.Lesson import com.lumenpearson.lessons.core.model.RibbonEntry @@ -71,9 +72,10 @@ private const val LOOK_AHEAD_BELOW_ROWS = 2 * possible to reason about (the same arguments always draw the same pixels). * * @param state what is happening now, or null when there is no cached timetable. - * @param signedIn whether a class has been joined. Only this tells the two - * causes of a null [state] apart: no class code yet, or a class joined whose - * timetable has never reached the device. + * @param mode how this phone came in, if it has. Only this tells the three + * causes of a null [state] apart: no way in taken yet, a class joined whose + * timetable has never reached the device, or a phone that reads its own + * school's diary and has no class timetable to draw. * @param today today's [SchoolDay], for the remaining-day timeline and for * today's own homework. Null on a date outside the cached window. * @param homeworkDay the day whose homework to show. After school this is @@ -90,7 +92,7 @@ private const val LOOK_AHEAD_BELOW_ROWS = 2 @Composable internal fun LessonsWidgetBody( state: DayState?, - signedIn: Boolean, + mode: ShellMode, today: SchoolDay?, homeworkDay: SchoolDay?, now: LocalDateTime, @@ -119,7 +121,7 @@ internal fun LessonsWidgetBody( // homework. Both are claims about a day the widget has never seen. The // instruction underneath is the only thing it actually knows. if (state == null || state is DayState.NoData) { - EmptyBody(size = size, signedIn = signedIn) + EmptyBody(size = size, mode = mode) } else { when (size) { WidgetSizeClass.TINY -> TinyBody(state, homeworkDay, now, size) @@ -147,31 +149,18 @@ internal fun LessonsWidgetBody( * thing a parent adds after installing, and the whole surface is already * clickable, so tapping the sentence does the thing the sentence asks for. * - * Which instruction depends on [signedIn]. Telling somebody who has already - * joined a class to go and enter a class code sends them to the one screen that - * cannot help them — what they actually need is to pull the timetable down, or - * to check the server address. + * Which instruction is [emptyTextRes]'s to decide. */ @Composable -private fun EmptyBody(size: WidgetSizeClass, signedIn: Boolean) { +private fun EmptyBody(size: WidgetSizeClass, mode: ShellMode) { val context = LocalContext.current - // By width, not by naming the sizes one at a time. The list was written when - // there were three narrow rungs and did not grow when two more arrived, so - // SMALL_TALL and NARROW were handed the long strings in a 110 dp column — - // and Glance text cannot ellipsize, so they were hard-clipped mid-word. - val compact = size.isNarrow || size == WidgetSizeClass.WIDE - val text = when { - !signedIn && compact -> R.string.widget_empty_short - !signedIn -> R.string.widget_empty_title - compact -> R.string.widget_no_data_short - else -> R.string.widget_no_data_title - } + val compact = emptyTextIsCompact(size) Box( modifier = GlanceModifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { BodyText( - text = context.getString(text), + text = context.getString(emptyTextRes(mode, size)), size = size, maxLines = if (compact) 2 else 3, muted = true, @@ -179,6 +168,41 @@ private fun EmptyBody(size: WidgetSizeClass, signedIn: Boolean) { } } +/** + * Whether [size] gets the short empty sentence. + * + * By width, not by naming the sizes one at a time. The list was written when + * there were three narrow rungs and did not grow when two more arrived, so + * SMALL_TALL and NARROW were handed the long strings in a 110 dp column — and + * Glance text cannot ellipsize, so they were hard-clipped mid-word. + */ +internal fun emptyTextIsCompact(size: WidgetSizeClass): Boolean = + size.isNarrow || size == WidgetSizeClass.WIDE + +/** + * The sentence the widget draws in place of a timetable, per way in. + * + * - [ShellMode.NONE]: nobody has come in, and there are two ways to — a class + * code, or the family's own school — so the sentence names the app rather + * than one of them. It used to say «введите код класса», which is wrong for + * exactly the family the second way was built for. + * - [ShellMode.CLASS]: a class was joined and nothing has synced. Telling + * them to enter a class code sends them to the one screen that cannot help; + * what they need is to pull the timetable down, or to check the server. + * - [ShellMode.DIARY]: the phone reads its own diary and has no class. The + * widget draws a class timetable and nothing from the diary (#142), so it + * says where the diary is instead of pretending to be about to load one — + * «потяните вниз» would promise a timetable that no pull will ever bring. + */ +internal fun emptyTextRes(mode: ShellMode, size: WidgetSizeClass): Int { + val compact = emptyTextIsCompact(size) + return when (mode) { + ShellMode.NONE -> if (compact) R.string.widget_empty_short else R.string.widget_empty_title + ShellMode.CLASS -> if (compact) R.string.widget_no_data_short else R.string.widget_no_data_title + ShellMode.DIARY -> if (compact) R.string.widget_diary_only_short else R.string.widget_diary_only_title + } +} + /** * 2x1: one line, two words. * diff --git a/android/widget/src/main/res/values-en/strings.xml b/android/widget/src/main/res/values-en/strings.xml index 4a5affa4..2eda5592 100644 --- a/android/widget/src/main/res/values-en/strings.xml +++ b/android/widget/src/main/res/values-en/strings.xml @@ -92,11 +92,13 @@ %1$s · %2$s at %3$s - Open the app and enter your class code - Enter class code + Open the app and connect with a class code or through your school + Open the app Loading the timetable… No timetable yet — open the app and pull down to refresh No timetable yet + The widget shows a class timetable. Your diary is in the app + Your diary is in the app %d subject diff --git a/android/widget/src/main/res/values/strings.xml b/android/widget/src/main/res/values/strings.xml index 23c7f15c..21798464 100644 --- a/android/widget/src/main/res/values/strings.xml +++ b/android/widget/src/main/res/values/strings.xml @@ -112,12 +112,19 @@ %1$s · %2$s в %3$s - - Откройте приложение и введите код класса - Введите код класса + + Откройте приложение и подключитесь по коду класса или через свою школу + Откройте приложение Загружаем расписание… Расписание ещё не загружено — откройте приложение и потяните вниз Расписание не загружено + + Виджет показывает расписание класса. Дневник — в приложении + Дневник — в приложении %d предмет diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/BoundedSnapshotParityTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/BoundedSnapshotParityTest.kt index c9342b66..986963fc 100644 --- a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/BoundedSnapshotParityTest.kt +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/BoundedSnapshotParityTest.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.widget +import com.lumenpearson.lessons.core.data.repository.ShellMode import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.core.model.DayState import com.lumenpearson.lessons.core.model.EventKind @@ -199,7 +200,7 @@ class BoundedSnapshotParityTest { private fun snapshotOf(timetable: Timetable, now: LocalDateTime) = snapshotOf( timetable = timetable, now = now, - signedIn = true, + mode = ShellMode.CLASS, options = WidgetOptions(), language = AppLanguage.SYSTEM, ) diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/UnreadableSnapshotTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/UnreadableSnapshotTest.kt index a9a9a50b..820f823c 100644 --- a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/UnreadableSnapshotTest.kt +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/UnreadableSnapshotTest.kt @@ -1,7 +1,8 @@ package com.lumenpearson.lessons.widget +import com.lumenpearson.lessons.core.data.repository.ShellMode +import org.junit.Assert.assertEquals import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue import org.junit.Test /** @@ -9,21 +10,23 @@ import org.junit.Test * * Anything out of `provideGlance` makes Glance draw «Problem loading widget» * permanently, so the read is wrapped and an empty state is drawn instead. The - * question this pins is which empty state: the flag chooses between two - * sentences, and under a failed read nothing is known about the class, so the + * question this pins is which empty state: the mode chooses between three + * sentences, and under a failed read nothing is known about the phone, so the * choice is about which way to be wrong. */ class UnreadableSnapshotTest { @Test - fun `a failed read does not tell a joined user to enter a class code`() { + fun `a failed read does not send a joined user back to a way in`() { val snapshot = LessonsWidget().unreadableSnapshot() assertNull("nothing was read, so there is no state to draw", snapshot.state) - assertTrue( - "«введите код класса» sends somebody who has already joined to the one " + - "screen that cannot help them; «потяните вниз» is harmless either way", - snapshot.signedIn, + assertEquals( + "the way-in sentence sends somebody who has already joined to a screen " + + "that cannot help them, and the diary sentence tells a class family " + + "the widget is not theirs; «потяните вниз» is harmless either way", + ShellMode.CLASS, + snapshot.mode, ) } } diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt new file mode 100644 index 00000000..6a2b26f4 --- /dev/null +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt @@ -0,0 +1,226 @@ +package com.lumenpearson.lessons.widget.ui + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.model.AppLanguage +import com.lumenpearson.lessons.core.model.DayState +import com.lumenpearson.lessons.core.model.Lesson +import com.lumenpearson.lessons.core.model.SchoolClassInfo +import com.lumenpearson.lessons.core.model.SchoolDay +import com.lumenpearson.lessons.core.model.Timetable +import com.lumenpearson.lessons.widget.R +import com.lumenpearson.lessons.widget.WidgetOptions +import com.lumenpearson.lessons.widget.WidgetSizeClass +import com.lumenpearson.lessons.widget.snapshotOf +import java.io.File +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Element + +/** + * What the widget says in place of a timetable, per way in — and that the mode + * it says it for is the one the snapshot carries. + * + * Two rungs are asked by name, `NARROW` (the 110 dp column) and `LARGE` (a + * wide one), and then every rung is asked by the width rule, so a rung that + * lands on the wrong length of sentence is noticed without this list having to + * grow with the ladder. + * + * The texts are read out of the source tree, as `NarrowLabelBudgetTest` reads + * them: this module's unit tests return defaults from `getString`, so a + * `Context` would answer nothing. + */ +class EmptyTextTest { + + private val narrow = WidgetSizeClass.NARROW + private val large = WidgetSizeClass.LARGE + + private val names: Map = mapOf( + R.string.widget_empty_title to "widget_empty_title", + R.string.widget_empty_short to "widget_empty_short", + R.string.widget_no_data_title to "widget_no_data_title", + R.string.widget_no_data_short to "widget_no_data_short", + R.string.widget_diary_only_title to "widget_diary_only_title", + R.string.widget_diary_only_short to "widget_diary_only_short", + ) + + private fun strings(folder: String): Map { + val document = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(File("src/main/res/$folder/strings.xml")) + val nodes = document.getElementsByTagName("string") + return (0 until nodes.length) + .map { nodes.item(it) as Element } + .associate { it.getAttribute("name") to it.textContent } + } + + private fun drawn(mode: ShellMode, size: WidgetSizeClass, folder: String): String { + val name = names.getValue(emptyTextRes(mode, size)) + return strings(folder)[name] ?: error("$folder has no $name") + } + + // -- which sentence -------------------------------------------------------- + + @Test + fun `nobody in yet is told to open the app, at both widths`() { + assertEquals(R.string.widget_empty_short, emptyTextRes(ShellMode.NONE, narrow)) + assertEquals(R.string.widget_empty_title, emptyTextRes(ShellMode.NONE, large)) + } + + @Test + fun `a class with nothing synced is told to pull down, at both widths`() { + assertEquals(R.string.widget_no_data_short, emptyTextRes(ShellMode.CLASS, narrow)) + assertEquals(R.string.widget_no_data_title, emptyTextRes(ShellMode.CLASS, large)) + } + + @Test + fun `a diary-only phone is told where its diary is, at both widths`() { + assertEquals(R.string.widget_diary_only_short, emptyTextRes(ShellMode.DIARY, narrow)) + assertEquals(R.string.widget_diary_only_title, emptyTextRes(ShellMode.DIARY, large)) + } + + @Test + fun `the three ways in never share a sentence on any rung`() { + for (size in WidgetSizeClass.entries) { + val texts = ShellMode.entries.map { emptyTextRes(it, size) } + assertEquals("$size: ${texts.map(names::getValue)}", texts.size, texts.toSet().size) + } + } + + @Test + fun `every narrow rung, and the one-row rung, is given the short sentence`() { + val shorts = setOf( + R.string.widget_empty_short, + R.string.widget_no_data_short, + R.string.widget_diary_only_short, + ) + for (size in WidgetSizeClass.entries) { + // Glance cannot ellipsize, so a long sentence in a 110 dp column is + // clipped mid-word rather than shortened. + val compact = size.isNarrow || size == WidgetSizeClass.WIDE + assertEquals("$size", compact, emptyTextIsCompact(size)) + for (mode in ShellMode.entries) { + assertEquals("$mode on $size", compact, emptyTextRes(mode, size) in shorts) + } + } + // Both halves of the ladder are still on it; if either vanished, the + // loop above would pass by asking nothing of it. + assertTrue(emptyTextIsCompact(narrow)) + assertFalse(emptyTextIsCompact(large)) + } + + // -- what the sentence says ------------------------------------------------ + + @Test + fun `nobody in yet is no longer told a class code is the only way in`() { + // Two ways in now, and the second is for the family whose class has no + // code at all; a sentence naming only the first sends them nowhere. + for (size in listOf(narrow, large)) { + val russian = drawn(ShellMode.NONE, size, "values") + assertFalse("«$russian» on $size", russian.contains("введите код класса", ignoreCase = true)) + val english = drawn(ShellMode.NONE, size, "values-en") + assertFalse("«$english» on $size", english.contains("enter your class code", ignoreCase = true)) + } + } + + @Test + fun `a diary-only phone is not promised a timetable a pull would bring`() { + for (size in listOf(narrow, large)) { + for (folder in listOf("values", "values-en")) { + val text = drawn(ShellMode.DIARY, size, folder) + assertNotEquals("$folder on $size", drawn(ShellMode.CLASS, size, folder), text) + assertFalse("«$text» in $folder on $size", text.contains("потяните")) + assertFalse("«$text» in $folder on $size", text.contains("pull down")) + } + } + } + + @Test + fun `every empty sentence is written in both languages`() { + for (folder in listOf("values", "values-en")) { + val table = strings(folder) + for (name in names.values) { + assertTrue("$folder has no $name", table[name]?.isNotBlank() == true) + } + } + } + + // -- the snapshot carries the mode, and only a class draws a timetable ----- + + /** A Monday at 08:40, ten minutes into the first lesson. */ + private val now = LocalDateTime.of(2026, 9, 21, 8, 40) + + private val timetable = Timetable( + schoolClass = SchoolClassInfo(id = 1, name = "9А", timeZoneId = "Europe/Moscow"), + days = listOf( + SchoolDay( + date = LocalDate.of(2026, 9, 21), + weekday = 1, + lessons = listOf( + Lesson( + index = 1, + subject = "Алгебра", + startsAt = LocalTime.of(8, 30), + endsAt = LocalTime.of(9, 15), + ), + ), + ), + ), + ) + + private fun snapshot(mode: ShellMode, timetable: Timetable?) = snapshotOf( + timetable = timetable, + now = now, + mode = mode, + options = WidgetOptions(), + language = AppLanguage.SYSTEM, + ) + + @Test + fun `the snapshot carries the mode it was read in`() { + for (mode in ShellMode.entries) { + assertEquals(mode, snapshot(mode, timetable = null).mode) + } + } + + @Test + fun `a class with a timetable draws its lesson, not an empty sentence`() { + val snapshot = snapshot(ShellMode.CLASS, timetable) + assertTrue("${snapshot.state}", snapshot.state is DayState.InLesson) + assertEquals(1, snapshot.week.first().lessons) + } + + @Test + fun `outside a class nothing of a timetable is drawn, even one handed in`() { + for (mode in listOf(ShellMode.NONE, ShellMode.DIARY)) { + val snapshot = snapshot(mode, timetable) + assertNull("$mode", snapshot.state) + assertNull("$mode", snapshot.today) + assertNull("$mode", snapshot.homeworkDay) + assertEquals("$mode", List(7) { 0 }, snapshot.week.map { it.lessons }) + } + } + + @Test + fun `each mode with nothing to draw lands on its own sentence`() { + val expected = mapOf( + ShellMode.NONE to (R.string.widget_empty_short to R.string.widget_empty_title), + ShellMode.CLASS to (R.string.widget_no_data_short to R.string.widget_no_data_title), + ShellMode.DIARY to (R.string.widget_diary_only_short to R.string.widget_diary_only_title), + ) + for ((mode, texts) in expected) { + val snapshot = snapshot(mode, timetable = null) + // A null state is what sends the body to its empty sentence. + assertNull("$mode", snapshot.state) + assertEquals("$mode, narrow", texts.first, emptyTextRes(snapshot.mode, narrow)) + assertEquals("$mode, large", texts.second, emptyTextRes(snapshot.mode, large)) + } + } +} From 5efca545c561d7743d47f97c9c6061c3b4ee500f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:21:16 +0000 Subject: [PATCH 21/30] Document the phone's half: the first run through your own school's diary, the diary-only home, and the fork's legal address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Android commits of #141 are in, and the documents that own each part now say what the app does: - docs/app/guide.ru.md and guide.en.md (the in-app guide, identical in shape): «Первый запуск» has the five steps, the terms line under «Продолжить», and the two ways in; the password goes from the phone to the diary only; the app has no server of its own (#154). The diary page covers a diary-only phone, the offline copy, the absence of any background read and signing out, and the widget note quotes the sentences the widget really shows. manifest.json moves to version 5, because a phone keeps its stored guide unless the bundled one is newer and would otherwise go on showing the old first run. - docs/design.md: the first run as a path of steps, with the hold, the permissions before the chooser and the legal line (#157); the paragraph saying the app never talks to dnevnik2 is corrected. - docs/architecture.md: the three homes and the arming rule (#151, #152); where the path, the login, the password, the upstream session and the bearer live during the first run and where they never do; the phone's half — the upstream client and its origin guard, the bundled catalog as the only source of a diary host, the shared vectors, registration, diary.db with its single writer, the import, the one unprompted refresh. - docs/build.md: LESSONS_LEGAL_BASE_URL / lessons.legal.baseUrl — why every fork sets its own, the https check, the non-empty default, the apk.yml step and its repository variable; «Why HTTP and not HTTPS» rewritten for native sign-in, which closes the last item of #150; the CI path filter (#159). - docs/widget.md, docs/diaries.md, docs/guide.md, docs/README.md, README.md (honest status: the first run and the diary-only home are written and JVM-tested, never run on a device or against a live diary; the legal texts were never read by a lawyer), CLAUDE.md (docs/app and docs/legal in the layout, two Room databases, the shell modes, UpstreamMarkers.kt as the one Russian in Kotlin, 1944 server tests), and the release skill (raise the legal edition before a tag when the texts change). - The privacy policy said the login is kept «as you typed it»; both the phone and the server strip spaces at its ends and characters that print nothing first, and both languages now say so. Nothing has been published, so the edition stays 1. Android test counts are 1371 (app 513, core/data 532, designsystem 99, model 125, widget 102); the document-reading tests on both halves pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/skills/release/SKILL.md | 5 + CLAUDE.md | 18 ++- README.md | 63 +++++--- docs/README.md | 23 +-- docs/app/guide.en.md | 41 ++++-- docs/app/guide.ru.md | 41 ++++-- docs/app/manifest.json | 4 +- docs/architecture.md | 247 +++++++++++++++++++++++++++++--- docs/build.md | 147 +++++++++++++++---- docs/design.md | 142 +++++++++++++----- docs/diaries.md | 39 ++++- docs/guide.md | 107 +++++++++++--- docs/legal/privacy.en.md | 2 +- docs/legal/privacy.ru.md | 2 +- docs/widget.md | 36 ++++- 15 files changed, 749 insertions(+), 168 deletions(-) diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index f07e7e39..5b471290 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -43,6 +43,11 @@ Before tagging, walk the milestone and check three things: - **every pull request on it carries the milestone**, set with `issue_write` when it was opened. One left bare is a change the notes will not mention. +**If the terms or the privacy policy changed since the last tag, raise `edition` and set +`effective` in `docs/legal/legal.json` before tagging**, in the commit the tag points at. The +APK bundles `docs/legal/` as it is at build time and names the edition in its sheet, so a +tag cut first ships changed texts under the old edition and date. + Then tag. A `v*` tag makes `apk.yml` build an installable APK **and** create a GitHub release with it attached, so the tag is the moment the notes have to be ready. diff --git a/CLAUDE.md b/CLAUDE.md index 1f3a33eb..f7fe6b10 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,9 @@ android/ Kotlin / Compose / Glance, five Gradle modules server/ FastAPI + aiogram in one process, one database, Alembic migrations api/ thin Vercel entry point that re-exports server/app/main.py docs/ nine documents plus an index (docs/README.md), all current, all English; - docs/diaries/ holds the per-platform reference pages of diaries.md + docs/diaries/ holds the per-platform reference pages of diaries.md; + docs/app/ (the in-app guide) and docs/legal/ (the terms and the privacy + policy) are product text the APK bundles, Russian source and English twin ``` There is no npm, no Node and no web frontend — with **one** deliberate exception: @@ -45,7 +47,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 1915 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 1944 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at @@ -159,6 +161,14 @@ depend on `:widget` — the sync worker tells the widget it has new data by broa `com.lumenpearson.lessons.action.DATA_SYNCED`, precisely so the dependency does not have to be circular. +There are **two** Room databases: `lessons.db`, the class cache, and `diary.db`, the +family's own diary, which nothing writes but `DiaryRepositoryImpl`'s successful reads, under +a generation guard that drops a read landing after a sign-out. A phone is in one of three +shell modes — `CLASS`, `DIARY` (a diary and no class, whose home is the diary) or `NONE` (the +first run) — and the periodic class sync is armed in `CLASS` only (#152): +`LessonsApplication` collects `shellMode.syncArming` rather than scheduling on every settings +emission. + **A window is one school year, and a class holds several of them.** `synced_window` says which years this phone has fetched, `replaceWindow` replaces one and leaves the rest, and `syncedYears` is what the screens read to tell «нет уроков» from «ещё не загружено». The @@ -572,7 +582,9 @@ points Hilt does not inject cleanly. What it cannot see is a Russian string written into Kotlin, because that word is in neither folder — `grep -rnP '"[^"]*[\x{0400}-\x{04FF}]' */src/main` is the check for that, and today it finds only `@Preview` data, maintainer-facing report - bodies, and the timezone list, whose file documents the choice. + bodies, the timezone list, whose file documents the choice, and + `core/data/.../upstream/UpstreamMarkers.kt` — the diaries' own words, matched in their + answers, which is the one documented exception on the diary's side. - **A renderer is written against the type it is handed, and nothing checks that but you.** «🗓 Четверти» crashed on every press in production because the card printed `term.days` and `days` lived on a flattened copy of a term that nothing ever constructed. There is diff --git a/README.md b/README.md index 718891ff..1b7a25ee 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ time zones from Kaliningrad to Kamchatka. | Part | Stack | Where it is described | | --- | --- | --- | -| **App** — three tabs, nine settings sections, several classes on one phone, Russian and English | Kotlin 2.4, Compose, Material 3 Expressive | [docs/design.md](docs/design.md) | +| **App** — three tabs, nine settings sections, several classes on one phone, Russian and English; or, with no class, the family's own school diary as the whole app | Kotlin 2.4, Compose, Material 3 Expressive | [docs/design.md](docs/design.md) | | **Widget** — twelve sizes, seven states, works offline | Glance | [docs/widget.md](docs/widget.md) | | **Notifications** — the bell, the morning digest, tomorrow's homework, substitutions | local alarms, no push | [docs/design.md](docs/design.md#notifications) | | **Bot** — and the admin panel: roles, timetable, bells, subjects, the log, who may connect a phone | aiogram 3 | [docs/bot.md](docs/bot.md) | @@ -155,11 +155,17 @@ With no keystore configured, the release build is signed with the debug key: it on a phone, but it must not be published. How to plug in your own key and how to tell the app where the server is, is in [docs/build.md](docs/build.md). -On first run the app walks through four screens and asks for a class code — the one the -bot hands out with `/code`. A class can be switched to a mode where the class code lets -nobody in and a phone joins with a personal one-time code from the bot (the «📱 Подключить -телефон» button); the field for the code is the same one either way — -[docs/bot.md](docs/bot.md#who-lets-a-phone-in). +On first run the app walks through five steps — the last of them «Как подключиться?» — and +offers two ways in. **By the class code**, the one the bot hands out with `/code`: a class +can be switched to a mode where the class code lets nobody in and a phone joins with a +personal one-time code from the bot (the «📱 Подключить телефон» button); the field for the +code is the same one either way — [docs/bot.md](docs/bot.md#who-lets-a-phone-in). Or **through +the family's own school**: region, school, diary system, a sign-in in which the password goes +from the phone to the diary and nowhere else, and an import of the diary onto the phone — +[docs/guide.md](docs/guide.md#first-run). The app has no server built in; its address is +typed in, and [docs/build.md](docs/build.md#pointing-the-app-at-a-server) says how. Under the +first screen's button is the line accepting the terms of use and the privacy policy, whose +texts are in [docs/legal/](docs/legal/) and bundled in the APK. ### A phone that does more than read @@ -183,6 +189,8 @@ The index is [docs/README.md](docs/README.md). In short: * [docs/design.md](docs/design.md) — the design system and the reasoning behind the interface * [docs/diaries.md](docs/diaries.md) — which electronic diary every region runs, and the routes of each platform as the open-source clients call them +* [docs/legal/](docs/legal/) — the terms of use and the privacy policy the app links and + bundles; product text rather than a document, Russian first For anybody about to write code: [CONTRIBUTING.md](CONTRIBUTING.md) and [CLAUDE.md](CLAUDE.md) — the commands, the boundaries, and what will bite anybody who does @@ -198,8 +206,8 @@ Read this before planning a release. | --- | --- | | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 1915 tests, green, about four minutes — the command CI runs | -| `./gradlew test` | 968 tests, green, all five modules | +| `pytest -q -n auto` | 1944 tests, green, about four minutes — the command CI runs | +| `./gradlew test` | 1371 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | @@ -212,9 +220,10 @@ handing back substitutions, events, homework and `next_school_day`. The state en walked through all 1440 minutes of a school day and through all eleven Russian time zones. **What nothing checks.** There is no `androidTest` directory in this project: not one test -has run on a device or an emulator. Twenty of the app's screens, sheets and rows — the class -list, the join mode, the connection errors, the first-run reveal, the crash-report sheet, -the calendar's header, its two sheets, its year picker and its day list, and the rest — are +has run on a device or an emulator. About two dozen of the app's screens, sheets and rows — +the class list, the join mode, the connection errors, the first-run reveal and the terms line +under its button, the diary home, the crash-report sheet, the calendar's header, its two +sheets, its year picker and its day list, and the rest — are composed in JVM tests under Robolectric, with a Russian locale and a phone's width, and those are real presses and real rotations on real strings; the design system's components are exercised the same way. Nobody has pressed the @@ -231,11 +240,11 @@ Material 3 Expressive and Glance 1.3.0-alpha02 are alphas. They compile, but nob measured how they behave across Android versions. The electronic diary has never once been opened against a real server. Not Petersburg's -dnevnik2.petersburgedu.ru — neither the sign-in page nor any of the four screens — and not -«Сетевой город. Образование», the second provider, which is **written server-side only and -has never met a live regional server**: its password sign-in, its keep-alive, its region -allow-list and its weekly-diary mapping are read from open-source clients and exercised on -hand-written payloads, exactly as Petersburg's were. The tests run a hand-written stub in +dnevnik2.petersburgedu.ru — neither the sign-in page nor any screen of the app's diary — and +not «Сетевой город. Образование», the second provider, which **has never met a live regional +server**: its password sign-in (on the server and on the phone), its +keep-alive, its region allow-list and its weekly-diary mapping are read from open-source +clients and exercised on hand-written payloads, exactly as Petersburg's were. The tests run a hand-written stub in place of each: that is the only honest way to check an integration with an undocumented service, but it says nothing about what that service actually answers. No browser has ever opened the sign-in page for either, and the first live session, for both, is the owner's @@ -252,6 +261,28 @@ still pass the password through this server — are what is left. The four calls город» registration makes have not been timed against Vercel's 30-second ceiling, and a session registered from a phone is invisible to the bot (#143). +**The first run's second way in, and the diary as a home, are written and JVM-tested and +nothing more.** The app now signs in to the diary itself and registers the session; keeps +what it reads in a second database; imports two weeks of it and the term's marks at the +first run, with a progress bar; and gives a phone with a diary and no class a home of its own, with the class +sync disarmed there (#151, #152). All of it is held by pure rules, view models and +MockWebServer: not one step has run on a device, against a live diary or against a deployed +server. Nothing composes the shell in a test, so the gate, the hold through a join or a +registration, the swap to the right home and the resume after a process death are proved by +their rules alone. TLS to the regional servers, Room's `diary.db` on a device, the browser +hand-offs to Госуслуги and to a diary's site, TalkBack on the new steps and the English text +in context are all unread. The path also needs a server address somebody gives the family — +the APK has none — and a diary-only phone gets no widget content, no Today or Calendar and no +alerts (#142). + +**The terms and the privacy policy describe the code and have never been read by a lawyer.** +The line under the first button opens them in the browser or, offline, from the copy in the +APK; that the default address resolves was checked on 25 September 2026 by fetching it, and no +link has been tapped on a phone. Phones that finished the first run before this build never +see the line — the documents stay reachable from «О приложении» — and the bot shows no link +to either. That crash reports are kept out of a phone's backup is in the backup rules and +their test only; it needs a phone to confirm (#156). + **Week parity was computed from the ISO week number, and that broke once every five or six years.** In an ISO year with 53 weeks, week 53 and week 1 stand next to each other and are both odd: Monday 28 December 2026 and Monday 4 January 2027 both came out as numerator, diff --git a/docs/README.md b/docs/README.md index b98cde64..df158ab2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Documentation -Nine documents, the reference pages one of them keeps in a folder of its own, and one folder +Nine documents, the reference pages one of them keeps in a folder of its own, and two folders the app itself reads. Each answers its own question, and none retells a neighbour — if the answer is not here it is in the code, and there is usually a link to it. @@ -23,14 +23,15 @@ answer is not here it is in the code, and there is usually a link to it. | --- | --- | | [guide.md](guide.md) | first run, the class code, the widget, notifications, the bot, the diary, the translation-correction mode — for whoever uses the app | | [bot.md](bot.md) | roles, invitation by phone number, editing the timetable, every command, what a card may say before Telegram refuses it | -| [widget.md](widget.md) | twelve sizes, seven states, the update schedule, why not a tick once a minute | -| [build.md](build.md) | standing the project up from a clone and how much of `server/.env` each step needs, the eight secrets Actions holds and what reads them, building the APK in Actions and locally, signing with your own key, a release from a tag, Actions minutes and where they go, the bundled typeface, pointing the app at a server | +| [widget.md](widget.md) | twelve sizes, seven states, the three sentences it draws when it has nothing to draw, the update schedule, why not a tick once a minute | +| [build.md](build.md) | standing the project up from a clone and how much of `server/.env` each step needs, the eight secrets and one variable Actions holds and what reads them, building the APK in Actions and locally, signing with your own key, where the terms and the privacy policy link to and what a fork must change, a release from a tag, Actions minutes and where they go, the bundled typeface, pointing the app at a server, what an `http://` server carries | | [deploy.md](deploy.md) | Vercel plus Neon or your own server, the webhook, migrations, why the server has no clock of its own | | [api.md](api.md) | the whole `/api/v1` contract: reads, writes, class management, the electronic diary — Петербург and «Сетевой город» behind one contract, signed into by this server or registered from a session the client opened itself — and the anonymous school directory | -| [architecture.md](architecture.md) | why the bot is the backend, the timetable resolution model, the five Android modules, the service layer, the tests | +| [architecture.md](architecture.md) | why the bot is the backend, the timetable resolution model, the five Android modules, the three homes a phone can have and the first run's state, the service layer, the diary on both sides — the server's providers and the phone's sign-in, `diary.db` and import — the tests | | [design.md](design.md) | the design system: what was taken from Essentials, what was fixed, and the reasoning behind every visible decision in the interface | | [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from — except for one section, the region catalog the server and the app read, which is generated from this survey | | [diaries/](diaries/) | **the reference pages of [diaries.md](diaries.md)**: one page per platform with its hosts, sign-in flows, headers and the full route table read out of the open-source clients, and one page with the evidence for every region. Nothing in them has been tried against a live diary | +| [legal/](legal/) | **not a document — the terms of use and the privacy policy the app links and bundles.** `*.ru.md` is the source, `*.en.md` the translation, `legal.json` names the edition and the date it applies from. They describe what this code does, and a fork that runs its own server rewrites the passages marked `FORK` — [build.md](build.md#the-terms-and-the-privacy-policy-the-app-links) | | [app/](app/) | **not a document — the guide the app draws.** `guide.ru.md` is the source, `guide.en.md` the translation, `manifest.json` says which version they are and which app version they describe. The app fetches these files from this repository and falls back to the copy built into the APK | Everything written about this project is English — these documents, the code comments, the @@ -53,16 +54,19 @@ the user will actually see, it quotes it in Russian, because that is what is on - **Which variable goes where** — three places, and they are not the same list. `server/.env.example` carries every setting the server reads, each with what empty means; [deploy.md](deploy.md), "Secrets", is the eleven a hosted deployment needs; - [build.md](build.md), "The other place variables live", is the eight GitHub Actions holds - for signing and for the fallback tick. `CRON_SECRET` is the one name in two of the three, + [build.md](build.md), "The other place variables live", is the eight secrets and one + variable GitHub Actions holds, for signing, for the fallback tick and for the legal link. `CRON_SECRET` is the one name in two of the three, and nothing checks that the two values match. - **The two different tokens** — [api.md](api.md): the device token comes from `POST /api/v1/join`, the diary token from `POST /api/v1/diary/session` (a session the client opened itself) or `POST /api/v1/diary/login` (a password), and neither implies the other. - **Where a diary password goes** — [api.md](api.md#the-electronic-diary) and - [architecture.md](architecture.md): registration keeps it off this server; `/diary/login` - and the bot's sign-in page pass it through to the diary once and store it nowhere. + [architecture.md](architecture.md#the-phones-half): the app signs in to the diary itself + and registers only the session, so from the app the password goes to the diary and nowhere + else; `/diary/login`, kept for older APKs, and the bot's sign-in page pass it through this + server once and store it nowhere. What an `http://` server address exposes is in + [build.md](build.md#why-http-and-not-https). - **Why there is no Госуслуги sign-in** — [diaries.md](diaries.md#what-it-means-for-this-project): a Госуслуги session is the person's whole state-services account. - **Who lets a phone into a class** — [api.md](api.md), "Who lets a phone in: the class @@ -78,7 +82,8 @@ the user will actually see, it quotes it in Russian, because that is what is on Markdown: `##` is a page, `-` a list, `1.` with a bold lead a step, `>` an aside. The parser is `DocsMarkdown` in `:core:data`, and `DocsGuideParityTest` holds the two languages to the same pages in the same order — the job `ResourceTranslationTest` does - for the text that is still in `values/`. + for the text that is still in `values/`. [legal/](legal/) is written in the same subset, + and `LegalDocumentsTest` holds its two languages level the same way. ## The rules these documents follow diff --git a/docs/app/guide.en.md b/docs/app/guide.en.md index 43ec96e6..2d63ce9e 100644 --- a/docs/app/guide.en.md +++ b/docs/app/guide.en.md @@ -13,25 +13,34 @@ # Lessons — how to use this ## First run - + -One person keeps the class timetable in a Telegram bot; the app reads it and shows it — on screen, in the widget and in notifications. There is nothing for you to type in but the class code, once. +The app shows one of two things, or both: a class timetable that one person keeps in a Telegram bot — on screen, in the widget and in notifications; or your school's electronic diary, if you sign in to it yourself. -A fresh install does not open with the code field. It opens with five steps. +A fresh install does not open with the code field. It opens with five introductory steps. Under the “Continue” button on the first of them there is always the line “By continuing, you accept the Terms of Use and the Privacy Policy”. Tap either name to open it — in the browser, or offline from the copy built into the app; both are under Settings → About afterwards too. 1. **Welcome** — The app mark, the theme and the language. The mark spins under a finger; the theme and the language are in settings afterwards. 2. **What this is** — A few paragraphs on what the app shows and what it does not do. It is also where you choose whether crash reports are kept — by default they are not. 3. **Preferences** — Haptics, wallpaper colours, a black background, the edge blur, the teacher on a lesson row and the progress bar in the widget. Only the things you can judge before seeing a single lesson. 4. **Permissions** — Notifications, exact alarms and background work, one card each. Without them the timetable still works — it just stays silent. -5. **The class code** — That field. +5. **How do you want to start?** — Two ways: “With a class code” and “Find your school”. You can add the other one later. > The language is on the first step on purpose: somebody who does not read Russian has to be able to switch it before the third screen, not after it. Below Android 13 changing it recreates the screen — that is normal, and the step is not lost. -The bot hands out the code with /code, to anybody who is an administrator of the class. A new code is eight characters long and never contains the look-alikes O, 0, I and 1. Older six-character codes still work: the field accepts 4 to 16 characters and upper-cases them for you. +“With a class code” opens the code field. The bot hands out the code with /code, to anybody who is an administrator of the class. A new code is eight characters long and never contains the look-alikes O, 0, I and 1. Older six-character codes still work: the field accepts 4 to 16 characters and upper-cases them for you. If the class is linked to a diary the app can sign in to, the app then offers to sign in to that diary too — “Not now” skips it. -If the school runs its own server rather than the one built into this APK, tap “Server” at the bottom of the join screen and type the whole address. It has to be the address the server is reachable at from the phone itself: “localhost” on a phone means the phone. +“Find your school” is for a family that wants to see its own diary, whether or not there is a class in the bot. The steps come in this order, and the ones a region does not need are skipped: -To change class or leave it: Settings → Class. After leaving, the app shows the code field again rather than the five screens over. +- **Region** — Search by the name of a region or a city, by the region's code, or by a school's name. The list of every region is built into the app and searches offline; a school's name is looked up by the server, if school search is switched on there. +- **School** — Only for Setevoy Gorod: the phone takes the list of schools straight from your region's diary server. +- **The electronic diary** — The systems the region's schools use; one is marked “Recommended”, and “Why?” explains the choice. If a diary opens only through Gosuslugi, or the app cannot read it yet, its site opens instead — or you can use a class code. +- **Sign-in** — The diary's login and password. The “Where the password goes” card names the diary's address: the password goes there and nowhere else, over HTTPS, and the server gets the session the diary hands out. +- **Loading** — The student, the terms, two weeks of timetable, homework and marks. If the account has several students, the app asks whose diary to show; if the load stops, “Try again” carries on from where it stopped. +- **All set** — The student, the diary, the class if there is one, and the main settings. “Open the app” goes to the home screen. + +The app has no server of its own: the address comes from the class admin, or from whoever set a server up for your school. It goes into the “Server address” row — on the “How do you want to start?” screen, under the code field, or in Settings → Sync; on the way through your school you are asked for it when it is needed. It has to be the address the server is reachable at from the phone itself: “localhost” on a phone means the phone. + +To change class or leave it: Settings → Class. After leaving the last class the app opens not the introduction again but “How do you want to start?” — or the diary, if you are signed in to one. ## The three tabs @@ -72,7 +81,7 @@ Added like any other: long-press an empty spot on the home screen, “Widgets” - It counts in the school's time, not the phone's. A parent in another timezone sees the bells as they ring at the school. - After the lessons it shows the homework — for the next school day, and across a holiday for the first day after it. -> If the widget says there is no data, open the app: nothing is cached for that date and no sync has run yet. +> If the widget says “No timetable yet”, open the app and pull the screen down: nothing is cached for that date. The widget draws only a class timetable, so on a phone with no class and only a diary it says “Your diary is in the app”. ## Notifications @@ -128,17 +137,23 @@ The commands an ordinary member of the class needs. One you are not allowed refu - /calendar — a subscription link: the timetable in the phone's calendar. - /help — the command list, grouped by what is available to you. -## The Petersburg diary - +## The electronic diary + + +A separate thing with a separate account: the class timetable lives in the bot, while the electronic diary is the system the school keeps marks, absences and homework in. The app signs in to Petersburg Education, and to Setevoy Gorod in the regions where it takes a login and a password. A diary that lets people in only through Gosuslugi, the app does not sign in to. -A separate thing with a separate account: the class timetable lives in the bot, while the diary is the St Petersburg city service that holds marks, absences and the homework the school itself sets. In the app it is Settings → Diary. +Where the diary is in the app depends on how you came in. On a phone with a class it is Settings → Diary. Without a class the diary is the app: its two tabs are the home screen, and settings has six sections — no content, notifications or class, which all run on a class. -Signing in takes the same login and password as the diary's own site. What the attempt came to is said in a pop-up: “Signed in”, naming the account, or “Could not sign in” with the reason - wrong pair, diary not answering, no connection. Those are different things and they need different fixes. +Signing in takes the same login and password as the diary's own site. The form names the diary and the address the password will go to; in settings, “Change” beside the name picks another diary. A failure is explained in a “Could not sign in” pop-up with the reason — wrong pair, diary not answering, too many attempts, no connection. Those are different things and they need different fixes. -> The password is never stored: it is needed for exactly one request, after which both the phone and the server forget it. Only the diary's own session is kept, and it lives as long as the service renews it. When it ends the app asks for the password again — the login stays where it was. +> The password goes from the phone straight to the diary, over HTTPS, and nowhere else — not to the server and not to the phone's storage. The server gets only the session the diary hands out, and keeps that. When it ends the app asks for the password again — the login stays where it was. Inside are two tabs — Timetable and Marks — and a child picker if the account sees more than one. Diary homework appears under the lessons of the day it is due on. An absence, a late arrival and a remark all arrive in the same list as the marks, but the app tells them apart and shows them differently. +What was loaded is kept on the phone and opens offline — the app then says it is showing what was saved, and when it was last updated. The app reads the diary again only while it is open: neither the background nor the widget ever reads it. That is also why the sign-in lasts while the app is being opened: after 30 days without that you sign in again, and the Petersburg diary may end the sign-in sooner. + +“Sign out of the diary” is in the same place, Settings → Diary. The lessons and marks saved on the phone are deleted and the server forgets its copy of the sign-in; a phone with no class then goes back to “How do you want to start?”. + > The service belongs to somebody else and is undocumented. If it answers in a way the app cannot read, the app says so: that is fixed on the server, not in the app. ## Managing the class diff --git a/docs/app/guide.ru.md b/docs/app/guide.ru.md index dbfa9842..d8452f9c 100644 --- a/docs/app/guide.ru.md +++ b/docs/app/guide.ru.md @@ -13,25 +13,34 @@ # Дневник — как этим пользоваться ## Первый запуск - + -Расписание класса ведёт кто-то один в Telegram-боте, а приложение читает его и показывает — на экране, в виджете и в уведомлениях. Вводить самому ничего не нужно, кроме кода класса при первом запуске. +Приложение показывает одно из двух, а можно и оба: расписание класса, которое кто-то один ведёт в Telegram-боте, — на экране, в виджете и в уведомлениях; или электронный дневник вашей школы, если вы войдёте в него сами. -Установленное приложение открывается не полем для кода, а пятью шагами. +Установленное приложение открывается не полем для кода, а пятью шагами знакомства. Под кнопкой «Продолжить» на первом из них всегда стоит строка «Продолжая, вы принимаете Условия использования и Политику конфиденциальности». Оба названия открываются нажатием — в браузере, а без сети из копии, встроенной в приложение; потом они же лежат в «Настройки → О приложении». 1. **Приветствие** — Знак приложения, тема и язык. Знак крутится пальцем, а тема и язык потом всегда доступны в настройках. 2. **Что это такое** — Несколько абзацев о том, что приложение показывает и чего оно не делает. Здесь же выбирается, сохранять ли отчёты о сбоях — по умолчанию нет. 3. **Свойства** — Отклик, цвета из обоев, чёрный фон, размытие у краёв, учитель в строке урока и прогресс в виджете. Только то, о чём можно судить, ещё не увидев ни одного урока. 4. **Разрешения** — Уведомления, точные будильники и работа в фоне — по карточке на каждое. Без них расписание всё равно работает, просто молча. -5. **Код класса** — То самое поле. +5. **Как подключиться?** — Два способа: «По коду класса» и «Найти свою школу». Второй можно добавить и потом. > Язык стоит на первом шаге намеренно: тот, кто не читает по-русски, должен переключить его до третьего экрана, а не после. Ниже Android 13 смена языка пересоздаёт экран — это нормально, шаг не теряется. -Код выдаёт бот командой /code тому, у кого в классе есть права администратора. В новом коде восемь символов, и в нём не встречаются похожие друг на друга O, 0, I и 1. Старые шестизначные коды продолжают работать: поле принимает от 4 до 16 символов и само приводит их к верхнему регистру. +«По коду класса» открывает поле для кода. Код выдаёт бот командой /code тому, у кого в классе есть права администратора. В новом коде восемь символов, и в нём не встречаются похожие друг на друга O, 0, I и 1. Старые шестизначные коды продолжают работать: поле принимает от 4 до 16 символов и само приводит их к верхнему регистру. Если класс привязан к дневнику, в который приложение умеет входить, после кода оно предложит войти и в него — «Не сейчас» это пропускает. -Если сервер школы свой, а не тот, что прошит в сборке, нажмите «Сервер» внизу экрана подключения и введите адрес целиком. Адрес нужен тот, по которому сервер видит телефон: «localhost» для телефона означает его самого. +«Найти свою школу» — для семьи, которая хочет видеть свой дневник, даже если класса в боте нет. Шаги идут в таком порядке, а те, что региону не нужны, пропускаются: -Сменить класс или выйти из него — «Настройки → Класс». После выхода приложение снова покажет поле кода, а не пять экранов заново. +- **Регион** — Поиск по названию региона или города, по коду региона и по названию школы. Список всех регионов лежит в самом приложении и ищется без сети; по названию школы подсказывает сервер, если на нём включён поиск школ. +- **Школа** — Только для «Сетевого города»: список школ телефон берёт прямо у сервера дневника вашего региона. +- **Электронный дневник** — Системы, которыми пользуются школы региона; одна отмечена «Рекомендуем», и «Почему?» объясняет выбор. Если дневник открывается только через Госуслуги или приложение его пока не читает, откроется его сайт — или можно войти по коду класса. +- **Вход** — Логин и пароль от дневника. Карточка «Куда уйдёт пароль» называет адрес дневника: пароль уходит только туда, по HTTPS, а сервер получает сессию, которую выдал дневник. +- **Загрузка** — Ученик, учебные периоды, расписание на две недели, задания и оценки. Если в аккаунте несколько учеников, приложение спросит, чей дневник показывать; если загрузка остановилась, «Повторить» продолжит с того же места. +- **Всё готово** — Ученик, дневник, класс, если он есть, и основные настройки. «Открыть приложение» ведёт на главный экран. + +Своего сервера у приложения нет: адрес даёт администратор класса или тот, кто поднял сервер для вашей школы. Его вводят в строке «Адрес сервера» — на экране «Как подключиться?», под полем кода или в «Настройки → Синхронизация»; на пути через свою школу его спросят, когда он понадобится. Адрес нужен тот, по которому сервер видит телефон: «localhost» для телефона означает его самого. + +Сменить класс или выйти из него — «Настройки → Класс». После выхода из последнего класса приложение откроет не знакомство заново, а выбор «Как подключиться?» — или дневник, если вы в него вошли. ## Три вкладки @@ -72,7 +81,7 @@ - Считает по времени школы, а не телефона. Родитель в другом часовом поясе видит звонки так, как они звонят в школе. - После уроков показывает домашнее задание — на следующий учебный день, а через каникулы на первый день после них. -> Если виджет говорит «нет данных» — откройте приложение: значит, на эту дату в кэше ничего нет и синхронизация ещё не проходила. +> Если виджет пишет «Расписание ещё не загружено» — откройте приложение и потяните экран вниз: на эту дату в кэше ничего нет. Виджет рисует только расписание класса, поэтому на телефоне без класса, где открыт один дневник, он пишет «Дневник — в приложении». ## Уведомления @@ -128,17 +137,23 @@ - /calendar — ссылка на подписку: расписание в календаре телефона. - /help — список команд, сгруппированный по тому, что вам доступно. -## Дневник Петербурга - +## Электронный дневник + + +Отдельная вещь и отдельный аккаунт: расписание класса ведёт бот, а электронный дневник — система, в которой школа ставит оценки, пропуски и задания. Приложение входит в «Петербургское образование» и в «Сетевой город» — в тех регионах, где он пускает по логину и паролю. В дневник, который пускает только через Госуслуги, приложение не входит. -Отдельная вещь и отдельный аккаунт: расписание класса ведёт бот, а дневник — государственный сервис Санкт-Петербурга, где лежат оценки, пропуски и задания, которые ставит школа. В приложении это «Настройки → Дневник». +Где дневник в приложении, зависит от того, как вы подключились. У телефона с классом он в «Настройки → Дневник». Без класса дневник и есть приложение: его две вкладки на главном экране, а в настройках шесть разделов — без содержимого, уведомлений и класса, которые работают только от класса. -Вход — те же логин и пароль, что на сайте дневника. Чем закончилась попытка, приложение говорит всплывающим окном: «Вход выполнен» с указанием аккаунта или «Не удалось войти» с причиной — неверная пара, дневник не отвечает, нет связи. Это разные вещи, и лечатся они по-разному. +Вход — те же логин и пароль, что на сайте дневника. Форма называет дневник и адрес, на который уйдёт пароль; в настройках «Сменить» рядом с названием выбирает другой дневник. Неудачу приложение объясняет всплывающим окном «Не удалось войти» с причиной — неверная пара, дневник не отвечает, слишком много попыток, нет связи. Это разные вещи, и лечатся они по-разному. -> Пароль нигде не сохраняется: он нужен ровно на один запрос, после чего его забывают и телефон, и сервер. Хранится только сессия самого дневника, и она живёт, пока сервис её продлевает. Когда она заканчивается, приложение просит пароль заново — логин при этом остаётся на месте. +> Пароль уходит с телефона прямо в дневник, по HTTPS, и больше никуда — ни на сервер, ни на диск телефона. Сервер получает только сессию, которую выдал дневник, и хранит её. Когда она закончится, приложение попросит пароль заново — логин при этом остаётся на месте. Внутри две вкладки — «Расписание» и «Оценки» — и выбор ребёнка, если аккаунт видит нескольких. Задания дневника показываются под уроками того дня, к которому заданы. Пропуск, опоздание и замечание сервис кладёт в один список с оценками, но приложение их различает и показывает по-разному. +Загруженное хранится на телефоне и открывается без сети — тогда приложение пишет, что показано сохранённое, и когда оно обновлялось. Перечитывает дневник приложение, только пока оно открыто: ни в фоне, ни из виджета дневник не читается. Поэтому и вход держится, пока приложение открывают: после 30 дней без этого войти придётся заново, а дневник Петербурга может закончить вход и раньше. + +«Выйти из дневника» — там же, в «Настройки → Дневник». Уроки и оценки, сохранённые на телефоне, удаляются, а сервер забывает свою копию входа; телефон без класса после этого возвращается к выбору «Как подключиться?». + > Сервис чужой и недокументированный. Если он ответит непонятно, приложение так и скажет: это чинится на сервере, а не в приложении. ## Управление классом diff --git a/docs/app/manifest.json b/docs/app/manifest.json index bb88df60..db200fbc 100644 --- a/docs/app/manifest.json +++ b/docs/app/manifest.json @@ -1,6 +1,6 @@ { - "version": 4, - "updated": "2026-09-22", + "version": 5, + "updated": "2026-09-25", "appVersion": "0.6.0", "files": { "ru": "guide.ru.md", diff --git a/docs/architecture.md b/docs/architecture.md index 53ebd48d..621544fb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -116,9 +116,10 @@ Five Gradle modules, split along the lines that actually pay for themselves: ``` :core:model pure JVM Kotlin — domain types + the state engine :core:designsystem theme + Compose components -:core:data Room, Retrofit, repositories, sync +:core:data Room (two databases), Retrofit, repositories, sync, + and the one client that talks to a diary directly :widget Glance home-screen widget -:app screens, navigation, ViewModels +:app screens, navigation, ViewModels, the first run ``` `:core:model` being a plain JVM library is the load-bearing decision: the state @@ -139,7 +140,10 @@ Telegram bot ──writes──▶ Postgres/SQLite ──/api/v1/bundle──▶ Room is the single source of truth. The network only fills it. Every screen and the widget read from Room, so the app is fully usable offline and the widget -keeps counting down in a dead zone. +keeps counting down in a dead zone. There are two databases, not one: `lessons.db`, +the class timetable this section is about, and `diary.db`, the family's own diary, +which is filled by a different rule and is described under +[the phone's half](#the-phones-half) of the diary. **One device, several classes.** A join code buys one read-only token for one class, so a pupil in two classes is a phone holding two tokens — that was always @@ -243,6 +247,88 @@ changed. Each sync fingerprints the next seven days — index, subject, start, r cancelled, replaced — and compares that against the previous one. The first sync sets the baseline and says nothing. +### Three homes: a class, a diary, or the way in + +A phone is in a class, reads its own diary without one, or has come in neither way yet, +and `ShellMode` (`NONE`, `CLASS`, `DIARY`) is that answer, decided by one rule in +`shellModeOf`: a class outranks a diary, so a phone with both lives in the class's app and +keeps the diary in settings. What makes `DIARY` is a stored diary **target** — which diary, +region, school and login — rather than a live session, because a bare `401` drops the bearer +and keeps the target, and a family whose session lapsed belongs on its own diary's sign-in +form rather than back at the start. The same rule is what sends a phone that leaves its last +class while signed in to a diary to the diary home, where the diary and its sign-out are, +instead of to a join screen that could reach neither (#151). + +`ShellModeSource` computes the mode, the first run's hold and the sync arming from **one** +read of the preferences file each time, never by combining a class flow with a diary flow: +two flows can disagree for an emission in between, and a gate that flickered to the wrong +home for a frame would reset the state of the one it left. The gate itself is a pure +function, `rootScreen` in `navigation/RootGate.kt`: nothing read yet is the splash, a hold or +`NONE` is the first run, anything else is a home, and `LessonsApp` keys the home on which one +it is, so moving between the class's home and the diary's resets the shell rather than +landing in a section of the old one. `AppShellViewModel` settles a cold start once per +process before the gate first reads: a hold left over in `NONE` means the credential it was +waiting for never landed, and it is dropped. + +What each home offers is one rule too, `SettingsSection.listedOn(mode, manager)`: the diary +home drops the sections that are about a class — content, alerts and the class account, +whose requests need a class token this phone does not have — and keeps the rest. + +**The periodic class sync is armed in a class and nowhere else** (#152). The application +used to schedule `SyncWorker` on every emission of the settings, whatever was stored, so a +phone that had just left its last class — whose sign-out had cancelled the worker — was woken +every fifteen minutes again from its next launch, for a run that found no class and returned; +a diary-only phone would have been woken that way for ever. `LessonsApplication` now collects +`shellMode.syncArming`, which is `syncArmingFor(mode, interval)`: armed at the interval in +`CLASS`, cancelled in `NONE` and `DIARY`. `SessionEffects` still arms on a join and cancels +on the last sign-out, and agrees with the rule. `SyncArmingTest` holds it, including a source +check that the application collects the arming and not the interval alone. + +The widget reads the mode as well — it has a sentence for each +([widget.md](widget.md#when-there-is-nothing-to-draw)) — and never the diary: the reason is +the diary's, under [the phone's half](#the-phones-half). + +### The first run holds the screen + +The first run is `ui/onboarding/`, and its rules are pure: `OnboardingFlow` turns a state — +the steps walked as a **path**, a floor below which back cannot go, and the answers +collected — into the next state, the dots and the step to draw, with no Compose and no +Android, so every route through it is a JVM test. Why a path and what the dots count is a +design decision and is written down in [design.md](design.md#first-run-is-a-path-not-one-field). + +`OnboardingViewModel` is activity-scoped and owns a handful of plain holders, each tested on +its own: `SignInStep`, `ImportRunner`, `RegionFinder` and `SchoolFinder`. What lives where is +the security of the flow, and it is deliberate: + +| What | Where it lives | Where it never is | +| --- | --- | --- | +| the path and the answers (region, school, system) | the view model's `SavedStateHandle`, so a recreate and a process death bring the step back | — | +| the login | the sign-in step's memory | the saved state | +| the password | the form's text field, and then one argument to `submit` | any field of any holder, the saved state, the disk | +| the diary's own session, between the diary's answer and ours | a private field of `SignInStep`, behind an opaque `HeldUpstream` | the saved state, the disk, anything the screen can read a token out of | +| our diary bearer, once registered | the preferences store, like the class bearer | — | + +The held session exists for one case: our server could not be reached after the diary let the +phone in. Then «Повторить без пароля» registers the same session again, and nobody types the +password twice; any other failure has already discarded it, and leaving the step discards it +upstream. `OnboardingViewModelTest` checks every value in the saved state for the login and +the password, and `OnboardingStepsTest` checks by reflection that the password is never a +field of the sign-in step. + +**The hold.** A join and a registration both write their credential before the flow is over — +an import or a summary is still to come — and either write turns the phone from `NONE` into a +class phone or a diary phone at once. So the flow calls `shellMode.hold()` on entering the +class-code or the sign-in step and `release()` in `finish()`, the gate keeps the first run on +screen while the hold is set, and the hold is persisted: after a process death, +`OnboardingFlow.resume` picks up at the import for a registered diary, at the class's diary +sign-in for a joined class whose diary this build can sign in to, and otherwise finishes. The +introduction counts as seen when the flow **reaches the chooser**, and `LessonsApp` latches +that flag on its first composition, so writing it cannot restart the flow under the finger. + +Nothing composes `LessonsApp` in a test: the gate, the hold through a real join, the swap to +the right home and the resume after a process death are held by the pure rules and the view +models only. + ### The guide is data, not code The documentation inside the app used to be 103 string resources and a Kotlin file naming @@ -352,9 +438,11 @@ contract; it never learns which upstream is behind it. - **`app/providers/petersburg/`** — «Петербургское образование» (`dnevnik2.petersburgedu.ru`), the first provider and still the only one that signs in with an email and a password alone. - **`app/providers/netschool/`** — «Сетевой город. Образование», the diary of about twenty - regions on one route set (`/webapi`) served from a different regional host in each. It is - server-side only, and **it has never met a live server**: every upstream shape is read from - open-source clients and hand-written payloads, exactly as Petersburg's was (#121, #135). + regions on one route set (`/webapi`) served from a different regional host in each. Its + reads are the server's alone — the phone speaks only its sign-in and its school search + ([the phone's half](#the-phones-half)) — and **it has never met a live server**: every + upstream shape is read from open-source clients and hand-written payloads, exactly as + Petersburg's was (#121, #135). What every region of the country runs, and the routes of each platform as its open clients call them, is surveyed in [diaries.md](diaries.md); [diaries/netschool.md](diaries/netschool.md) @@ -421,9 +509,9 @@ idles a session out in 15–60 minutes, so the cron tick keeps each live one ali `GET /webapi/context` (the mechanism is in [deploy.md](deploy.md#the-clock-the-server-has-none-and-githubs-will-not-do), the counters in [api.md](api.md)). When a session dies either way, the request answers `401` with -`X-Diary-Reauth: required` and the person signs in again. The price is that a background -sync of the diary does not outlive the session; the price of the alternative is every -family's password in the database. +`X-Diary-Reauth: required` and the person signs in again. The price is that nothing reads +the diary once its session is gone — and the phone never reads it in the background at all; +the price of the alternative is every family's password in the database. ### Two ways a session arrives, and only one of them sees the password @@ -443,16 +531,18 @@ asking for it again would loop. Whether either diary does take a session opened and replayed from Frankfurt is exactly what has never been seen; the contract, the statuses and the shared limiter are in [api.md](api.md#the-electronic-diary). -The cost is that the sign-in protocol now lives on both sides — a client that registers -speaks it to the diary, and the server still speaks it for the bot and for older apps — and +The cost is that the sign-in protocol now lives on both sides — this app speaks it to the +diary, and the server still speaks it for the bot and for older apps — and two implementations of «Сетевой город»'s salted hash over a windows-1251 password agree exactly until they do not. The known-answer vectors in `server/tests/vectors/diary_protocol.json` are the one set of bytes both are -tested against; the Python half is driven over `httpx.MockTransport`, and #147 and #148 — +tested against; the Python half is driven over `httpx.MockTransport`, the Kotlin half over +MockWebServer, and #147 and #148 — a sign-in that sent the word `None` upstream, and malformed answers that escaped as `500` — were fixed in the same change. -The other doors stay. `/diary/login` is unchanged for the apps that still call it. The bot's +The other doors stay. `/diary/login` is unchanged for the APKs built before registration; +this app stopped calling it in the same batch that made the phone sign in itself. The bot's page still relays the password — it posts to this server, which passes it to the diary once and writes it nowhere — and since #150 **it says so**: the page and the two cards before it used to promise the password went «прямо в дневник», which it never did. A registered @@ -463,6 +553,113 @@ bearer families would meet — and a linked session would inherit the bot's rule «Выйти» would sign the phone out too, deleting the class would take the phone's session with it, and rebinding the class would expire it. Those are the owner's to weigh first. +### The phone's half + +The app signs in to a diary itself and hands our server only the session. That puts part of +the diary on the phone, and it is fenced exactly as the server's is: everything that knows a +diary's routes lives in `core/data/.../upstream/`, and what comes out of it is an opaque +`UpstreamSession` or a failure with a name. + +**One client, and it talks to diaries only.** `UpstreamHttp.client` shares nothing with the +client that talks to our server, which rewrites every host to the configured server and signs +requests with our bearers by path; a diary request through that one would go to our server, +or carry our bearer to somebody else's. This one has no cookie jar (the session travels per +request, so two sign-ins cannot meet), follows no redirect (a `302` to another host is the +one way around an allow-list), does not retry a failed connection (`getdata`'s salt is +one-shot, and a silent re-POST reads as a wrong password), and carries exactly two +interceptors: `OriginGuard`, which refuses any origin not on the allow-list before a byte is +sent, and one that refuses an `Authorization` header outright. The failures are classified +once: only a failure that examined the certificate is "untrusted" — a handshake the network +broke is "unavailable", with a retry. + +**The bundled catalog is the only source of a diary host.** The app bundles +`server/app/catalog/data/regions.json` in place as an asset, never a copy, and +`CatalogUpstreamDirectory` builds the allow-list from it, dropping any origin that is not +`https` or carries a path, a query, a fragment or credentials. Nothing typed and nothing +received ever becomes a host: a region is picked by its key and the key finds an origin; the +one piece of user input that reaches a diary, a school search, travels as a query parameter. +The same file is the phone's region search — names in both languages, aliases, cities, codes, +the wrong keyboard layout and transliteration, all read from the catalog's `search` block +([diaries.md](diaries.md#the-region-catalog)) so that no Russian word has to be written in +Kotlin. The ports are Kotlin twins of the server's: Petersburg's sign-in, «Сетевой город»'s +salted hash with its own windows-1251 table (carried in the code rather than trusted to the +device's ICU), the server's login cleaning (`DiaryLogin.clean`, character for character, so a +login pasted with an invisible character is not a wrong password on one side only), and a +JSON reader that refuses what Python's `json.loads` refuses. `DiaryProtocolVectorsTest` runs +every case of `server/tests/vectors/diary_protocol.json` through them, read in place from +the test classpath and over real sockets where the case is a request, so the two +implementations cannot drift apart silently. `upstream/UpstreamMarkers.kt` is the one Kotlin +file allowed Cyrillic: the diaries' own words, matched in their answers. + +**Registration.** `DiarySignIn` is four steps, and the first run's sign-in step drives them +one at a time. *Preflight* checks the catalog row — region known, password sign-in, school +present — and then asks `GET /api/v1/diary/capabilities`, before the password field means +anything. *Open* cleans the login, refuses one too short and an empty password without a +request, and signs in at the diary. *Register* refuses a session too old to hand over and one +the server's schema would refuse, posts it as `credential` to `POST /api/v1/diary/session`, +and keeps our bearer and a `DiaryTarget` — provider, region, school, login and the diary's +zone, one JSON key in the preferences. A different account than the stored one empties the +phone's copy of the diary and the chosen pupil **before** the new session is written. +*Discard* signs a «Сетевой город» session that will not be registered out upstream +(Petersburg has no logout outside a browser); a session is spent once, by a registration or +a discard. A bare `401` later clears our bearer only and keeps the +target, which is what keeps the phone on its diary's sign-in form; signing out forgets both. +Every failure on the way is a `DiarySignInProblem`, and every diary screen turns one into +words through one mapping, `ui/diary/DiaryProblemText.kt` — too many attempts, a switched-off +diary, a diary that refuses our server's address and a timeout each have their own, naming +the host where there is one, and «Повторить» is offered only where a retry can help (#153). +Our diary bearer is kept off `/diary/login`, `/diary/session` and `/diary/capabilities`, and +the class bearer off `/api/v1/directory/` and `/api/v1/diary/`, each held by a test. + +**`diary.db` keeps what was read, and has one writer.** It is a second Room database with an +exported schema: pupils, the terms, lessons, homework and marks, and a row per pupil per week +whose stamps tell "fetched and empty" from "never fetched" — the same distinction +`synced_window` draws for the class. Nothing writes it but `DiaryRepositoryImpl`'s own +successful reads (`remembered`): the pupils, the terms, any window of marks, and a timetable +or homework range of whole Monday-to-Sunday weeks, each written through as it arrives; a +write that fails costs the copy, never the answer. **A generation guards it:** a sign-out's +`clear()` bumps the generation under the same lock every write takes, a read takes the +generation before its request, and a read that was in flight across a sign-out or another +account's sign-in is dropped rather than written back after the clear. The registration's +own list of pupils is written by `SeedingDiarySignIn`, so the import need not ask again. The +database sits under the backup rules' existing exclusion of every database. + +**The import** fills it once, after the first registration: the pupils, the choice of pupil +(asked only when the account has several and none was chosen before), the terms, this week's +and next week's timetable, the homework and the marks of the current term — sequential, with +a weight per phase for the progress bar (rough costs, not measured ones). The pupils and the +timetable stop it; the terms, the homework and the marks are skipped and named, and a session +the diary ended stops it with a way back through the sign-in. It resumes from the phase that +failed, reading the earlier ones from the cache, and "today" is taken in the diary's zone, +not the phone's. + +**The only diary read nobody pressed for is `refreshIfStale`**, and it runs in one place: the +diary home's `LifecycleStartEffect`, each time the app comes to the foreground. When the +current week's copy is older than thirty minutes it re-reads this week's and next week's +timetable and homework; while an import holds the lock it does nothing. It goes through +`DiaryViewModel.refreshOnStart`, so the screen's own load waits for it rather than reading +the same week a second time. **There is no background diary read at all** — not in the +worker, not in the widget, not in the alerts, not in any application class, receiver or +service a manifest declares — and `SyncWorkerSourceTest` scans all of those and fails on a +reference to the diary's repository, cache or import. The reason is the keep-alive: a +«Сетевой город» session is kept open for up to thirty days after the family last used it, and +a read from the background would count as use with nobody there. The screens read the saved +copy first, skip the network while it is fresh, and keep it on the screen, saying when it was +saved, when the diary or the network cannot be reached. + +**The school search is two lookups.** «Which region is this school in» asks our server's +anonymous directory, `GET /api/v1/directory/school-regions`, and only for a query that looks +like a school's name and is not too common to place, so the day's allowance is spent on +questions it can answer. «Which school in this region» asks the region's own diary server +from the phone, like the sign-in. + +**Not verified.** None of this has met a live diary or run on a device. Whether a diary +accepts a session opened on a phone when our server in Frankfurt replays it is open — the +`409` is the designed failure. TLS against the regional servers (the tests run plain HTTP, +and the certificate failures are the shapes Conscrypt and the JVM are known to throw), Room's +invalidation of `diary.db` on a device, and a `Retry-After` given as a date (read as no wait) +are unverified too; the device's own windows-1251 is never asked, on purpose. + ### The region catalog is generated, not written «Which region is this family in, and what can it do there» has one answer, and it is the @@ -471,8 +668,8 @@ survey's. `server/app/catalog/data/regions.json` is generated from allow-list by `python -m scripts.region_catalog`, and committed; a test fails when the committed file and its inputs disagree. Generated, because the alternative was prose parsed at run time, or a second hand-kept list of eighty-nine regions that would disagree with the -survey within a month; committed, because the server reads it at run time and the app is to -bundle the same file, and neither should run a generator to start. The decisions it carries — which systems are a sign-in, +survey within a month; committed, because the server reads it at run time and the app +bundles the same file, and neither should run a generator to start. The decisions it carries — which systems are a sign-in, which a hand-off to the browser, why there is no Госуслуги sign-in anywhere — are written down beside the survey, in [diaries.md](diaries.md#the-region-catalog). The server reads four things from it: a region's key, its subject code, its names and DaData's spellings of it, @@ -508,9 +705,9 @@ with the host. ## Testing -1915 tests on the server, 968 on Android; `pytest -q -n auto` and `./gradlew test`, both -offline, both in CI. On Android that is `:core:model` 125, `:core:data` 286, -`:core:designsystem` 95, `:widget` 90, `:app` 368. +1944 tests on the server, 1371 on Android; `pytest -q -n auto` and `./gradlew test`, both +offline, both in CI. On Android that is `:core:model` 125, `:core:data` 532, +`:core:designsystem` 99, `:widget` 102, `:app` 513. The table below is the load-bearing part of that rather than the whole of it: @@ -539,12 +736,18 @@ The table below is the load-bearing part of that rather than the whole of it: | `server/tests/test_scripts.py` | that both one-shot scripts refuse a database that is not a local file, and say truthfully where they are about to write | pytest | | `server/tests/test_announcements.py` | that every place pushing to the class is bounded, measured at the call site rather than on the helper | pytest | | `android/core/model/.../StabilityPromiseTest.kt` | that nothing in the domain module is a `var`, which is what `compose-stability.conf` promises the Compose compiler | JVM JUnit | +| `android/core/data/.../upstream/DiaryProtocolVectorsTest.kt` | the phone's sign-in ports against the same known-answer vectors as the server's, over MockWebServer | JVM JUnit | +| `android/core/data/.../diary/DiaryCacheTest.kt`, `DiaryImportTest.kt` | `diary.db`'s write-through, the generation guard across a sign-out, the import's phases, resume and zone, and `refreshIfStale` | JVM JUnit | +| `android/core/data/.../sync/SyncWorkerSourceTest.kt` | that the worker, the widget, the alerts and every declared application, receiver and service never name the diary | JVM JUnit, reading the sources | +| `android/app/.../RootGateTest.kt`, `SyncArmingTest.kt` | which home each mode opens on, and that the class sync is armed in a class only | JVM JUnit | +| `android/app/.../ui/onboarding/OnboardingFlowTest.kt`, `OnboardingViewModelTest.kt` | the first run's routes, dots and resume, and that the saved state never carries a credential | JVM JUnit | What nothing covers is a device: there is no `androidTest` directory, so not one test has -run on hardware or an emulator. Twenty of the app's screens, sheets and rows are composed -under Robolectric with a Russian locale and a phone's width — among them the class list, the -join mode, the connection errors, the first-run reveal, the crash-report sheet, the two -sheets the calendar reopens after a rotation, its header and its day list — and the design +run on hardware or an emulator. About two dozen of the app's screens, sheets and rows are +composed under Robolectric with a Russian locale and a phone's width — among them the class +list, the join mode, the connection errors, the first-run reveal and its legal line, the +diary home, the crash-report sheet, the two sheets the calendar reopens after a rotation, its +header and its day list — and the design system's components are exercised the same way; for the rest of the interface, compilation proves the types line up and says nothing about the screen. The "Honest status" section of the README keeps the full list — that is the honest status, not an oversight. diff --git a/docs/build.md b/docs/build.md index dd21314f..07ebee5d 100644 --- a/docs/build.md +++ b/docs/build.md @@ -81,20 +81,23 @@ cd ../android The Android SDK has to be real — its path in `android/local.properties` or in `ANDROID_HOME` — and Gradle does not, because the wrapper is in the repository. Nothing -about the app is configured in a file: the address of the server is typed into the app on -the connection screen, and how to make it reachable from a phone is "Pointing the app at a -server" at the end of this page. The class code is the one the bot hands out with `/code`, -or `DEMO24` from the seeding script. +about the app has to be configured in a file: the address of the server is typed into the +app itself, and how to make it reachable from a phone is "Pointing the app at a server" at +the end of this page. The class code is the one the bot hands out with `/code`, or `DEMO24` +from the seeding script. The one build setting a **fork** has to think about is where the +first screen's terms and privacy policy link to — "The terms and the privacy policy the app +links", below. ### The other place variables live, and it is not `.env` -**GitHub Actions holds eight repository secrets of its own** (Settings → Secrets and -variables → Actions), and they overlap with `server/.env` by exactly one name. They are -nothing to do with running the project — none of them is read by the server, and a fresh -clone needs none of them to develop against. They exist because two workflows do things a -local build does not: sign an APK, and call a deployed server. +**GitHub Actions holds eight repository secrets and one repository variable of its own** +(Settings → Secrets and variables → Actions), and they overlap with `server/.env` by +exactly one name. They are nothing to do with running the project — none of them is read by +the server, and a fresh clone needs none of them to develop against. They exist because two +workflows do things a local build does not: sign an APK and say whose terms it links, and +call a deployed server. -| Secret | Read by | Without it | +| Name | Read by | Without it | | --- | --- | --- | | `KEYSTORE_BASE64` | `apk.yml` | the release APK is signed with the **debug** key; the workflow says so as a warning and carries on. It installs and must not be published — see "Signing" below | | `KEYSTORE_PASSWORD` | `apk.yml` | as above: all four are needed together, and Gradle treats three of four as no key at all | @@ -104,12 +107,14 @@ local build does not: sign an APK, and call a deployed server. | `LESSONS_CONTACT_EMAIL` | `apk.yml` | «Отправить письмом» is hidden | | `SERVER_URL` | `reminders.yml` | the fallback tick skips with a notice rather than failing — see [deploy.md](deploy.md), "The clock" | | `CRON_SECRET` | `reminders.yml` | the same skip | +| `LESSONS_LEGAL_BASE_URL` — a **variable**, not a secret | `apk.yml` | the APK links `docs/legal/` of the repository the workflow runs in — see "The terms and the privacy policy the app links" | Four things about that table are worth more than the table. -**`ci.yml` reads no secret at all.** The gate — ruff, pytest, `./gradlew test` and both -assembles — needs nothing configured, which is why a pull request from a fork runs the -whole of it. +**`ci.yml` reads no secret and no variable at all.** The gate — ruff, pytest, `./gradlew +test` and both assembles — needs nothing configured, which is why a pull request from a fork +runs the whole of it. The one consequence worth knowing: its APKs are built with the legal +link's default, so they link *this* repository's terms, whoever's CI built them. **`CRON_SECRET` is one value living in two places, and nothing checks that they match.** The server takes it from its own environment and compares it with the `X-Cron-Secret` @@ -128,8 +133,9 @@ Nothing in Actions imports the server's code: the tests set their own key in `tests/conftest.py`, and `reminders.yml` only calls an already-deployed endpoint over HTTP. It belongs to whatever *runs* the app, which is Vercel's environment variables. -The signing four are set up in "Configuring your own key" further down, and the two build -properties in "What the build is told about itself". +The signing four are set up in "Configuring your own key" further down, the two build +properties in "What the build is told about itself", and the variable in "The terms and the +privacy policy the app links". ## Through GitHub Actions @@ -200,7 +206,7 @@ step. What stayed in CI for good: - **`pytest -n auto`.** The suite spread across the runner's cores: 289 s → 101 s on four cores locally, 12:18 → 3:23 on the runner, the same 1340 green — 1340 was the count when - this was measured; it is 1630 today. That is safe by + this was measured, and the README's "Honest status" has today's. That is safe by construction rather than by luck: `tests/conftest.py` takes the SQLite path from an `mkdtemp` computed at import time, and every xdist worker is a separate process with its own import, so they never share a database. It started as a saving and stayed for the @@ -222,9 +228,15 @@ step. What stayed in CI for good: the short life, uploading the test reports is marked `continue-on-error`: the gate is `./gradlew test`, not where the report landed. - **Path filters.** The "What changed" job decides in eight seconds which halves could - possibly have broken; a change confined to `docs/` runs neither. If the commit range - cannot be worked out (a force push, a branch's first push), both run — a skipped build - costs more than ten wasted minutes. + possibly have broken, and a half runs when a file **its tests read** changed, not only a + file in its own folder. So a change confined to `docs/` usually runs neither — but + `docs/app/` and `docs/legal/` are packaged into the APK and run Android; `docs/build.md`, + `docs/deploy.md`, `docs/diaries.md` and `docs/diaries/` are read by server tests and run + the server; and the region catalog and the protocol vectors, which live under `server/` + and are the phone's inputs too, run both. A commit touching only one of those documents + used to run nothing and come back green (#159); `ci.yml` names each file beside the test + that reads it. If the commit range cannot be worked out (a force push, a branch's first + push), both run — a skipped build costs more than ten wasted minutes. And one thing that did **not** stay: for a while, release was not built on a pull request. That saved about two minutes per push at the cost of finding a broken R8 at the merge @@ -529,6 +541,68 @@ mailbox is the answer, not leaving it empty. Both are ordinary build properties: `lessons.github.clientId` and `lessons.contactEmail` in `~/.gradle/gradle.properties`, or the environment variables above. +## The terms and the privacy policy the app links + +The first screen of the first run says «Продолжая, вы принимаете Условия использования и +Политику конфиденциальности» under its «Продолжить» button, always, and «О приложении» has a +row for each document. Both names are links, and where they lead is a build setting: +`LESSONS_LEGAL_BASE_URL` in the environment or `lessons.legal.baseUrl` in +`~/.gradle/gradle.properties`, compiled into `BuildConfig.LEGAL_BASE_URL`. + +**What it is.** The `https://` address of a folder holding `terms.ru.md`, `terms.en.md`, +`privacy.ru.md` and `privacy.en.md` — the four files of [docs/legal/](legal/). The app +appends `/terms.ru.md` and the like, Russian for a Russian reader and English for everybody +else, and opens the result in the browser when the phone has a validated network and a +browser starts. Otherwise — offline, behind a captive portal, no browser — it shows the copy +the APK carries: `docs/legal/` is an asset folder of `:app`, so the bundled text is the +repository's own bytes at build time, in a sheet that names its edition and date from +`docs/legal/legal.json`. + +**What the build refuses.** A value that is not `https://`, has no host, or carries a query +or a fragment fails the build with a message pointing here, and so does a quote, a backslash +or a space, which would break the generated Java string. It is refused rather than kept +because it is the first link of every install, and a policy fetched over plain HTTP is one +anybody on the café's network can rewrite before it is read. A trailing slash is trimmed; a +blank value counts as unset. + +**The default is not empty:** `https://github.com/lumenpearson/lessons/blob/HEAD/docs/legal`, +this repository's folder on its default branch (GitHub resolves `blob/HEAD` to it). That is +so a build from a fresh clone links a real, current document rather than nothing — and it +means **a build that sets nothing links this repository's operator's texts.** A local +`./gradlew`, and every APK `ci.yml` builds, is such a build. + +**`apk.yml` works it out per repository.** Its «Resolve legal documents» step derives +`https://github.com///blob//docs/legal` for whichever repository +the workflow runs in (`HEAD` when the event carries no default branch), so a public fork's +APK links the fork's own folder with nothing configured. The repository **variable** +`LESSONS_LEGAL_BASE_URL` (Settings → Secrets and variables → Actions → **Variables**) +overrides the derivation — a variable rather than a secret because the value is public and +the run summary prints it, which a masked secret would not allow. The step checks the value +in seconds, before the compile: whitespace, a quote, a backslash or anything that is not +`https://` fails it. On a **private** repository it warns, because the derived address opens +for nobody outside the repository; set the variable to somewhere that does. The summary's +«Terms and privacy policy» row says which address was used and where it came from. The +default branch rather than the branch or tag being built, because an installed APK keeps its +link for life: a feature branch is deleted within a week, and a tag would freeze the policy +at the day it was cut. + +**What every fork has to do.** Set the address to its **own** `docs/legal/` — nothing for a +public fork's `apk.yml`, the variable for a private one, the property for any build made by +hand. Then rewrite the texts themselves: the address changes where the link goes and not a +word of what it says, and until the passages marked `FORK` are rewritten the fork's copy still +names this repository's maintainer as the operator, and this deployment's hosting, database +and country. The fields each passage needs are listed at the top of +`docs/legal/privacy.ru.md` and `docs/legal/terms.ru.md`. The Russian file is the source and the +English one its translation, held level section for section by `LegalDocumentsTest`; a change +to what the code stores, sends or keeps changes the texts and raises the `edition` in +`legal.json`. + +**Not verified.** That the default address answers was checked on 25 September 2026 by +fetching it, not by a tap on a phone; that `github.event.repository.default_branch` is filled +on a manual run rests on GitHub's documentation; no run of `apk.yml` with this step has been +seen; neither the browser hand-off nor the bundled sheet has been opened on a device. The texts +describe what this code does and were never reviewed by a lawyer. + ## Locally ```bash @@ -638,8 +712,10 @@ The app needs an address the **phone** can reach, not the computer. `localhost` network rather than the app: the phone and the computer have to be on the same Wi-Fi, and the firewall has to let port 8000 through. -4. In the app, press **Сервер** at the bottom of the connection screen and enter - `http://
:8000/`. Then enter the class code. +4. In the app, press «Адрес сервера» under «Сервер» — on the first run's «Как + подключиться?» screen, at the bottom of the class-code screen, or later in «Настройки → + Синхронизация» — and enter `http://
:8000/`. Then enter the class code. The app + has no server of its own to fall back to: until an address is typed, there is none. The bot hands out a class code with `/code`, and `python -m scripts.seed_demo` creates a demo class with the code `DEMO24`. @@ -649,6 +725,29 @@ demo class with the code `DEMO24`. Since Android 9 the system blocks `http://` by default. The app allows it through `network_security_config.xml`, because the real scenario is a server in the same school, reachable at a local address, and public CAs do not issue certificates for an IP on a -private network. What travels over that wire is only a class code and a timetable: no -passwords, no personal data. If the school has configured TLS, enter `https://` — the -configuration does not apply to such an address. +private network. If the school has configured TLS, enter `https://` — the configuration does +not apply to such an address. + +What travels over a plain `http://` wire is **not** harmless, and this page used to say it +was — «only a class code and a timetable: no passwords, no personal data». The diary +**password** is not on it, from this app: the app signs in to the diary itself, straight at +the diary's own origin, which comes from the region catalog bundled in the APK and is +`https://` or dropped; the client that makes that request refuses any other host +(`OriginGuard`) and follows no redirect, so nothing typed into the server field can send the +password anywhere near it. What does cross an `http://` server, readable by anybody on the +same Wi-Fi, is: + +- the diary **session** the diary handed back, sent once at registration + (`POST /api/v1/diary/session`) — a working key to the child's diary until it expires; +- the **diary bearer** on every diary read, and the marks, homework and timetable in the + answers; +- the **class bearer**, which is a write token on a phone connected with a personal code or + linked to Telegram, along with the phone's name and the class's timetable. + +Two routes still carry a **password** through the server, and over `http://` they carry it +in the clear: the older `POST /api/v1/diary/login`, kept for the APKs built before +registration, and the bot's sign-in page, which posts the password to the server at +`PUBLIC_BASE_URL` — in the clear if that address is `http://`. Neither is on this app's path. +Before anything is typed, the app's diary sign-in warns when the server address is `http://` +(«⚠️ Адрес сервера начинается с http://…»), and the warning is about the session, not the +password; the configuration file's own comment carries the same list. diff --git a/docs/design.md b/docs/design.md index 8c95dd10..e9268ca5 100644 --- a/docs/design.md +++ b/docs/design.md @@ -103,7 +103,7 @@ does not apply. | `utils/ui/HapticUtil.kt` | `haptic/LessonsHaptics.kt` | | `MainActivity` (the tab pager) | `navigation/LessonsApp.kt` | | `ui/activities/SettingsActivity.kt` | `ui/settings/SettingsScreen.kt` | -| `ui/composables/WelcomeScreen.kt` | `ui/onboarding/` — the four steps of first run | +| `ui/composables/WelcomeScreen.kt` | `ui/onboarding/` — the introduction of the first run | The AGSL shaders — both the scroll blur and the blur under the sheet — were carried over character for character. They were tuned by eye, and an "improved" constant in them breaks @@ -224,41 +224,102 @@ finger on a row would just as silently stop working again. So instead of coverin we remove them from the composition once the page has arrived: there is nothing to block and nothing to depend on. `rememberSaveableStateHolder` keeps their scroll position. -## First run is four screens, not one field +## First run is a path, not one field A new install used to open with a field for a class code. That is asking a stranger to type -a key they were given, on a screen that has said nothing about itself yet. - -The order is now the same as in Essentials' `WelcomeScreen.kt`, and it is not accidental: - -1. **Welcome** — the app's mark, its name, the theme picker and the language picker. The - mark spins under a finger and springs back with haptics: it is the first thing the user - touches, and it answers instantly. Essentials has the language picker in this slot, and - now so do we — together with the theme, the second setting whose effect is visible on the - next frame. The language sits on the very first step rather than on "Properties" two - screens later because between them lies the acknowledgement: four paragraphs on what this - timetable is and what it is not, the most useful thing a new user reads at all. Somebody - who does not read Russian has to be able to switch the language before that, not after. - The setter and the strings are the same ones the settings page uses. Below API 33, - changing the language recreates the activity, so the step number lives in - `rememberSaveable` rather than `remember`: `recreate()` saves and restores instance state - exactly as a rotation does, so the step, the latched decision to show the introduction and - the view model all survive — only the slide animation is lost, and that is no loss. +a key they were given, on a screen that has said nothing about itself yet. And since the +family's own diary became a way in, a field for a class code is also the wrong question for +half the people who open the app: a family whose class is kept in no bot has no code to type. + +So the first run is an introduction followed by a choice, and the introduction keeps the +order of Essentials' `WelcomeScreen.kt`, which is not accidental: + +1. **Welcome** — the app's mark, its name, the theme picker and the language picker, and + «Продолжить». The mark spins under a finger and springs back with haptics: it is the first + thing the user touches, and it answers instantly. Essentials has the language picker in + this slot, and so do we — together with the theme, the second setting whose effect is + visible on the next frame. The language sits on the very first step rather than on + "Properties" two screens later because between them lies the acknowledgement: a few + paragraphs on what this app shows and what it does not, the most useful thing a new user + reads at all. Somebody who does not read Russian has to be able to switch the language + before that, not after. The setter and the strings are the same ones the settings page + uses. 2. **Acknowledgement** — what the app shows, what it does not do, and the one thing it can record. Crash reports are off by default and are chosen right here, next to the text that explains them. 3. **Properties** — haptics, colours from the wallpaper, a black background, blur, the teacher on a lesson's row, the progress bar in the widget. Not every setting, but the ones that can be judged without having seen a single lesson. -4. **The class code** — the very same `JoinScreen` rather than a copy of it, with a back - button. - -The "introduction shown" flag is set on entering the fourth step rather than after a -successful connection: somebody who closed the app on the code field has already read the -introduction. The decision whether to show the introduction is latched on the first -composition — otherwise writing the flag would swap the screen out in the middle of the -slide. Leaving the **last** class returns to the bare code field rather than to the four -screens again; while at least one other class remains on the phone, the app simply shows it. +4. **Permissions** — one card per permission. It stays **before** the choice although a + family that takes the diary way in gets no alerts: moved behind the branch, the question + would be asked on one path only. The summary at the end hides its notifications row on a + phone with no class instead. +5. **«Как подключиться?»** — two cards, «По коду класса» and «Найти свою школу», and the + server address. Nothing is preselected, and the button names the way that was chosen. + +From the choice the flow branches. «По коду класса» is the very same `JoinScreen` rather +than a copy of it; a class whose join names a diary this build can sign in to goes on to +that diary's sign-in, with «Не сейчас» beside it. «Найти свою школу» is region → school → +diary system → sign-in → import → summary, and a region skips what it does not need: the +school step exists only where the diary is «Сетевой город», whose sign-in needs a school, and +a region whose diaries the app cannot sign in to ends at the system step, with the diary's +site to open and the class code offered instead. + +**A path, not an index.** Once the flow branches, "step 4 of 9" stops meaning anything, so +`OnboardingFlow` keeps the steps walked as a list: back pops it, the slide's direction is +depth rather than enum order (the system step's way to the class code is plainly forward), +and the badge above the slide morphs along the path. A **floor** in the path is raised by +every write that cannot be undone by going back — a join, a registration, a finished import +— so back never reopens the join screen over a class already joined, or a sign-in that would +open a second session on the server. The path and the answers are the view model's, saved in +its `SavedStateHandle`: a `recreate()` for the language below API 33, and a process death, +bring back the step; no login, password or session is ever among what is saved. + +**The dots count a chapter, not the flow.** The whole flow is not known until the choice has +been answered, and a count that grew at the choice would read as the flow getting longer — +the one thing progress dots must never do. So the introduction is five dots and the choice +closes it; the school way is a chapter of its own, counted from what is known — a region not +yet picked projects the longest route, so the count can only shrink as answers arrive; the +join screen has no dots and no badge, because it has a heading of its own. The steps with a +search or a keyboard (region, school, system, sign-in) keep the dots and drop the badge, +because they need the height more than a shape. + +**The flow, not the credential, decides when it is over.** A join and a registration both +land before the flow is finished — there is still an import or a summary to show — and each +makes the phone a class phone or a diary phone at once. Left to the credential, the app would +swap to a half-filled home mid-flow. So the flow holds the screen from the class-code or +sign-in step until its last «Открыть приложение», and the hold is persisted: a process death +between the write and the summary brings the flow back at the import or the class's diary +rather than dropping the family onto a home. How it is stored is in +[architecture.md](architecture.md#the-first-run-holds-the-screen). + +The "introduction shown" flag is set on reaching the choice rather than after a successful +connection: somebody who closed the app there has already read the introduction. The +decision whether to show it is latched on the first composition — otherwise writing the flag +would restart the flow under the finger. Leaving the **last** class returns to the choice +rather than to the introduction, and there is no bare code field any more: it could reach +neither the diary nor the diary's sign-out. A phone still signed in to a diary goes to the +diary instead. + +**The line under the first button.** «Продолжая, вы принимаете Условия использования и +Политику конфиденциальности» is drawn under «Продолжить» on every build, whatever the build +says about where its documents are published: with no reachable address, a tap opens the copy +bundled in the APK, so there is never a first screen that asks to continue without saying on +what terms. The two names are `LinkAnnotation.Clickable` rather than `Url`, so that every tap +can fall back to the bundled copy instead of handing a dead link to the system; and the +sentence is one template with two placeholders rather than three pieces with spaces at their +edges, because aapt2 trims a string's edge spaces — which is how the about page's credit came +out as «по мотивамEssentials» (#155). The address is a build setting, +[build.md](build.md#the-terms-and-the-privacy-policy-the-app-links). + +**No server is promised.** The APK carries no server address, so no screen may speak of a +default one, and the class-code screen and the settings no longer do (#154). The school way +asks for the address where it is first needed — pressing sign-in with none set opens the +address sheet, saying that the password will not go there — rather than on a screen of its +own before anybody knows why it is needed. + +The whole flow is held by pure rules and view-model tests; nothing composes it end to end, +and none of it has been seen on a device. ## Notifications @@ -992,11 +1053,14 @@ the shapes of its answers only partly, and for lessons and the timetable not at work with something like that, but only if you decide in advance exactly who suffers when it changes. -The decision: one directory suffers. `app/providers/petersburg/` is the only place that knows -the words `p_educations[]`, `estimate_type_code` and `X-JWT-Token`. What comes out of it are -this project's models and typed errors. The app does not talk to dnevnik2.petersburgedu.ru at -all and does not know it exists: it asks our server about the timetable, the homework and the -marks. +The decision: one directory suffers. `app/providers/petersburg/` is the only place on the +server that knows the words `p_educations[]`, `estimate_type_code` and `X-JWT-Token`. What +comes out of it are this project's models and typed errors. The app reads nothing from +dnevnik2.petersburgedu.ru: it asks our server about the timetable, the homework and the marks. +It talks to the diary once, to sign in — so that the password goes to the diary and nowhere +else — and that conversation is fenced the same way on the phone: `core/data/.../upstream/` is +the one place that knows the sign-in's routes, and what comes out of it is a session to hand +to our server or a failure with a name. Two asymmetric habits follow from the lack of documentation. On the way in the mapper is lenient: a field is looked for under every name it has appeared under (a room is `office`, @@ -1010,14 +1074,16 @@ client should not have to know that, so a mark in our model has two fields: `val written in the cell («5», «Н», «!»), and `kind`, what it actually is. An absence can be coloured differently from a bad mark without knowing about the code. -The password is not stored — in any form. It is needed for one request, after which the -diary's own session lives on, refreshed from its own answers: the service hands back a fresh -token on almost every call, we overwrite ours with it, and an active session does not die of -age. When it does finally stop being accepted, any request answers 401 with an +The password is not stored — in any form, on the phone or on the server. It is sent to the +diary to sign in, after which the diary's own session lives on, refreshed from its own +answers: the service hands back a fresh token on almost every call, we overwrite ours with +it, and an active session does not die of age. When it does finally stop being accepted, any request answers 401 with an `X-Diary-Reauth: required` header — a request to ask for the password again rather than "the token is wrong": those are different screens. -The price is named honestly: a background sync of the diary does not outlive the session. +The price is named honestly: nothing reads the diary once the session is gone — and the +phone never reads it in the background at all, so a family that stops opening the app is +eventually asked for the password again. Reference implementations solve this by storing the password, so they can silently re-authenticate once a day. Every family's password in a database to save one sign-in screen every few days is a bad bargain, and we do not make it. diff --git a/docs/diaries.md b/docs/diaries.md index ded8b5d5..e29be5e1 100644 --- a/docs/diaries.md +++ b/docs/diaries.md @@ -334,8 +334,11 @@ turned into a file once rather than parsed as prose: `server/app/catalog/data/re **generated** by `python -m scripts.region_catalog` (run from `server/`). The server reads it to place a school found in the company register in a region ([api.md](api.md#which-regions-a-school-is-in-get-apiv1directoryschool-regions)), and the -same file is written for the app to bundle. It is therefore exactly as current as the survey -— September 2026 — and exactly as tested: nothing in it was read from a live diary either. +app bundles the same file in place: on the phone it is the region search, the list of +systems a family chooses from, and the allow-list of every host the phone may send a diary +password to ([architecture.md](architecture.md#the-phones-half)). It is therefore exactly as +current as the survey — September 2026 — and exactly as tested: nothing in it was read from a +live diary either. **Three inputs, each trusted for one thing.** @@ -353,6 +356,38 @@ same file is written for the app to bundle. It is therefore exactly as current a keys are the allow-list's own, byte for byte, because they are already stored in `classes.diary_region`, `diary_sessions.region` and the sealed credential. +**The search lexicon** is the overlay's `[search]` block, copied into the JSON as `search`, +and it is data rather than Kotlin because nearly every entry is Cyrillic. The phone +lower-cases a query and applies `fold` (ё, the dashes), cuts it at punctuation and drops +`stop_words` («область», «край», «республика»…), and tries it three ways besides: through the +keyboard-layout swap (`latin_layout` / `cyrillic_layout`, «cfvfhf» for «самара»), through +`translit` for a Latin query, and through `synonyms`. `school_words` are what make a query a +school's name rather than a place's, for the phone and for the server's directory alike. + +- **`translit`** is `[latin, cyrillic]` pairs, **longest first**, and the generator refuses + any other order, because the phone takes the first pair that matches at each position. The + endings are how English writes the Russian ones — `iya`, `ia`, `iy`, `yy`, `tsk` — so that + «Chuvashia», «Bashkiriya», «Khanty-Mansiysk» and «Yakutsk» come out whole rather than as + «чувашиа» or «якуцк». It is best effort, not a standard. +- **`[search.synonyms]`** is optional: a lower-case Latin word mapped to a non-empty list of + them, the only shape the generator accepts, because the phone compares words after it has + folded case and cut at punctuation and nothing else could ever be typed. A query is also + tried with a word swapped for each of its synonyms, and still as typed: `st` is `saint`, + and `region` is `oblast` or `krai`, which is how «St Petersburg» and «Moscow region» find + their regions. «oblast» is deliberately **not** a stop word the way «область» is: «moscow» + would then tie the region with the city, and a tie goes to the list's order rather than to + the city somebody meant. +- **An English spelling goes into a region's `aliases` only when neither `name_en` nor + `translit` can produce it** — «Zabaikalye» and «Zabaykalye» for Забайкальский край, + «Primorye» for Приморский: no transliteration table brings back a soft sign. `cities` are a + few large towns, so that «Тольятти» finds Самарская. Both are search hints, never shown as + a region's name. + +`test_region_catalog.py` holds the shape — every synonym is a word some `name_en` actually +contains, «oblast» is not a stop word, and the transliteration spells the endings above — and +on the phone `RegionSearchTest` requires fifteen common English spellings, from «St. +Petersburg» to «Khanty-Mansiysk», to land on their region first. + **Never edit the JSON by hand.** A change to a region goes into regions.md or the overlay, and the generator is run again. `server/tests/test_region_catalog.py` runs the generator's `--check` and fails when the committed file is not what the survey, the overlay and the diff --git a/docs/guide.md b/docs/guide.md index 68a5f293..30e16b0b 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -5,19 +5,23 @@ A document for whoever uses the app rather than builds it. Building is in The short version: one person keeps the class's timetable in a Telegram bot, and the app on the phone reads it and shows it — on the screen, in the widget and in the -notifications. Nothing has to be typed in except the class code on first run. +notifications. A family whose class is in no bot can instead sign in to its own school's +electronic diary and have that as the app; a phone can have both. > The app speaks Russian (with an English translation, chosen in the app), so the buttons > and menu paths quoted below are quoted as they appear on the screen. ## First run -An installed app opens not with a field for a code but with five steps: +An installed app opens not with a field for a code but with five steps of introduction: 1. **Welcome** — the app's mark, the theme and the language. The mark spins under a finger; the theme and the language are changed here and are always available in the - settings afterwards. -2. **What this is** — four paragraphs about what the app shows and what it does not do. + settings afterwards. Under its «Продолжить» button there is always the line «Продолжая, + вы принимаете Условия использования и Политику конфиденциальности»: each name opens its + document — in the browser, or offline from the copy inside the app — and both are in + «Настройки → О приложении» later. +2. **What this is** — a few paragraphs about what the app shows and what it does not do. They are worth reading: it is the shortest description of the project there is. Whether to keep crash reports is chosen here too (off by default). 3. **Properties** — haptics, colours from the wallpaper, a black background, blur, the @@ -26,12 +30,37 @@ An installed app opens not with a field for a code but with five steps: 4. **Permissions** — notifications, exact alarms and background work, each with its own button and an explanation of what it is for. Refusing breaks nothing: with no notifications there simply are no reminders. -5. **The class code** — that field. +5. **«Как подключиться?»** — the two ways in, «По коду класса» and «Найти свою школу». + The other one can be added later. The language sits on the first step deliberately: somebody who does not read Russian has to be able to switch it **before** the third screen, not after. Below Android 13 changing the language recreates the screen — that is normal, and the step is not lost. +**«По коду класса»** is the field for the class code, described in the next section. If +the class is linked to a diary the app can sign in to, the app then offers that diary's +sign-in too, and «Не сейчас» skips it. + +**«Найти свою школу»** is for a family that wants its own diary, with or without a class in +the bot. In order, skipping what a region does not need: + +- **the region** — found by the name of the region or a city, its code, or a school's name. + The list of regions is inside the app and searches offline; a school's name is looked up + by the server, when the server has school search switched on; +- **the school** — only where the diary is «Сетевой город»: the phone asks the region's own + diary server for its list of schools; +- **the diary system** — what the region's schools use, one of them marked «Рекомендуем», + with «Почему?» explaining the choice. A diary that opens only through Госуслуги, or one the + app cannot read yet, opens its own site in the browser instead, and the class code is + offered beside it; +- **the sign-in** — the diary's own login and password; the card «Куда уйдёт пароль» names + the address the password goes to (more in "The electronic diary" below); +- **the import** — the pupil, the terms, two weeks of timetable, the homework and the marks, + with a progress bar; several pupils on one account are asked about, and a load that stops + resumes from where it stopped with «Повторить»; +- **«Всё готово»** — a summary of the pupil, the diary, the class if there is one, and the + main settings. + ## The class code The bot hands the code out with `/code` to whoever has administrator rights in the class. @@ -48,11 +77,14 @@ code is correct — that class simply does not let anybody in with it any more. personal code from the bot; there is no need to go back to whoever gave you the class code. -If the school's server is its own rather than the one built into the app, press -**«Сервер»** at the bottom of the connection screen and enter the whole address — -`http://192.168.1.50:8000/` or `https://lessons.example.com/`. The address has to be the -one the **phone** can see the server at: to a phone, `localhost` means itself. The details, -and how to check from a browser, are in [build.md](build.md#pointing-the-app-at-a-server). +**The app has no server of its own**: the address comes from the class's administrator, +or from whoever set a server up for the school. It goes into the **«Адрес сервера»** row +under «Сервер» — on the «Как подключиться?» screen, at the bottom of the class-code screen, +or in «Настройки → Синхронизация» — as a whole address, `http://192.168.1.50:8000/` or +`https://lessons.example.com/`. On the way through the school's diary it is asked for when +it is first needed. The address has to be the one the **phone** can see the server at: to a +phone, `localhost` means itself. The details, and how to check from a browser, are in +[build.md](build.md#pointing-the-app-at-a-server). ### Several classes on one phone @@ -67,7 +99,8 @@ The widget and the notifications follow the selected class. There are two ways out now, and they are different. **«Выйти из класса «7А»»** removes one class and its timetable and leaves the others alone; **«Выйти из всех классов»** removes -them all — after which the app shows the code field again rather than the four screens. +them all — after which the app opens «Как подключиться?» rather than the whole +introduction again, or the diary, if the phone is signed in to one. While there is exactly one class there is one line, and it means what it always did. Editing rights are per class: a phone is linked to Telegram per class rather than as a @@ -90,6 +123,10 @@ The settings are not a fourth tab but a separate button: you go in, change one t come back. Inside are nine sections, each opened on its own: appearance, interaction, content, notifications, sync, class, diary, updates and "about". +A phone with **no class and a diary** has a different home: the diary itself, with its two +tabs, «Расписание» and «Оценки», in the toolbar. Its settings keep six sections — no +content, notifications or class, because each of those is about a class timetable. + ## The widget The point of the whole thing. The widget answers one question — "what now?" — and when the @@ -115,8 +152,11 @@ Worth knowing: - **After lessons it shows the homework** — for tomorrow, on Friday for Monday, and across the holidays for the first school day after them. -If the widget says «нет данных», open the app: there is nothing in the cache for that date -and no sync has happened yet. +If the widget says «Расписание ещё не загружено», open the app and pull the screen down: +there is nothing in the cache for that date. On a phone with no class it asks to be opened +and connected instead, and on a phone that has only a diary it says «Дневник — в +приложении»: the widget draws a class timetable and never the diary. The three sentences are +in [widget.md](widget.md#when-there-is-nothing-to-draw). ## Notifications @@ -232,23 +272,44 @@ Editors and administrators additionally have `/subjects`, `/holidays`, `/bells`, `/devices`, `/log`, `/class`, `/export`, `/import`, `/stats` and `/code` — all described in [bot.md](bot.md). -## The Petersburg electronic diary +## The electronic diary + +A separate thing and a separate account: the class's timetable is kept by the bot, while the +diary is the system the school keeps its marks, absences and assignments in. The app signs in +to two of them: St Petersburg's «Петербургское образование», and «Сетевой город» in the +sixteen regions where it takes a login and a password. A diary that lets people in only +through Госуслуги, the app does not sign in to — which diary each region runs is in +[diaries.md](diaries.md). -A separate thing and a separate account: the class's timetable is kept by the bot, while -the diary is St Petersburg's state service, holding the marks, the absences and the -assignments the school sets. In the app it is the **«Настройки → Дневник»** section. +Where it lives depends on the way in. On a phone with a class it is the **«Настройки → +Дневник»** section; on a phone with only a diary it is the home screen, and its account — +the pupil, the diary, the school, «Подключиться к классу по коду» and «Выйти из дневника» — +is under «Настройки → Дневник». -You sign in with the same login and password as on the diary's website. **The password is -not saved anywhere**: it is needed for exactly one request, after which both the phone and -the server forget it. Only the diary's own session is stored, and it lives as long as the -service keeps extending it. When it ends, the app says «Сессия дневника закончилась» and -asks for the password again — the login stays where it was. +You sign in with the same login and password as on the diary's website, and the form names +the address the password will go to. **The password goes from the phone straight to the +diary, over HTTPS, and nowhere else** — not to the server and not to the phone's storage. The +server receives the session the diary handed back, checks it with a request of its own, and +keeps it sealed. When it ends, the app says «Сессия дневника закончилась» and asks for the +password again — the login stays where it was. A failed sign-in says why: a wrong pair, a +diary that is not answering, too many attempts, a diary that will not accept the server's +address, no connection — different things, with different fixes. + +The bot's own diary sign-in page works differently: there the password goes through the +server once on its way to the diary, and the page says so ([bot.md](bot.md)). Inside are two tabs — «Расписание» and «Оценки» — and a choice of child, if the account sees several. The diary's assignments are shown under the lessons of the day they are set for. An absence, a late arrival and a remark are all put into one list with the marks by the service, but the app tells them apart and shows them differently. +What the app has loaded stays on the phone, so the diary opens without a network — the app +then says it is showing the saved copy, and from when. The app reads the diary only while +it is open: the widget and the background sync never do. That is also what keeps the +sign-in alive — after 30 days without the app being opened you sign in again, and +Petersburg's diary may end a sign-in sooner. «Выйти из дневника» deletes what the phone +saved and has the server forget its copy of the sign-in. + The service is somebody else's and undocumented. If it answers incomprehensibly, the app says exactly that: the service has changed, and that is fixed on the server rather than in the app. @@ -290,7 +351,7 @@ A manual check in the same place also shows the notes for the version already in | What you see | What it means | | --- | --- | -| The widget says «нет данных» | there is no cache for that date — open the app and let it sync | +| The widget says «Расписание ещё не загружено» | there is no cache for that date — open the app and pull the screen down | | The time in the app is wrong | "now" is computed in the class's time zone; an administrator changes it in the bot, «⚙️ Класс → 🕒 Часовой пояс» | | Notifications do not arrive | the first line of the «Уведомления» section says whether they are forbidden at the system level; check the quiet hours and "no reminders during the holidays" | | The code does not connect | check the server address under «Синхронизация» and open `
/api/v1/health` in the phone's browser | diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index 0faa8f23..74b1fbe5 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -58,7 +58,7 @@ When a phone joins a class, the server keeps: When you sign in to a diary, the server keeps: - the diary session — **encrypted** with the operator's key; for Setevoy Gorod, the region, the school's number and name and the school year's details are sealed inside with it; -- your login — as you typed it, in plain text; in Petersburg Education that is an email address; +- your login — in plain text, as you typed it, minus spaces at its ends and characters that print nothing; in Petersburg Education that is an email address; - which diary and region it is, when the session was opened, when it was last used, when the server last kept it open and when the diary stopped accepting it; - the diary access key issued to the phone — only as a SHA-256 hash. diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index 55e1a72c..2dab46fd 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -79,7 +79,7 @@ Когда вы входите в дневник, сервер сохраняет: - сессию дневника — **зашифрованной** ключом оператора; у «Сетевого города» вместе с ней внутри шифра лежат регион, номер и название школы и сведения об учебном годе; -- ваш логин — так, как вы его ввели, открытым текстом; в «Петербургском образовании» это адрес электронной почты; +- ваш логин — открытым текстом, так, как вы его ввели, без пробелов по краям и непечатаемых символов; в «Петербургском образовании» это адрес электронной почты; - какой это дневник и регион, когда сессию открыли, когда ею последний раз пользовались, когда сервер её поддерживал и когда дневник перестал её принимать; - ключ доступа к дневнику, выданный телефону, — только в виде хеша SHA-256. diff --git a/docs/widget.md b/docs/widget.md index ce079a4f..7ccf04ea 100644 --- a/docs/widget.md +++ b/docs/widget.md @@ -82,7 +82,7 @@ from `timetable.nowAtSchool()`. | `DuringEvent` | canteen, assembly, excursion | the event's name and how long is left | | `AfterSchool` | after the last bell | **homework for the next school day** | | `DayOff` | day off, holidays | the same | -| `NoData` | no cache for this date | a hint to open the app | +| `NoData` | no cache for this date | one of three sentences, by how the phone came in — see below | The priority when they overlap: an event with `coversLesson` beats a running lesson; an event without it is shown only during a break. That is why «Обед» is visible on a break but @@ -91,6 +91,40 @@ does not hide a lesson. The homework heading names the day the way a person would: «на завтра», «на понедельник», «на 15 сентября» — depending on how far away it is. +### When there is nothing to draw + +With no timetable — no class, nothing cached, or `NoData` — the widget draws an instruction +rather than an error, and which instruction depends on how the phone came into the app. The +snapshot carries the phone's `ShellMode`, read from `container.shellMode.current()`: one +preferences read, and the same rule the app shell uses to choose its home. + +| Mode | Wide rungs | Narrow rungs and `WIDE` | +| --- | --- | --- | +| no class, no diary | «Откройте приложение и подключитесь по коду класса или через свою школу» | «Откройте приложение» | +| a class, nothing synced | «Расписание ещё не загружено — откройте приложение и потяните вниз» | «Расписание не загружено» | +| a diary and no class | «Виджет показывает расписание класса. Дневник — в приложении» | «Дневник — в приложении» | + +The first used to be «введите код класса», which is wrong for exactly the family the second +way in was built for, and it now names both ways. The third is new, and deliberately does +not say «потяните вниз»: no pull will ever bring a timetable to a phone that has no class. +A snapshot that cannot be read at all draws the class sentence, the least wrong of the three +when nothing is known. Which rungs get the short form is a width rule, `emptyTextIsCompact`, +because Glance text cannot ellipsize and a long sentence in a 110 dp column is clipped +mid-word. + +**The widget never reads the diary** (#142). Outside a class it does not even ask Room for a +timetable, and `snapshotOf` ignores one handed to it, so the sentence and anything drawn +beside it come from one answer. A diary read from the widget would count as the family's +activity and keep a diary session alive on the server with nobody behind it; +`SyncWorkerSourceTest` fails if any widget source names the diary's repository, cache or +import. A diary-only phone therefore gets no widget content at all, and that is recorded as +the open question it is rather than patched here. + +The widget learns that the mode changed the way it learns of a sync: registering a diary +session and signing out of one send the same `DATA_SYNCED` broadcast. None of this has been +seen on a launcher — whether the longer first sentence fits its rungs is judged by its +length, and the redraw on a mode change is not composed by any test. + ## The school's time, not the phone's A timetable is stored as the school's wall clock. The widget takes "now" through From 8bad211123501ac993c8ffeeec836f6da3e4ada4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:23:05 +0000 Subject: [PATCH 22/30] Stop the contributor and agent documents quoting a test command, counts, secret names and milestones that are no longer true MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five documents people and agents read before touching the repository had drifted (#160), each checked by hand against the tree: - CONTRIBUTING.md recommended `python -m pytest -q` for «1634» server tests. The `-m` form is the one CLAUDE.md warns against — it puts the current directory on sys.path, so a cross-test import passes locally and fails at collection on CI — and the count was stale; so was mypy's «84 modules». It now gives `pytest -q -n auto`, 1944 tests and 100 modules. - The release skill said apk.yml needs «four LESSONS_KEYSTORE_* secrets». The secrets are KEYSTORE_BASE64, KEYSTORE_PASSWORD, KEY_ALIAS and KEY_PASSWORD; LESSONS_KEYSTORE_* are the names Gradle reads them under. An agent following the skill would have set secrets the workflow never reads. - docs/architecture.md gave :core:model 117 tests; it has 125. - AGENTS.md said «there are no issues here»; there have been since #128, and a defect gets one before its fix. - The milestone facts: the owner renamed all nine milestones and created the tenth on 25 September. The github-pr skill's table now carries the ten real titles with the pull requests and issues each holds (it still said milestone 6 was «#60–#62 — the version being worked on» and milestone 9 held only #109–#117); CLAUDE.md names the two open version milestones instead of «the ninth … the current one»; the release skill's example tag uses the new v0.8.0 title. The skill tells sessions to read a milestone's number back by searching its exact title, so a stale title there was a search that finds nothing. HANDOVER.md still quotes the old titles in its batch history; the close-out of this batch rewrites its milestone table. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/skills/github-pr/SKILL.md | 27 +++++++++++++++++---------- .claude/skills/release/SKILL.md | 10 ++++++---- AGENTS.md | 7 ++++--- CLAUDE.md | 11 +++++++---- CONTRIBUTING.md | 4 ++-- docs/architecture.md | 2 +- 6 files changed, 37 insertions(+), 24 deletions(-) diff --git a/.claude/skills/github-pr/SKILL.md b/.claude/skills/github-pr/SKILL.md index 6f0606b4..f7260b9f 100644 --- a/.claude/skills/github-pr/SKILL.md +++ b/.claude/skills/github-pr/SKILL.md @@ -69,18 +69,25 @@ matched pull request's body in full. | # | Title | Covers | | --- | --- | --- | -| 1 | `v0.1.0 — First run on a phone` | #1–#14 | -| 2 | `v0.2.0 — The diary, and the class run from the bot` | #15–#17, #28–#31 | -| 3 | `v0.3.0 — The school year` | #27, #32–#35, #43 | -| 4 | `v0.4.0 — Nothing breaks in silence` | #44, #45, #50 | -| 5 | `v0.5.0 — A public repository` | #46–#49, #51, #55–#57, #59 | -| 6 | `v0.6.0 — One container, and nothing cut off` | #60–#62 — the version being worked on | -| 7 | `Dependencies` | every dependabot bump; deliberately not a version | -| 8 | `v0.7.0 — Оптимизация` | #75–#85, #128 — the one Russian title | -| 9 | `v0.8.0 — On a device` | issues #109–#117 — **the current one**, and the first whose work needs an emulator or a phone | +| 1 | `v0.1.0 — App, widget, admin bot and read API` | PRs #1–#14; issues #86, #88, #89 | +| 2 | `v0.2.0 — Petersburg e-diary, class run from bot and phone` | PRs #15–#17, #28–#31; issues #87, #90, #91, #102 | +| 3 | `v0.3.0 — School year, terms, school search, several classes` | PRs #27, #32–#35, #43; issue #92 | +| 4 | `v0.4.0 — 67-defect sweep, first audit, app-wide correction mode` | PRs #44, #45, #50; issues #93, #94 | +| 5 | `v0.5.0 — Public repo: secrets audit, English docs, font licence` | PRs #46–#49, #51, #55–#57, #59; issue #95 | +| 6 | `v0.6.0 — Dishka DI, scrolling text, in-app guide from the repo` | PRs #60–#74; issues #96, #97, #99, #101, #103, #104 | +| 7 | `Dependencies — dependabot bumps` | every dependabot bump; deliberately not a version, and open for good | +| 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | PRs #75–#85, #128; issues #98, #100, #105–#108 | +| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | PRs #129, #133, #134; issues #109–#117, #130–#132 — **open**, the first whose work needs an emulator or a phone | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | PR #140; issues #135–#139, #141, #145–#160 — **open**, the one being worked on | + +All ten were renamed on 25 September 2026: every title now names what the version +delivered, and each description names its pull requests and issues. A title quoted from +before that date — «On a device», «Оптимизация», «Nothing breaks in silence» — finds +nothing when searched, so take titles from this table or from a milestone object, never +from an old commit message. New work goes in the newest version milestone unless it plainly opens the next one; a -dependabot bump goes in `Dependencies` whatever else is in flight. +dependabot bump goes in milestone 7, `Dependencies — dependabot bumps`, whatever else is in flight. They are **retrospective**. The boundaries were read off the history in September 2026 rather than declared at the time, and **nothing in this repository has ever been tagged or diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 5b471290..2c3bd2e9 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -22,8 +22,9 @@ names both revisions. ## 3. Signing -`apk.yml` needs all four `LESSONS_KEYSTORE_*` secrets and fails with `::error::` if any is -empty. That failure is the feature: an APK signed with the AGP debug key can never be updated +`apk.yml` needs all four signing secrets — `KEYSTORE_BASE64`, `KEYSTORE_PASSWORD`, `KEY_ALIAS` +and `KEY_PASSWORD` — and fails with `::error::` if any is empty. (`LESSONS_KEYSTORE_*` are +the names the Gradle build reads them under, not the names of the secrets.) That failure is the feature: an APK signed with the AGP debug key can never be updated by the real key on a phone that already installed it. The keystore and its passwords come from environment variables or `~/.gradle/gradle.properties` — never from the repository, where `*.jks` and `keystore.properties` are gitignored. @@ -31,7 +32,8 @@ where `*.jks` and `keystore.properties` are gitignored. ## 4. The milestone closes before the tag is cut **The milestone is what decides what is in the release**, so it is settled first and the -tag is the version it is named for — `v0.8.0 — On a device` is tagged `v0.8.0`. +tag is the version it is named for — `v0.8.0 — On-device checks, 89-region e-diary survey` +is tagged `v0.8.0`. Before tagging, walk the milestone and check three things: @@ -52,7 +54,7 @@ Then tag. A `v*` tag makes `apk.yml` build an installable APK **and** create a G release with it attached, so the tag is the moment the notes have to be ready. ```bash -git tag -a v0.8.0 -m 'On a device' +git tag -a v0.8.0 -m 'On-device checks, 89-region e-diary survey' git push origin v0.8.0 ``` diff --git a/AGENTS.md b/AGENTS.md index 9067d91a..15ca8b06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,9 +67,10 @@ CI is exactly: ruff, pytest `-n auto`, `./gradlew test`, both assembles. `./grad survive review. - Commit messages are English sentences saying what the change makes the project do. No Conventional Commits prefix — none of this history has one. -- Every pull request carries a milestone, set when it is opened — there are no issues here, - so they are the only grouping the history has. No session can create one: when none fits, - ask the owner, with the title and description written out. See `.claude/skills/github-pr/`. +- Every pull request carries a milestone, set when it is opened, and so does every issue. A + defect gets an issue before it gets a fix, and the pull request says `Closes #NN`. No + session can create a milestone: when none fits, ask the owner, with the title and + description written out. See `.claude/skills/github-pr/`. - Versions are copied from a project that builds, never guessed. - **Say what is not covered.** "Written, never run" is a legitimate status; a claim that something was verified when it was not is not. diff --git a/CLAUDE.md b/CLAUDE.md index f7fe6b10..0e5b12de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -216,12 +216,15 @@ points Hilt does not inject cleanly. names what is left uncovered. Unlike the owner's other repositories, this history does carry a `Co-Authored-By: Claude …` trailer; keep doing what the history does. - **Every pull request carries a milestone**, set when it is opened. Nothing in a session - here can create a milestone or even list one — when none of the nine fits, ask the owner + here can create a milestone or even list one — when none of the ten fits, ask the owner to create it and hand over the title and description already written, rather than inventing a version or leaving the pull request bare. The `github-pr` skill has the - numbers, the one tool that sets them, and the two ways this was got wrong first. **The - ninth is `v0.8.0 — On a device` and it is the current one**; issues #109–#117 are on it, - and it is the first milestone whose work needs an emulator or a phone. + numbers, the one tool that sets them, and the two ways this was got wrong first. **Two + version milestones are open:** the ninth, `v0.8.0 — On-device checks, 89-region e-diary + survey`, holds issues #109–#117, the first work that needs an emulator or a phone; the + tenth, `v0.9.0 — NetSchool e-diary, onboarding via the school's diary`, holds PR #140 and + its issues. All ten were renamed on 25 September 2026, so a title quoted from before then + finds nothing when searched. - **A defect that is found gets an issue, always, and before it gets a fix.** The rule is new and it is not optional: the moment an audit, a review, a CI failure or a reader finds something wrong, it becomes an issue of its own — title saying what is broken rather than diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c4fcc0a..04bec2ac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,8 +36,8 @@ cp .env.example .env # BOT_TOKEN and OWNER_IDS are your own | Command | What it does | | --- | --- | | `ruff check app tests scripts migrations` | lints the server — exactly what CI runs | -| `python -m mypy` | one question of all 84 modules: does anything reach for an attribute its type does not have? | -| `python -m pytest -q` | the server tests; 1634 of them, about five minutes, or a third of that with `-n auto` | +| `python -m mypy` | one question of all 100 modules: does anything reach for an attribute its type does not have? | +| `pytest -q -n auto` | the server tests, 1944 of them, in about two minutes — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | | `python -m pytest -q tests/test_schedule.py -k parity` | one file, one test | | `python -m uvicorn app.main:app --reload` | run the server | | `alembic upgrade head` | apply the migrations (with a working `DATABASE_URL`) | diff --git a/docs/architecture.md b/docs/architecture.md index 621544fb..585d8fcb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -124,7 +124,7 @@ Five Gradle modules, split along the lines that actually pay for themselves: `:core:model` being a plain JVM library is the load-bearing decision: the state engine is the most logic-dense part of the product, and this makes its test suite -run in milliseconds with no emulator and no Android SDK. Its 117 tests, in ten +run in milliseconds with no emulator and no Android SDK. Its 125 tests, in ten classes, walk a full school day minute by minute. The widget module exists so the home-screen widget can reach the cached timetable From 2ea98f5b01ad86ec265f76f51934ef7145c838de Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 21:42:05 +0000 Subject: [PATCH 23/30] Close out the batch in HANDOVER while its pull request is still open MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HANDOVER.md now describes PR #140 as it stands: both batches on it (the server-side «Сетевой город» provider, #135–#139, and the first run through the family's own school's diary, #141), the defects filed and fixed on the way (#145–#160) with the commits that fixed each, the ten milestones under the titles the owner gave them on 25 September, head 0016 with production read at 0014, the test counts (server 1944, Android 1371), what was deliberately left alone (#142–#144) and what nothing has verified — no live diary, no device, the replay from Frankfurt, DaData's fields and day boundary, a lawyer's read of the legal texts. The batch chain is repaired: eight sections that still said «Open as PR #NN» name their merge commits, and the false «There is no number 7» is gone. Two things are still to be written into it before the merge: the outcome of applying 0015 and 0016, and whatever the audit and review now running turn up. The merge SHA of this pull request is the next batch's to record. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- HANDOVER.md | 775 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 539 insertions(+), 236 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index 7091cd35..c1774337 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -4,84 +4,85 @@ A working document, not part of the reference set in `docs/`. It describes **the the moment of handover**, so that a new session — human or agent — continues from the same place without reopening or redoing anything. -Last updated: **24 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are +Last updated: **25 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are merged**; `main` is at `fa4fe0c`, the merge of #134. `dev` is still at `a43c6e8`, the merge -of #129, because #133 and #134 each went in from a branch of their own. It is behind `main` -and has nothing `main` lacks, so bringing it level is a fast-forward. **The only thing open -is the pull request carrying this paragraph, #140**, a **draft** from -`claude/school-diary-api-routes-cc4o1n`. It closes #136, #137, #138 and the feature epic -#139. It **cannot merge yet**: the owner chose a new — tenth — milestone for it, e.g. -«v0.9.0 — A second diary», and nothing in a session here can create a milestone, so it stays -a draft with **no milestone** until the owner makes it. The SHA of its own merge is for the -next close-out to write. - -**Code moves again, after four documentation-only batches.** #128, #129, #133 and #134 -changed documentation and agent configuration only, so «nothing in the code has moved since -#85» stood through all of them. #140 ends that: it adds a second electronic diary, «Сетевой -город» (ИРТех NetSchool), behind a provider-neutral seam under `server/app/providers/diary/`, -and Петербург goes behind the same seam byte-for-byte unchanged. Two new provider packages -joined and server files across the api, bot, services and models changed, so the server gates -were **run**, not quoted (below), and a migration was written (`0015`) that is **not yet -applied**. The Android app was **not** touched — it stays Petersburg-only until batch 2, the -owner's «server first» decision. - -**Once #140 merges, four issues close (#136–#139) and twenty stay open.** **#109** is the -epic and **#110–#117** are its children on `v0.8.0 — On a device`. **#118–#122** are the -owner's alone, and #123–#127 are `status:someday`. **#135** — the owner's decision about -which diary comes second, how a family signs in, and whether ТОР may be used — **stays -open**: this batch answers its first part (it is «Сетевой город», and it takes a password) -but leaves the Госуслуги and ТОР questions to the owner. #136, #137 and #138 are the three -diary defects this batch fixed, and #139 is the feature epic it delivers. +of #129, because #133 and #134 each went in from a branch of their own, and #140 is on one +too. It is behind `main` and has nothing `main` lacks, so bringing it level is a +fast-forward. **The only thing open is the pull request carrying this paragraph, #140**, from +`claude/school-diary-api-routes-cc4o1n`, on milestone 10, +`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`. It is no longer a draft: +the owner created that milestone on 25 September and renamed the other nine the same day +(the table, with what each was called before, is under «And before that: nothing on a +screen is cut off»). What stands between it and the merge is the `github-pr` skill's +checklist — CI green on the exact head, and the findings of the review of its code fixed on +the branch — and `0015` and `0016` on the production database, below. The SHA of its own merge +is for the next close-out to write. + +**Code moved on both halves, and the schema with it.** #140 carries two batches. The first +(#139, `4c34cb5` to `42fdf0a`) reads a second electronic diary, «Сетевой город» (ИРТех +NetSchool), on the server, behind a provider-neutral seam that Петербург went behind +unchanged. The second (#141, from `17c0473`) is the owner's request of 25 September: a first +run with two ways in — the class code, or the family's own school's diary — on which the +password goes from the phone to the diary and never to this server, and a phone that reads +only its diary gets a home of its own. Both halves' gates were run rather than quoted: +server **1944** tests, Android **1371**. + +**Once #140 merges, twenty issues are meant to close and twenty-four stay open.** Meant to +close: #136–#139, #141, #145–#155 and #157–#160. Staying open: **#156**, whose fix is in +`ce9c749` but which waits for a phone's backup to be read (`needs:device`); **#135**, the +owner's decision about the second diary, which the code has now answered but which is theirs +to close; **#142**, **#143** and **#144**, this batch's deliberate follow-ups, on no +milestone; **#109–#117**, the device epic and its children on milestone 9; **#118–#122**, +the owner's alone; and #123–#127, `status:someday`. What a merge closes is decided by the +`Closes` lines in the pull request body and in the commit messages, not by this paragraph — +read them against this list before merging. + +**The code expects head `0016`; production was read on 25 September at `0014`.** +`EXPECTED_REVISION` in `app/db.py` is `0016`, pinned to the real head by +`tests/test_schema_version.py`. `0015` adds the eight nullable columns the second diary +needs, and `0016` creates `usage_counters`, the anonymous school directory's daily count of +DaData requests. Both are additive and destroy nothing, so both go on through the Neon +connector (the project named `lessons`) **before** the merge; «Schema» in the section on #140 +below says when they did and what the database said. The `0014` chapter still holds: #83's +pinned table of the enum column widths fails when a `SAEnum` member's **name** outgrows its +`VARCHAR`, which SQLite cannot see and production Postgres finds at the moment somebody marks +a day. + +Production was read after #60 and again after #61, rather than assumed: `/api/v1/warmup` — +which opens a real connection, so it answers for the database as well as the code — +answered `{"status":"ok","api_version":1,"schema":"0013"}`. **It has not been re-read since, +and #83 found out why.** The deployments sit behind Vercel's Deployment Protection and +answer a redirect to a login page, so `/api/v1/warmup` cannot be read from a session here at +all. It still wants reading, by the owner's browser or with a bypass token (#119). Once #140 +has merged and deployed it should answer `"schema":"0016"`; in the window between the +migrations and the merge it answers `degraded` with «База впереди кода…», which is the +window the correct order creates rather than a fault. That single line is the cheapest check +that the migrations and the code actually met. **Two things changed about how this project is tracked, and they are the reason to read on before planning anything.** -**The work moves to a local machine.** Everything up to #85 was built in a cloud session -with no emulator, no `adb` and no device. The section «Where the work happens from here» -below says what that unlocks and what it still cannot do; **#109** is the epic. +**The work moves to a local machine.** Everything up to #85 was built with no emulator, no +`adb` and no device, and so were #133, #134 and #140. The section «Where the work happens +from here» below says what that unlocks and what it still cannot do; **#109** is the epic. +#140 is the first batch since that decision to change screens, so nearly everything it adds +to section 5 is a question a device answers. **The repository has issues now, and until #128 it had none at all.** Before that, the milestones were the only grouping the history had. Forty-two issues were opened in one go: **#86–#108**, closed, for what was built and what each bug sweep found, and **#109–#127**, open, for the whole of what was left. Several of the open ones record a decision *not* to do something, so that a later session does not re-discover it as an oversight. From #129 on, a -found defect becomes an issue before it becomes a fix. #131 and #132 are the first two filed -under that rule. - -**The code now expects head `0015`; the production database is still at `0014`, and `0015` -has not been applied.** `EXPECTED_REVISION` in `app/db.py` moved to `0015` (revision -`0015_diary_provider_columns`, pinned to the real head by `tests/test_schema_version.py`). -It is **additive** — five nullable columns on `diary_sessions` (`provider`, `region`, -`kept_alive_at`, `keepalive_attempted_at`, `upstream_ok_at`) and three on `classes` -(`diary_region`, `diary_school_id`, `diary_school_name`), a `NULL` provider meaning -Петербург — so like every additive revision in this chain it is applied to Neon **before** -the merge. **This is the outstanding pre-merge action:** apply `0015` through the Neon -connector (the project named `lessons`, read the name rather than guessing an id) before -#140 merges; it destroys nothing. The server gates were run rather than quoted: `ruff` -clean, `pytest -q -n auto` **1668 passed** (was 1634), `python -m mypy` clean across 97 -modules (`files = ["app"]`, 84 before the two new provider packages). The `0014` chapter -still holds: #83's pinned table of the ten enum column widths fails when a `SAEnum` member's -**name** outgrows its `VARCHAR`, which SQLite cannot see and production Postgres finds at the -moment somebody marks a day. - -Production was read after #60 and again after #61, rather than assumed: `/api/v1/health` -answered `{"status":"ok","api_version":1}` and `/api/v1/warmup` — which opens a real -connection, so it answers for the database as well as the code — answered -`{"status":"ok","api_version":1,"schema":"0013"}`. **It has not been re-read since, and #83 -found out why.** The deployments sit behind Vercel's Deployment Protection and answer a -redirect to a login page, so `/api/v1/warmup` cannot be read from a session here at all — -this is not an omission anybody can close with one more `curl`. It still wants reading, by -the owner's browser or with a bypass token: #77 moved server code and the schema together, -so the answer should read `"schema":"0014"` today — and `"schema":"0015"` once #140's -migration is applied and its code deployed — and that single line is the cheapest check that -the migration and the code actually met. It is outstanding since #61. +found defect becomes an issue before it becomes a fix: #131 and #132 were the first two +filed under that rule, and #140's branch filed #136–#138 and #145–#160. ## Where the work happens from here: a local machine **#128 was meant to be the last batch built in a cloud session, and the change is one of venue rather than of direction.** #133 and #134 were still written from one, because neither -needs a device. Everything up to and including #85 was made with no emulator, no `adb` -and no device. That is what produced a project with 968 Android tests, 1634 server tests — +needs a device, and #140 was written without one too, although its screens want one most. +Everything up to and including #85 was made with no emulator, no `adb` and no device. That +is what produced a project with 968 Android tests, 1634 server tests — and a section 5 of this document that has only ever grown, because the things in it are not things a JVM test can be asked. @@ -123,21 +124,35 @@ section describes, **#118–#122** are the owner's alone, and **#126** collects things carried deliberately, so that a later session does not re-discover a decision as if it were an oversight. +**Twenty-eight have been filed since.** #130 was the survey #134 closed, and #131 and #132 +the two defects #133 closed. #135 is the owner's decision about the second diary; #136–#139 +and #141 are the work #140 carries; #142–#144 are its deliberate follow-ups, on no +milestone; and #145–#160 are the defects found on its branch, each filed before its fix. + Labels are `type:` (feature, bug, chore, research, decision, epic), `area:`, `status:` (now, next, someday, done) and `needs:` (device, owner). **A session cannot create a GitHub Project board** — Projects v2 is GraphQL-only and the toolset here is REST — so the board is the owner's to make, and these labels are what its views filter on. -## What the last session added: a second electronic diary, «Сетевой город», behind a provider-neutral seam +## What the last session added: «Сетевой город» on the server, and a way in through your own school's diary + +Open as PR #140, from `claude/school-diary-api-routes-cc4o1n`, on milestone 10 +(`v0.9.0 — NetSchool e-diary, onboarding via the school's diary`). Twenty-two commits on +`fa4fe0c` when this was written, `4c34cb5` to `8bad211`, then the fixes of the review that +was running on the branch and this close-out. It is two batches on one branch, and both +halves of the project moved. -Open as the **draft** PR #140, from `claude/school-diary-api-routes-cc4o1n`, closing #136, -#137, #138 and #139. It **has no milestone yet** and cannot merge until the owner creates one -(e.g. «v0.9.0 — A second diary»). Seven commits on `fa4fe0c`, `4c34cb5` through `9ceef0c`; -the server gates were run, not quoted. **The Android app was not touched.** +The second part was planned in design documents and a decision record that stayed in the +session's scratch space, as #134's generator did. What they settled is in the commit bodies, +in #141 and in `docs/architecture.md`, so nothing needs them; but a session that goes looking +for a design document in the repository will not find one. -The project read one diary, Петербург's, wired straight into `services/diary.py` and -`/diary/signin`. This batch puts a seam between the service and the provider, adds a second -provider behind it, and reads either from the same bot and API. +### Part one: «Сетевой город» on the server (#139) + +Seven commits, `4c34cb5` to `9ceef0c`, and their documentation, `42fdf0a`. The project read +one diary, Петербург's, wired straight into `services/diary.py` and `/diary/signin`. This +part puts a seam between the service and the provider, adds a second provider behind it, and +reads either from the same bot and API. - **A provider-neutral diary seam** lives under `server/app/providers/diary/`: the shared models, a `DiaryError` family (`PetersburgError` re-exported as an alias so nothing that @@ -149,62 +164,205 @@ provider behind it, and reads either from the same bot and API. only origins ever contacted — the SSRF guard), windows-1251 salted-MD5 password sign-in, the weekly diary mapped onto the existing models (homework is assignment type 3), keep-alive, and school search for binding. -- **The service dispatches by provider.** `POST /api/v1/diary/login` now accepts optional - `provider` / `region` / `school_id` (for the phone's future batch), and - `services/diary_keepalive.py` keeps every live session alive from `GET /api/v1/cron/tick` - with `GET /webapi/context`, within a batch cap and a time budget, never touching - `last_used_at`. `TickOut` gained `diary_sessions_kept_alive`, `diary_sessions_lost` and - `diary_keepalive_failed`. +- **The service dispatches by provider.** `POST /api/v1/diary/login` accepts optional + `provider` / `region` / `school_id`, and `services/diary_keepalive.py` keeps every live + «Сетевой город» session alive from `GET /api/v1/cron/tick` with `GET /webapi/context`, + within a batch cap and a time budget, never touching `last_used_at`. `TickOut` gained + `diary_sessions_kept_alive`, `diary_sessions_lost` and `diary_keepalive_failed`. - **The bot binds and reads either diary.** An admin binds a class to «Сетевой город» through a provider chooser → region → school-name search; the read path (`bot/handlers/diary.py`) - is provider-neutral — the sign-in card names the bound diary in the genitive, and a session - is keyed on the class's current provider. -- **Three diary defects fixed (#136, #137, #138).** #136: revoking a member now drops their - diary sessions and links, not just invites and subscriptions, so a revoked member no longer - holds a live credential for thirty days. #137: `/diary/signin` re-checks the class binding - at submit and refuses **before** spending the ticket if the diary was unbound or rebound - after the ticket was issued. #138: four false diary comments corrected and two dead type - names removed. + is provider-neutral, and the sign-in card names the bound diary in the genitive. +- **Three diary defects fixed (#136, #137, #138).** Revoking a member drops their diary + sessions and links, not just invites and subscriptions; `/diary/signin` re-checks the + class binding at submit and refuses **before** spending the ticket if the diary was unbound + or rebound after the ticket was issued; four false diary comments corrected and two dead + type names removed. + +Its gates at `9ceef0c`, a record of that commit: `pytest -q -n auto` 1668, `python -m mypy` +clean across 97 modules; Android was not touched. + +### Part two: a way in through your own school's diary (#141) + +Fourteen commits, `17c0473` to `8bad211`: four on the server, five on the phone, one for CI +and four of documents. + +- **The first run has two ways in.** After «Продолжить», the introduction and the + permissions, a family picks the class code, as before, or its own school's diary: the + region — all 89, found on every keystroke in Russian or English, by nickname, city, code, + the wrong keyboard layout or transliteration, or by typing a school's name — then the + school, searched on the region's own «Сетевой город» server, then the region's systems + with the recommended one highlighted and «Почему?» beside it, then the sign-in, then the + import under a wavy progress bar, then a summary. The path is a saved list of steps, + `OnboardingFlow`, in `android/app/.../ui/onboarding/`. +- **On that path the password never reaches our server.** The phone signs in to Петербург or + «Сетевой город» itself — over https, only to an origin in the bundled catalog, with no + redirects and no cookie jar (`core/data/.../upstream/`) — and hands the session to + `POST /api/v1/diary/session`, which reads once with it from its own address, seals it with + Fernet and answers with our diary bearer. A `password` key in that body is a `422`. The app + no longer calls `POST /api/v1/diary/login`; the endpoint stays for older APKs, and + `docs/api.md` and the bot's `/diary/signin` page now say plainly that on those two routes + the password passes through this server. +- **The phone knows what the server can do before a password is typed** + (`GET /api/v1/diary/capabilities`), every diary `503` says why in `X-Diary-Unavailable` + (`disabled`, `address-refused`, `upstream`), and a session the diary refuses from our + address is a `409` rather than `/login`'s `401`, because asking for the password again + would loop. `JoinResponse.diary` hands a joining phone its class's binding. +- **A phone that reads only its diary has a home of its own.** `ShellMode` is none, class or + diary: a phone in no class with a diary session opens on the diary, whose settings keep + «Дневник» and «Выйти из дневника» (#151), and periodic class sync is armed only in class + mode (#152). Every diary failure has its own words through `DiarySignInProblem` and + `DiaryProblemText` (#153). +- **The phone keeps what it reads.** `diary.db` is a second Room database, written only by + successful reads; `DiaryImport` fetches pupils, terms, timetable, homework and marks with + weighted progress and resumes from the phase that failed. The one unprompted read is a + refresh when the app comes to the foreground and the copy is older than 30 minutes; + `SyncWorkerSourceTest` fails if the worker or the widget ever names the diary. +- **The widget says which way in a phone took**: a diary-only phone is told «Дневник — в + приложении» rather than asked for a class code, and a phone with neither is offered both + ways. +- **The terms and the privacy policy exist and are linked.** «Продолжая, вы принимаете + Условия использования и Политику конфиденциальности» is always drawn under «Продолжить»; + `docs/legal/{terms,privacy}.{ru,en}.md` and `legal.json` are bundled in the APK, opened in + the browser when online and from the bundle otherwise, and also from «О приложении». + `LESSONS_LEGAL_BASE_URL` / `lessons.legal.baseUrl` becomes `BuildConfig.LEGAL_BASE_URL`, + https only, one per fork; `apk.yml` derives it from the repository it runs in unless the + repository variable of that name overrides it. +- **A catalog of all 89 regions** — `server/app/catalog/data/regions.json`, generated by + `scripts/region_catalog.py` from `docs/diaries/regions.md` and a hand overlay + (`scripts/region_catalog.toml`): each region's systems, which one is recommended and the + reason codes for it, and the allow-list's «Сетевой город» origins byte for byte. The phone + bundles the same file in place as its only source of a diary host, and `--check` and a + test fail when the survey or the allow-list changes without a regeneration. +- **An anonymous school directory.** `GET /api/v1/directory/school-regions?q=` answers which + regions a school may be in, from DaData; a name that exists everywhere («Школа № 5») is + answered `generic` without calling DaData. It is throttled at 20 calls per 15 minutes per + caller and capped at 4,000 of DaData's 10,000 daily requests, counted per Moscow day in + `usage_counters` (`services/quota.py`, migration `0016`), so onboarding cannot spend the + search the bot's create-class step depends on. +- **Known-answer vectors both halves run.** `server/tests/vectors/diary_protocol.json` pins + both sign-in protocols, the login cleaning and the parsing of raw answers; the Python tests + and the Kotlin port run every case, so the two implementations cannot drift apart silently. + That proves they agree, not that either is right. +- **Each CI job runs whenever a file its tests read changes** (#159), not only its own + folder — `docs/deploy.md`, `docs/build.md`, `docs/diaries*`, `docs/legal/`, the catalog + and the vectors included. + +### The defects, each filed before its fix + +Sixteen, on top of part one's three (#136–#138): + +| Issue | What was wrong | Fixed in | +| --- | --- | --- | +| #145 | «📒 Мой дневник» kept reading the «Сетевой город» region a class had been rebound away from | `6fa1c6e` | +| #146 | the keep-alive could overwrite a credential a diary read had rotated while the ping was in flight | `6fa1c6e` | +| #147 | a sign-in without `cacheVer` sent the word `None` upstream as `ver` | `6fa1c6e` | +| #148 | malformed «Сетевой город» sign-in answers escaped the diary errors as `500`s | `6fa1c6e` | +| #149 | the school search kept a result whose id was JSON `true` and bound the class to school 1 or 0 | `6fa1c6e` | +| #150 | comments and documents described a CA bundle, a breaker, a region order and a password route that do not exist, and the bot told families their password went «прямо в дневник» | `6fa1c6e`, `0a9a188`, `6281dea`, `5efca54` | +| #151 | a phone that left its last class kept its diary sign-in but could neither open «Дневник» nor sign out of it | `b19e6b2`, `c032ff2` | +| #152 | a phone in no class had its periodic sync re-armed on every cold start | `b19e6b2`, `c032ff2` | +| #153 | the diary said «HTTP 429», «Дневник не отвечает» for a switched-off diary, and a raw «HTTP 504» | `6fa1c6e`, `b19e6b2`, `c032ff2` | +| #154 | the join screen, settings and the guide promised a default server the APK does not have | `c032ff2`, `5efca54` | +| #155 | the design credit ran into the word before it, «по мотивамEssentials» | `ce9c749` | +| #156 | crash reports went into the cloud backup although the first run says they stay on the phone | `ce9c749` — **stays open** until a phone confirms it | +| #157 | comments and `docs/design.md` described a four-screen first run and a six-character class code | `c032ff2`, `5efca54` | +| #158 | the bot's sign-in page sent a «Сетевой город» family to Петербург's diary on an unreadable answer | `0a9a188` | +| #159 | CI skipped the server tests that read `docs/deploy.md` and `docs/build.md` when only those changed | `ba9170c` | +| #160 | contributor and agent documents quoted a stale test command, stale counts, wrong secret names and milestone facts | `8bad211` | + +Twelve more, from an adversarial review of the new Android data layer, were fixed in +`9c797a2`, each with a test that failed before its fix; they are listed in that commit's body +and have no issues of their own. + +**One commit body is wrong, and the code is right.** `6fa1c6e` says rebinding a class to +another *school* expires its diary sessions. `services/diary.expire_off_binding` expires them +when the provider or the region changes and keeps them for another school in the same region, +because a «Сетевой город» session is an account on the region's server rather than on one +school. The documents follow the code. ### Schema -`EXPECTED_REVISION` is now `0015` (revision `0015_diary_provider_columns`), which adds the -eight nullable columns named in the opening — five on `diary_sessions`, three on `classes`. It -is **additive** and **must be applied to Neon before the merge**; it has **not** been applied -yet, and the production database is still at `0014`. A `NULL` provider means Петербург, so the -running code is happy without the columns and the code that needs them is #140's. +`EXPECTED_REVISION` is `0016`; production was at `0014` when this was written, two +revisions behind: + +- **`0015`** (`0015_diary_provider_columns.py`) adds five nullable columns to + `diary_sessions` — `provider`, `region`, `kept_alive_at`, `keepalive_attempted_at`, + `upstream_ok_at` — and three to `classes` — `diary_region`, `diary_school_id`, + `diary_school_name`. A `NULL` provider means Петербург, the only diary before the column. + Its downgrade expires every non-Petersburg session before dropping the columns that tell + one apart. +- **`0016`** (`0016_usage_counters.py`) creates `usage_counters` and nothing else. + +Both are additive, rewrite no row and destroy none, so both go on **before** the merge, +together, through the Neon connector: the DDL taken from the model, the database's state read +first, and `alembic_version` stamped to `0016` in the same transaction. On 25 September +production read `0014`, with **0** rows in `diary_sessions` and **1** class, so neither +revision had a row to touch. + +**Not applied yet, at the time of this commit.** The owner allowed both on one condition: that the code they serve is free of defects. The audit of the server half and of the two revisions was still running, and the DDL taken from the models had been compared with both revision files op by op, with no difference. This paragraph is replaced with the time and the outcome when the transaction runs, and that happens before the merge or not at all. ### What was deliberately left alone -- **Госуслуги (ЕСИА) sign-in.** Some regions have switched passwords off and answer with a - clear refusal, which the client surfaces as `SignInUnsupported`. Driving ЕСИА ourselves is - #135's decision, not this batch's. -- **The refresh-token grant (LoginType 9).** It exists in the client but is unverified live. -- **SignalR reports** — final marks, attendance letters — are not read. -- **Everything on the phone.** The Android app stays Petersburg-only until batch 2 (region and - school at sign-in, the zone from the server, neutral strings). That «server first» order was - the owner's decision. +- **No Госуслуги (ЕСИА) sign-in, no WebView and no cookie capture, anywhere.** A Госуслуги + session is a session to the person's whole state-services account. ТОР «Моя школа» and the + three Госуслуги-only «Сетевой город» regions (`altai-krai`, `primorye`, `tula`) hand off to + the official site instead, and a generator test refuses any catalog field for an in-page + sign-in. This is the code's answer to #135's second and third questions; the issue stays + open for the owner to close. +- **A diary-only phone's widget, «Сегодня», «Календарь» and alerts show nothing from the + diary** — + #142, `status:next`, no milestone. Feeding them would mean a background read, which would + count as the family's activity and keep a session alive with nobody behind it. +- **A diary session opened on the phone is invisible to the bot** — #143, `status:someday`, + no milestone. Phone-registered rows carry no Telegram account and no class. +- **A fresh install has no default server** — #144, a decision for the owner, no milestone. + The address is asked for where it is first needed; there is no + `LESSONS_DEFAULT_SERVER_URL`. +- **The class's binding reaches the phone in `JoinResponse.diary` only**; `ClassOut` does not + carry it. +- **The password routes stay.** The bot's `/diary/signin` and `POST /api/v1/diary/login` + still pass a password through this server, for the bot and for older APKs, and the texts + now say so. +- **The phone does not refuse a login longer than the server's 200 characters**; the server + answers `422` at registration, which the phone reads as an app bug. +- **Left from part one:** the refresh-token grant (LoginType 9) is in the client and + unverified live, and SignalR reports — final marks, attendance letters — are not read. +- **The older sections of this file quote the milestones' old titles** where that is what + they were called at the time; the table maps each to its new one. ### Gates -Run on the final head, not quoted: `ruff check app tests scripts migrations` clean; -`pytest -q -n auto` **1668 passed** (was 1634); `python -m mypy` **Success** across 97 modules -(`files = ["app"]`, 84 before the two provider packages joined). Android was not touched, so -`./gradlew test` was not re-run and stands at **968**. +Run, not quoted, on the branch as it stood at `8bad211`: `ruff check app tests scripts +migrations` clean; `pytest -q -n auto` **1944** passed (1634 on `main`); `python -m mypy` +**Success** across **100** modules (84 on `main`); `./gradlew test` **1371** (968 on `main`) — +`:app` 513, `:core:data` 532, `:core:designsystem` 99, `:core:model` 125, `:widget` 102. +`assembleDebug` and `assembleRelease` were last run locally at `c032ff2`, and CI builds both +on every push. `b19e6b2` and `c032ff2` report the grep for Russian in Kotlin finding nothing +new but `UpstreamMarkers.kt`, the diaries' own words matched in their answers; it was not +re-run for this close-out. ### What nobody has verified in this batch -**No code here has met a live «Сетевой город» server with a real account.** Every upstream -shape — the salted-MD5 sign-in dance, `/webapi/context`, the weekly diary, the school search — -is from open-source clients and hand-written test payloads, never from a server seen -answering. The first live sign-in is the owner's (#121, #135), the same caveat that stands -for Петербург. +Section 5 carries each of these with the reason it is unverifiable. In short: + +- **Nothing has met a live diary.** «Сетевой город» has never been signed in to for real, on + the server or through the phone's port, and Петербург never through the phone. +- **Whether a session opened on a phone is accepted when our Frankfurt server replays it** is + open for both diaries. A `409` is the designed failure; the owner's first live session + decides it. +- **Nothing has run on a device**: the first run, the swap between the three homes, the + handoffs to the browser, the backup exclusion (#156), TLS against the regional servers, + Android's own windows-1251, `diary.db` on a real phone, the widget's new sentence on a + launcher. +- **DaData**: whether its company rows carry `region_kladr_id`, the codes of the four regions + admitted in 2022, and whether its day turns at Moscow midnight. +- **The legal texts have never been read by a lawyer.** ## What the session before it added: the electronic diary of every Russian region, and the routes each platform exposes -Open as PR #134, from `claude/school-diary-api-routes-cc4o1n`, in the milestone -`v0.8.0 — On a device`; it closes #130. **Documentation only.** No file under `server/`, -`android/` or `.github/` changed, and there is no migration. +Merged as PR #134 (`fa4fe0c`), from `claude/school-diary-api-routes-cc4o1n`, in the milestone +then called `v0.8.0 — On a device`; it closed #130. **Documentation only.** No file under +`server/`, `android/` or `.github/` changed, and there is no migration. The project reads one diary, Петербург's. Until this batch nothing in it said what a school anywhere else keeps its marks in, how a client signs in there, or which routes it exposes. @@ -286,8 +444,9 @@ passed. What was checked instead, on the final head: ## What the batch before added: the tracker (#128), its rule (#129), and their close-out (#133) -Documentation and agent configuration only. No model, endpoint, screen or test changed, so -the gates stand exactly where #85 measured them. +Merged as #128 (`3c3b728`), #129 (`a43c6e8`) and #133 (`5a77d14`). Documentation and agent +configuration only. No model, endpoint, screen or test changed, so the gates stood exactly +where #85 measured them. - **#128** opened the issue tracker: forty-two issues, #86–#108 closed and #109–#127 open, labelled `type:`, `area:`, `status:` and `needs:`. It also moved the work to a local @@ -315,12 +474,12 @@ already point at their issues. `/api/v1/warmup` has still not been read since #6 ## What the batch before added: the gesture #84 shipped did nothing, and the variables nobody could find -Open as PR #85, in the milestone `v0.7.0 — Оптимизация`. It is one defect, and it is the -defect that the feature merged an hour earlier did not work: **a tab dragged to another slot -went back where it came from and the order was never stored.** On the screen it looked -right the whole way — the icons slid, the row opened a gap, the neighbours moved — because -all of that is recomputed every frame. Only the drop was wrong, and the drop is the part -that is remembered. +Merged as PR #85 (`ef07739`), in the milestone `v0.7.0 — Оптимизация`. It is one defect, and +it is the defect that the feature merged an hour earlier did not work: **a tab dragged to +another slot went back where it came from and the order was never stored.** On the screen it +looked right the whole way — the icons slid, the row opened a gap, the neighbours moved — +because all of that is recomputed every frame. Only the drop was wrong, and the drop is the +part that is remembered. ### Why it survived #84's tests @@ -1279,11 +1438,11 @@ server either. ## What the batch before added: an audit of the whole project, and a typeface that can draw it -Open as PR #76, in the milestone `v0.7.0 — Оптимизация`. Twelve agents swept the nine areas -of `.claude/skills/audit/SKILL.md` plus documentation, strings and access, read-only; every -finding below was then re-verified by hand here and closed by a test proved red without its -fix. What was found is larger than what is fixed, and the rest is listed at the end rather -than quietly dropped. +Merged as PR #76 (`01f7a30`), in the milestone `v0.7.0 — Оптимизация`. Twelve agents swept the +nine areas of `.claude/skills/audit/SKILL.md` plus documentation, strings and access, +read-only; every finding below was then re-verified by hand here and closed by a test proved +red without its fix. What was found is larger than what is fixed, and the rest is listed at +the end rather than quietly dropped. ### The app shipped a typeface that cannot draw Russian @@ -1402,11 +1561,11 @@ repository. ## What the batch before added: the typeface is compressed by the build -Four commits in `dev`, open as PR #75, in the milestone `v0.7.0 — Оптимизация` (number 8), -which the owner created for this batch because none of the seven fitted. Its number was not -handed over and nothing here lists a milestone, so it was assigned as 8 — the next after the -seven — and then **read back off the pull request** rather than assumed, which is the only -check available and is what the `github-pr` skill means by reading a number back. +Four commits in `dev`, merged as PR #75 (`01a69fc`), in the milestone `v0.7.0 — Оптимизация` +(number 8), which the owner created for this batch because none of the seven fitted. Its +number was not handed over and nothing here lists a milestone, so it was assigned as 8 — the +next after the seven — and then **read back off the pull request** rather than assumed, which +is the only check available and is what the `github-pr` skill means by reading a number back. Its title is Russian where the other seven are English, which is the one place the project's own rule — Russian on the screen, English in everything written about the project — is not @@ -1571,10 +1730,10 @@ the code asks for and renders under Robolectric like any other resource. Nothing GitHub sign-in has run against live GitHub either; the secrets are set and the button is in the build, and the first press will be the owner's. -## What the last session added: the two loose ends +## What the batch before added: the two loose ends -One commit in `dev`, open as PR #72, in the milestone `v0.6.0`. Both were named by the batch -below as found-and-not-taken, and both are now taken. +One commit in `dev`, merged as PR #72 (`cb20b45`), in the milestone `v0.6.0`. Both were named +by the batch below as found-and-not-taken, and both are now taken. **A command the bot does not have answers.** Telegram stays silent on one, and for a bot with a single screen that is fine — but once a command started breaking out of a half-finished @@ -1621,12 +1780,12 @@ Nothing here has run on a device or against a live Telegram, as with everything `LESSONS_GITHUB_CLIENT_ID` and an address in `LESSONS_CONTACT_EMAIL`. Until then «Войти через GitHub» is in no build and the APK run summary says «off». -## What the last session added: the four things the sweep would not decide +## What the batch before added: the four things the sweep would not decide -Three commits in `dev`, open as PR #71, in the milestone `v0.6.0`. The batch below found -these four and deliberately left every one of them, because each is a decision rather than a -correction. The owner took all four; what follows is what each decision *was*, because the -code is the easy half. +Three commits in `dev`, merged as PR #71 (`0cdd7f1`), in the milestone `v0.6.0`. The batch +below found these four and deliberately left every one of them, because each is a decision +rather than a correction. The owner took all four; what follows is what each decision *was*, +because the code is the easy half. **A command wins over a half-finished form.** `/week` typed at «Теперь пришлите текст задания:» was committed as an assignment whose text was «/week», audited, and pushed to every @@ -1688,11 +1847,11 @@ register an OAuth App with **Enable Device Flow** ticked and put its client id i repository secret `LESSONS_GITHUB_CLIENT_ID`, and an address in `LESSONS_CONTACT_EMAIL`. Until then «Войти через GitHub» is in no build, and the APK run summary says «off». -## What the last session added: the crash, the button that was never built, and twelve defects +## What the batch before added: the crash, the button that was never built, and twelve defects -Seven commits in `dev`, open as PR #70, in the milestone `v0.6.0`. Three parts: the crash the -batch below could not explain, a feature that was missing from every APK ever built, and a -five-agent sweep of the whole tree. +Seven commits in `dev`, merged as PR #70 (`7bde4f7`), in the milestone `v0.6.0`. Three parts: +the crash the batch below could not explain, a feature that was missing from every APK ever +built, and a five-agent sweep of the whole tree. ### The crash after the link, which was a line of layout @@ -1817,10 +1976,10 @@ honest answer rather than a silent one. And install a build carrying all of this phone again: none of it has run on a device, and the uninstall-first caveat below still applies to a debug-signed APK. -## What the last session added: a crash report that its own phone can read +## What the batch before added: a crash report that its own phone can read -One commit in `dev`, open as PR #69, in the milestone `v0.6.0`. It is the answer to a -question that could not be answered: **«приложение вылетает через несколько секунд после +One commit in `dev`, merged as PR #69 (`cbb81e8`), in the milestone `v0.6.0`. It is the answer +to a question that could not be answered: **«приложение вылетает через несколько секунд после привязки Telegram» — and there was no way to get the stack trace off the phone.** The switch that records crash reports has always been on «О приложении», where everybody can @@ -1859,7 +2018,7 @@ is written, not when it is written. --- -## What the last session added: the guide is fetched, and a debug-signed APK explained +## What the batch before added: the guide is fetched, and a debug-signed APK explained Four commits in `dev`, merged as PR #67 (`0957628`), in the milestone `v0.6.0`. Two unrelated things that arrived in one batch because the first was a question about the @@ -1964,7 +2123,7 @@ afterwards — and silent on this tree, where it had just spoken. --- -## What the session before it added: a correction goes out as a pull request +## What the batch before added: a correction goes out as a pull request Three commits in `dev`, merged as PR #64 (`e4361a0`), in the milestone `v0.6.0`. Before them, PR #63 (`ec0d976`) carried the previous batch's close-out in this file and nothing else, and @@ -2119,32 +2278,37 @@ turn a true record of a named commit into a false one. **Every pull request now carries a milestone, and the rule is written down.** Sixty-two had gone in without one, and they have one only because somebody went back and did it by hand. -There are no issues in this repository — not one has ever been opened — so the milestones are -the only grouping its history has. Seven exist and they are **retrospective**: the boundaries -were read off the history rather than declared, and nothing here has ever been tagged or -released, so `versionName` is still the `0.1.0` default. - -| # | Milestone | Covers | -| --- | --- | --- | -| 1 | `v0.1.0 — First run on a phone` | #1–#14 | -| 2 | `v0.2.0 — The diary, and the class run from the bot` | #15–#17, #28–#31 | -| 3 | `v0.3.0 — The school year` | #27, #32–#35, #43 | -| 4 | `v0.4.0 — Nothing breaks in silence` | #44, #45, #50 | -| 5 | `v0.5.0 — A public repository` | #46–#49, #51, #55–#57, #59 | -| 6 | `v0.6.0 — One container, and nothing cut off` | #60–#74 | -| 8 | `v0.7.0 — Оптимизация` | #75–#85, #128 — the one Russian title | -| 9 | `v0.8.0 — On a device` | issues #109–#117, #130–#132; #129, #133 and #134 — the latest that **exists** | -| 7 | `Dependencies` | every dependabot bump; deliberately not a version | - -**A tenth milestone does not exist yet, and #140 waits on it.** The second-diary work -belongs to none of the nine — it is neither «On a device» nor a dependency bump — so the -owner was asked to create a tenth, e.g. «v0.9.0 — A second diary», with the title and -description already written. Until they do, #140 is a draft with no milestone. +There were no issues in this repository then — #128 opened the first — so the milestones +were the only grouping its history had. Seven existed and they are **retrospective**: the +boundaries were read off the history rather than declared, and nothing here has ever been +tagged or released, so `versionName` is still the `0.1.0` default. + +**The milestones as they are now.** The owner renamed all nine on 25 September 2026, so that +every title names what its version delivered and every description names its pull requests +and issues, and created the tenth the same day. The older sections of this file quote the +titles of their own time, which a search no longer finds; the third column maps them. The +`github-pr` skill carries the same table. + +| # | Title | Called before 25 September | State | Covers | +| --- | --- | --- | --- | --- | +| 1 | `v0.1.0 — App, widget, admin bot and read API` | `v0.1.0 — First run on a phone` | closed | PRs #1–#14; issues #86, #88, #89 | +| 2 | `v0.2.0 — Petersburg e-diary, class run from bot and phone` | `v0.2.0 — The diary, and the class run from the bot` | closed | PRs #15–#17, #28–#31; issues #87, #90, #91, #102 | +| 3 | `v0.3.0 — School year, terms, school search, several classes` | `v0.3.0 — The school year` | closed | PRs #27, #32–#35, #43; issue #92 | +| 4 | `v0.4.0 — 67-defect sweep, first audit, app-wide correction mode` | `v0.4.0 — Nothing breaks in silence` | closed | PRs #44, #45, #50; issues #93, #94 | +| 5 | `v0.5.0 — Public repo: secrets audit, English docs, font licence` | `v0.5.0 — A public repository` | closed | PRs #46–#49, #51, #55–#57, #59; issue #95 | +| 6 | `v0.6.0 — Dishka DI, scrolling text, in-app guide from the repo` | `v0.6.0 — One container, and nothing cut off` | closed | PRs #60–#74; issues #96, #97, #99, #101, #103, #104 | +| 7 | `Dependencies — dependabot bumps` | `Dependencies` | open, for good | every dependabot bump; deliberately not a version | +| 8 | `v0.7.0 — School-year calendar, day ribbon, rearrangeable tabs` | `v0.7.0 — Оптимизация` | closed | PRs #75–#85, #128; issues #98, #100, #105–#108 | +| 9 | `v0.8.0 — On-device checks, 89-region e-diary survey` | `v0.8.0 — On a device` | open | PRs #129, #133, #134; issues #109–#117, #130–#132 — the first whose work needs an emulator or a phone | +| 10 | `v0.9.0 — NetSchool e-diary, onboarding via the school's diary` | none — proposed as «v0.9.0 — A second diary», never created under that name | open | PR #140; issues #135–#139, #141, #145–#160 — the one being worked on | + +**#142, #143 and #144 are on no milestone, deliberately**: two follow-ups and a decision that +#140 left alone on purpose, which belong to whichever version takes them up. **Nothing in a session here can create a milestone**, only attach one — the owner created -the ninth on 22 September 2026 and issues #109–#117 are on it. **It is the first milestone -that groups issues rather than pull requests**, and the first whose work cannot be done -without an emulator or a phone. +the ninth on 22 September 2026 and the tenth on 25 September. **The ninth was the first +milestone that groups issues rather than pull requests**, and the first whose work cannot be +done without an emulator or a phone. From here the rule is in `CLAUDE.md` and in the `audit`, `github-pr` and `release` skills: a found defect becomes an issue before it becomes a fix, the pull request ties itself to it @@ -2549,7 +2713,7 @@ curl -s https://.vercel.app/api/v1/warmup # {"status":"ok","schema":" A `"degraded"` here would mean the deploy had not arrived; before `0013` was applied, the same request honestly called the database behind, because `EXPECTED_REVISION` was already -`0013`. The head is `0014` today — see the top of this file — and the same request reads it +`0013`. The head is `0016` today — see the top of this file — and the same request reads it the other way round while a revision waits for its merge: the database is *ahead* of the code, and `/warmup` says so in as many words, «База впереди кода…». @@ -2572,9 +2736,9 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 1668 tests, ~4 min (CI runs this) -cd server && python -m mypy # clean, 97 modules -cd android && ./gradlew test # 968 tests across the five modules +cd server && pytest -q -n auto # 1944 tests, ~4 min (CI runs this) +cd server && python -m mypy # clean, 100 modules +cd android && ./gradlew test # 1371 tests across the five modules cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` @@ -2646,11 +2810,13 @@ parity was computed from the ISO week number, which does not alternate in a 53-w from January 2027 the whole denominator of the **current** school year slid by a week, simultaneously in the API, the widget, the digests and the calendar. -**Migrations:** production is at `0014`, and that is the last revision written. `0007`–`0012` -were applied **before** the merge through the Neon connector, `0013` after it (it adds a -`UNIQUE`, and a constraint migrates in the opposite direction from a column), and `0014` -before it again. The details and what each one did are in section 7, item 1. **There is -nothing left to do to the database before a merge.** +**Migrations:** the last revision written is `0016`, and production was read at `0014` on +25 September. `0007`–`0012` were applied **before** their merge through the Neon connector, +`0013` after it (it adds a `UNIQUE`, and a constraint migrates in the opposite direction +from a column), and `0014` before it again. `0015` and `0016`, both written on #140 and both +additive, go on before #140's merge; whether they have is in «Schema» in that batch's section +at the top of this file. What each earlier revision did is in `CLAUDE.md` and in section 7, +item 1. --- @@ -2664,6 +2830,11 @@ calendar by years — was a decision rather than work, the owner made it on 21 S section is kept struck through rather than deleted: it shows what exactly was asked for and what it turned out to be. +**One request has come in since, and it is on #140.** On 25 September the owner asked for a +way in through the family's own school's diary, with the password never reaching our server +(#141). It is built — the first run, the diary-only home, the legal line, the catalog and the +directory — and closes when #140 merges; what nobody has verified about it is in section 5. + ~~1. **A pupil choosing their own class.**~~ Done in `8ec2e31`. The phone keeps a list of memberships, shows one of them and switches instantly; the cache is split by class, so switching works with no network too. What exactly is unverified is in section 5. @@ -2687,6 +2858,13 @@ The same as the "What does not exist at all" section of `README.md`: - The widget stays on the system font: Glance passes `fontFamily` as the name of a system family rather than as a resource. +And two that #140 left out on purpose, which are issues rather than lines in `README.md`'s +list: + +- A phone that reads only its diary gets nothing from it in the widget, «Сегодня», + «Календарь» or the alerts (#142). +- A diary session opened on the phone is invisible to the bot (#143). + ### 3.3. The typeface's licence — closed, and not the way this said **`google_sans_flex.ttf` is under SIL Open Font License 1.1**, Copyright 2015 Google LLC. The @@ -2709,7 +2887,14 @@ trademark stays a trademark: bundling is allowed, naming a product after it is n --- -## 4. There are no open defects +## 4. Open defects: none that #140 does not fix, and one fix that waits for a phone + +**The defects open as this is written are the ones #140 fixes.** #136–#138 and #145–#160 are +all fixed on its branch and meant to close with its merge — the table is in that batch's +section at the top of this file. The exception is **#156**: crash reports are now excluded +from every backup path in the rule files and a test reads both, but whether a phone's backup +really leaves them out takes a phone and `bmgr`, so the issue stays open, `needs:device`. +Everything below is the record from before the tracker, and it still holds. All sixteen findings of the first four audits are closed, as are all six findings of the four audits of `8ec2e31` (`569bab8`), the fifteen of `ce02348` (`c6ba66c`), the seven of `59c7a77` @@ -2945,8 +3130,10 @@ else.** #113 the widget's sizes, #114 the arranging gesture, #115 the correction mode, #116 two classes on one phone, #117 the upgrade path, #111 what the ribbon's shader costs, #121 the real diary. They are children of **#109**, the epic for moving this work to a machine with a -device on it. The prose here is kept because it says *why* each one is unverifiable, which -an issue title cannot. +device on it. #140's additions below belong to #121 where they need a live diary and to +#156 where they need a phone's backup; the rest wait for the first APK built after its +merge. The prose here is kept because it says *why* each one is unverifiable, which an issue +title cannot. - **Not one route in `docs/diaries/` has been seen answering.** #134's 1916 routes were read from client code and two official apps, and cross-checked against each other. @@ -2954,15 +3141,58 @@ an issue title cannot. means that a client active in 2025 or 2026 sends it, not that a server accepts it today. ТОР «Моя школа» rests on one app build, 5.0.0.454, and its first-wave list rests on one official post. The first live session on any platform will correct its page. Whoever has - it should edit the page by hand, because the generator is not in the repository. + it should edit the page by hand, because the generator is not in the repository — and, + where the edit touches `docs/diaries/regions.md`, regenerate the region catalog with + `scripts/region_catalog.py`, which a test insists on. - **The «Сетевой город» provider has never met a live server.** #140 wrote the client, the mapper, the keep-alive and the school search from open-source clients and hand-written test payloads; no ИРТех server answers a cloud session, so none was called. Every upstream shape — the salted-MD5 sign-in, `/webapi/context`, the weekly diary, the school search — is what a client sends, not what a server was seen to accept. The refresh-token grant (LoginType 9) and the Госуслуги refusal path (`SignInUnsupported`) are the least exercised of all. The - first live sign-in on it is the owner's, #121's caveat a second time; #135 is the decision - that precedes it. + first live sign-in on it is the owner's, #121's caveat a second time. +- **The phone's own sign-in has never met a live diary either — neither «Сетевой город» nor + Петербург.** The Kotlin ports and the Python originals run one set of known-answer vectors + (`server/tests/vectors/diary_protocol.json`), which proves the two agree and nothing about + whether either is right. Whether a Петербург pupil's own account lists itself as a pupil, + and how long its token lives, are unknown for the same reason. +- **Nobody knows whether a diary accepts a session opened on a phone when our server replays + it.** The phone signs in from the family's own address, and `POST /api/v1/diary/session` + then reads with that session from Frankfurt. A diary that ties a session to its address, or + refuses foreign ones, answers that read with a refusal, and the server turns it into a + `409`, meaning the diary refused the session from our address — by design, with no automatic + retry. If that is what the first live session gets, the phone-registered path does not work + for that diary and only the password routes remain. Whether «Сетевой город»'s four bootstrap + calls fit inside Vercel's 30-second ceiling is unmeasured too. +- **Nothing of #140's phone half has run on a device.** Nothing composes `LessonsApp` in a + test, so the gate between the three homes, the hold on the first run through a join or a + registration, the swap to the right home and the resume after the process dies are proved + by the pure rules and the view models only. Nobody has seen the first run on a screen, + the wavy progress bar under real timings, the browser handoffs — the legal documents, ТОР + «Моя школа», the three Госуслуги-only regions — or the bundled fallback sheet, or heard + any of it through TalkBack. `diary.db` has not been written on a real phone. +- **TLS against the regional servers, and Android's own windows-1251, are inferred.** The + failure shapes `UpstreamHttp` classifies are the ones Conscrypt and the JVM are known to + throw, not ones seen on a device; the port carries its own windows-1251 table rather than + trusting the device's ICU, and whether the device's would have agreed is unasked. A + `Retry-After` given as a date is read as no wait. +- **The backup exclusion of crash reports (#156) is proved in XML only.** `BackupRulesTest` + reads both rule files and the reporter's folder name; whether a real backup leaves the + reports out takes a phone and `bmgr`, which is why the issue stays open. +- **The widget's third sentence has never been on a launcher.** Whether «Дневник — в + приложении» and the new sentence for a phone with neither fit their rungs without a clip is + judged by length only, and the redraw when the mode changes rests on a broadcast no test + composes. +- **DaData's side of the school directory is assumed.** Whether its company rows carry + `region_kladr_id` is unknown — the directory falls back to the region's name for exactly + that reason — and so are the subject codes of the four regions admitted in 2022 (90, 93, + 94, 95), every DaData spelling in the catalog's overlay, and whether DaData's day turns at + Moscow midnight, which is when `usage_counters` starts a new one. Two requests racing for + the last unit of the day were checked on SQLite only. +- **The terms of use and the privacy policy have never been read by a lawyer.** They + describe what the code does and claim compliance with nothing: whether naming a GitHub + account as operator satisfies 152-ФЗ, the transfer to hosting in Frankfurt, the age line + and parental consent are open. - **Nothing of the tab arranging has been seen on a phone, and it is a gesture.** #84 is a long press, a wobble and a drag; #85 is the drag actually reporting where it landed. What the 39 tests prove is arithmetic and contracts: where a drag of so many pixels lands, that @@ -3038,7 +3268,8 @@ an issue title cannot. - **`/api/v1/warmup` has still not been read, and it is now known to be unreachable from a session rather than merely not done.** The deployments are behind Vercel's Deployment Protection and answer a redirect to a login page, so no `curl` from here can settle - whether `0014` and the code that needs it met. It needs the owner's browser or a bypass + whether the schema — `0016` once #140's revisions are on — and the code that needs it + met. It needs the owner's browser or a bypass token; it has been outstanding since #61 and it is in section 7 for that reason. - **`docker compose up` has never been run.** There is no Docker in this environment, so what #83 proves about the new `migrate` service is that the compose file parses and that @@ -3060,8 +3291,8 @@ an issue title cannot. would not compile normally throws in-process instead of logging from the render thread. - **The reported term defect is fixed against tests, not against the class that reported it.** The server fix needs no new APK, so the first real check is that class's next sync - after the deploy, and `/api/v1/warmup` answering `"schema":"0014"` is the cheapest sign - that the migration and the code actually met. + after the deploy, and `/api/v1/warmup` answering `"schema":"0014"` or later is the + cheapest sign that the migration and the code actually met. - **There is still no `androidTest` in the project**, and no emulator is available here: the container has no `/dev/kvm` and no virtualisation flags, so the system could only be started by full software emulation, that is, not at all. @@ -3135,9 +3366,10 @@ an issue title cannot. decision (`SchoolAlerts.arm` refused `setWindow` and explained why). - **A live DaData has never been asked**: there is no `DADATA_TOKEN` in the development environment, and every test on both sides runs a stub. The owner reported setting the key - on Vercel — **nothing has verified that.** -- **The real dnevnik2 has never been opened**, neither the sign-in nor any of the four - screens. + on Vercel — **nothing has verified that.** #140's anonymous school directory rests on the + same stub, and so does its daily count. +- **The real dnevnik2 has never been opened**, neither the sign-in — the server's or, since + #140, the phone's own — nor any of the four screens. - **Not one server-side fix has been run against a live class.** `claim` is verified by claiming twice on one date, but nobody has run two ticks at once; the export's round trip is verified by computing both sides, which is all it claims. @@ -3211,8 +3443,10 @@ second between those two answers during a switch, and taking the local one would one class's window under another's name. `replaceAll` moves the `classId` from the class's row onto the day records for the same reason. -The Room schema is at version 3. There is no migration and none is needed — the cache is -disposable (`fallbackToDestructiveMigration`) and the first sync fills it. +`lessons.db` (`LessonsDatabase`) is at Room schema version 5, and #140 added a second +database, `diary.db` (`DiaryDatabase`), at version 1. Neither has a migration and neither needs +one — both are disposable (`fallbackToDestructiveMigration`): the first sync fills the one and +the next diary read the other. The memberships live in `Memberships.kt`, separately from `LessonsPreferences`: that is also where the **old format** is read — one session in four flat keys — and where the @@ -3318,6 +3552,43 @@ checked only by its hash — `find_live` does not re-read `BotUser` — so witho excluded in the last fifteen minutes would still let a phone in. Used rows are left alone: they are the record that a phone has already joined. +### The second way in: a phone that signs in to its own diary + +`docs/architecture.md` says where the password, the upstream session and the two bearers +live during the first run, and where they never do. These are the parts that break quietly: + +- **On the phone's path the password goes to the diary and nowhere else.** + `POST /api/v1/diary/session` refuses a body with a `password` key (`extra="forbid"`), and + every credential value passes the one "safe to put in a header" check in + `providers/diary/http.py`, because cookie values go straight into `Cookie:`. Do not add a + field there that could carry a password. `/diary/login` and the bot's `/diary/signin` + still take one, and say so to the person typing it. +- **The phone's diary hosts come from the bundled catalog and nowhere else.** `OriginGuard` + refuses any other origin; the catalog is `server/app/catalog/data/regions.json`, bundled + in place rather than copied, and its «Сетевой город» origins are the server's allow-list + byte for byte. Change the allow-list or `docs/diaries/regions.md` and regenerate with + `scripts/region_catalog.py` — `--check` and + `test_the_committed_catalog_is_what_the_generator_writes` fail otherwise. +- **The two sign-in implementations are held together by one file.** + `server/tests/vectors/diary_protocol.json` runs in the Python tests and against the Kotlin + port; a protocol change is a change to the vectors first, then to both. +- **Nothing reads the diary in the background** — not the sync worker, not the widget. + `SyncWorkerSourceTest` scans them and every application, receiver and service the manifests + declare. A background read would count as the family's activity and hold a «Сетевой город» + session open for the keep-alive's thirty days with nobody behind it (#142). +- **Periodic class sync is armed only in class mode**, from the shell mode's arming in + `LessonsApplication` rather than on every settings emission (#152). +- **The directory's share of DaData is its own.** `/api/v1/directory/school-regions` is + charged to `usage_counters` under a cap of 4,000 a day; the bot's and `/manage/schools`' + searches are never charged to it. Putting them on one counter is how onboarding would + spend the search the bot's create-class step depends on. +- **The legal address is per fork.** `LESSONS_LEGAL_BASE_URL` compiles into + `BuildConfig.LEGAL_BASE_URL`, and the build refuses a value that is not https; the texts + carry `FORK:` comments naming what a fork rewrites, and `docs/build.md` says the rest. +- **CI runs a job when a file its tests read changes**, and `ci.yml`'s path filter names + those files; a test that starts reading a document outside its half adds the document + there (#159). + ### Everything that came from outside is escaped before it is sent The bot sends HTML, and on one angle bracket Telegram refuses **the whole message** rather @@ -3767,33 +4038,66 @@ All of this is beyond an agent's reach: it needs a phone, a key or a live servic **These are issues now**, so that they can be closed rather than re-read: #118 the Preview environment, #119 `/api/v1/warmup` and the bot's `/start`, #120 the external cron and `DADATA_TOKEN`, #121 the real diary, #122 the widget's tick cadence and the diary -credential's bound, #135 the second diary. Each carries the label `needs:owner`. - -**Create the tenth milestone so #140 can leave draft.** #140 adds the second diary and closes -#136–#139, but it belongs to no existing milestone; nothing in a session here can create one, -so it stays a draft until the owner makes a tenth (e.g. «v0.9.0 — A second diary») and -attaches it, with the title and description already handed over. +credential's bound, #135 the second diary, #144 a default server for a fresh install. Each +carries the label `needs:owner`; #156 carries `needs:device`. + +**The tenth milestone exists, and #140 is on it.** The owner created +`v0.9.0 — NetSchool e-diary, onboarding via the school's diary` on 25 September and renamed +the other nine the same day. One line of it is behind: its description names issues +#145–#159, and #160 is on it too. A milestone's description is the owner's to edit; nothing +in a session here can. + +**Sign in once, for real, from a phone — it is the one question #140 cannot answer about +itself.** Build an APK from `main` after #140 merges, install it on a phone in no class, and +take the diary path twice: a «Сетевой город» region that takes a password, and Петербург. +Whether the import arrives, or the phone says the diary refused the session from our +server's address — the `409` — decides whether the phone-registered path works for that +diary at all. It is #121's first live session, for both diaries at once. + +**Then walk the rest of the first run on that phone.** The class code as the other way in; +leaving the last class with a diary signed in, which should land on the diary as the home +with «Выйти из дневника» still in settings (#151's path); the two legal links online and in +airplane mode; a ТОР region's hand-off to the official site. And read a backup with `bmgr` +for the crash reports — #156 closes only on that. + +**Decide #144: whether a fresh install gets a default server.** The diary path needs our +server to register the session, and today a fresh install asks for its address where it is +first needed, because no address is compiled in and none is promised any more (#154). A +default is a build property and a decision about who that server serves; it is the owner's. + +**Have the terms of use and the privacy policy read before anybody relies on them.** They +describe what the code does and claim compliance with nothing: whether a GitHub account named +as operator satisfies 152-ФЗ, the transfer to hosting in Frankfurt, the age line and parental +consent are questions for a lawyer. Each passage about this deployment sits under a `FORK:` +comment. Nothing has been published, so `docs/legal/legal.json` is still edition 1; once +the texts are out, every change to them raises it, as the `release` skill says. + +**`DADATA_TOKEN` now serves a second caller (#120).** The anonymous school directory spends at +most 4,000 of DaData's 10,000 daily requests. Without the key it answers `503` with +`X-Directory-Unavailable: disabled`, and a family still finds its region in the bundled +catalog — only the search by a school's name is gone. **The keep-alive is only as alive as the cron (#120).** «Сетевой город» sessions are held open from `GET /api/v1/cron/tick`, so they lapse if the external cron does not tick; `.github/workflows/reminders.yml` is the fallback, not the clock, exactly as for the digests. -**#140 answered the first of #135's three questions; the other two remain.** `docs/diaries.md` -is the map: - -- **Which platform — settled.** #140 built «Сетевой город» server-side: one route set, the - largest group of regions, and a password still accepted outside the regions that allow - Госуслуги only. The МЭШ family comes after it. Against a live server it has not been read. -- **How a family signs in**, now that Госуслуги is the only door in most regions. Either - the server accepts a token a person brought from a browser, which is what every durable - client does, or it drives ЕСИА itself and breaks whenever Госуслуги changes its login. - The first makes `/diary/signin` a page with a second job, and `CLAUDE.md` guards that page - closely. -- **Whether ТОР «Моя школа» may be used at all.** It is the diary of twenty regions since - 1 September 2026. Its only known way in is a person signing in to Госуслуги inside a - WebView, and nobody has read Госуслуги's terms. - -Whichever platform it is, the first step is one real session against it, as #121 is for +**#135 now has an answer in the code to each of its three questions, and closing it is the +owner's.** `docs/diaries.md` is the map: + +- **Which platform** — «Сетевой город», built on the server in #140's first part: one route + set, the largest group of regions, and a password still accepted outside the regions that + allow Госуслуги only. The МЭШ family comes after it. Against a live server it has not been + read. +- **How a family signs in** — with its password, typed into the app's own form and sent to + the diary alone; the session, not the password, reaches our server. Госуслуги is not driven + and no token is carried over from a browser, because a Госуслуги session is the person's + whole state-services account. The three Госуслуги-only «Сетевой город» regions hand off to + their own site. +- **Whether ТОР «Моя школа» may be used** — it is not read. The provider screen names it as + the region's system and hands off to the official site. Nobody has read Госуслуги's terms, + and nothing needs them read until somebody proposes reading ТОР. + +Whichever platform comes next, the first step is one real session against it, as #121 is for Петербург. Not one route in `docs/diaries/` has been seen answering. **Install one built after #85 and long-press a tab on the home screen.** The APK on #84's @@ -3833,11 +4137,12 @@ turn Preview deployments off in the project's Git settings; nothing here is a we there is nothing for a preview to show. Only the owner can do either — this session can read which keys exist per environment but must not create them. -**Open `/api/v1/warmup` in a browser — it is the one thing that settles whether `0014` and -the code that needs it actually met**, and it is outstanding since #61. It cannot be closed -from a session here at any effort: the deployments are behind Vercel's Deployment Protection -and answer a redirect to a login page, so this needs the owner's own browser or a bypass -token. The answer wanted is `{"status":"ok","api_version":1,"schema":"0014"}`; a +**Open `/api/v1/warmup` in a browser — it is the one thing that settles whether the schema +and the code that needs it actually met**, and it is outstanding since #61. It cannot be +closed from a session here at any effort: the deployments are behind Vercel's Deployment +Protection and answer a redirect to a login page, so this needs the owner's own browser or a +bypass token. The answer wanted once #140 has merged and deployed is +`{"status":"ok","api_version":1,"schema":"0016"}`; a `"degraded"` naming two revisions is the honest report of a migration and a deploy that have not met, and which way round it is, is in the `detail`. @@ -3868,14 +4173,16 @@ a deliberate replacement rather than an addition, because two views of one day i bot's two timetable editors nearly drifted apart; if it turns out to be missed, the ruler is in the history at `f5a8172^`. -**The milestones were the newest of these, and that one is done.** Milestones 1 to 5 cover -versions that are finished and the owner has closed all five. Three stay open on purpose: -`v0.6.0`, which is finished but not yet closed; **`v0.7.0 — Оптимизация`, number 8**, which -the owner created when none of the earlier ones fitted and which every batch from #75 to -#84 has gone in; and `Dependencies`, which takes every future bump. There is no -number 7 — the numbering is GitHub's and it skips. The reason a new one has to be asked for -stands for next time: no tool in a session here changes a milestone's state or creates one — -`issue_write` only assigns an existing one by number — and there is no `gh` CLI. +**The milestones were the newest of these, and that one is done.** Milestones 1 to 6 and 8 +cover versions that are finished, and the owner has closed all seven. Three stay open on +purpose: number 9, `v0.8.0 — On-device checks, 89-region e-diary survey`, whose device work +is still to do; number 10, `v0.9.0 — NetSchool e-diary, onboarding via the school's +diary`, which #140 is on; and number 7, `Dependencies — dependabot bumps`, which takes every +future bump. The ten titles, and what each was called before the owner renamed them on +25 September, are in the table under «And before that: nothing on a screen is cut off». The +reason a new one has to be asked for stands for next time: no tool in a session here changes +a milestone's state or creates one — `issue_write` only assigns an existing one by number — +and there is no `gh` CLI. **The first press of two network paths should be the owner's.** Neither the translation pull request from #64 nor the guide's fetch from #67 has ever run against GitHub, and both @@ -3883,10 +4190,6 @@ are written to be pressed by a reader. Opening the documentation once on a real and without a network, checks the second of them in about a minute — and the first press of «Отправить как pull request» checks the first. -**What is left of it is one line of text.** Milestone 6 describes itself as «PRs #60–#62» -and now holds everything up to #74. Editing that description needs the same access closing -it does. - **Two more are decisions rather than actions**, both from the second audit, both deliberately not taken by the session that found them because they trade one real cost against another and the trade is the owner's to make. @@ -3933,12 +4236,12 @@ and that is the thing to decide rather than the ttl. matches the model column for column, three indexes. ~~1a. **Apply `0013` after PR #45 is merged.**~~ Applied: head `0013`, the constraint in place, zero rows deleted (`homework` had none). -1b. **Open `/api/v1/warmup` and make sure the deploy arrived** — today that is - `{"status":"ok","schema":"0014"}` — and then send the bot `/start`: the very first message - goes through the middleware that reads a class, and that is the fastest check that the - schema and the code agree. That is all that is left of item 1; it needs a live service, - and since the deployments sit behind Deployment Protection it needs a browser or a bypass - token rather than a `curl` from a session. +1b. **Open `/api/v1/warmup` and make sure the deploy arrived** — once #140 has merged and + deployed that is `{"status":"ok","schema":"0016"}` — and then send the bot `/start`: the + very first message goes through the middleware that reads a class, and that is the fastest + check that the schema and the code agree. That is all that is left of item 1; it needs a + live service, and since the deployments sit behind Deployment Protection it needs a browser + or a bypass token rather than a `curl` from a session. 2. **Build the APK from `main` and install it on a phone.** See section 5 — it is the only way to check what nothing currently checks, and doubly so after three build-chain bumps. Three things have been added to this: connect the phone to two classes and walk between From 061a716604cb0caf5bbb2fb894e27d484518bbc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 07:12:41 +0000 Subject: [PATCH 24/30] Close the holes a second review found in the first run, the diary home and the join, each with a test that fails without its fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A second adversarial review of the screens (c032ff2, 9c797a2, fb8a70c) had 31 findings survive two independent refuters each; all 31 are fixed here. One of them already existed on main and has its own issue (#161); the rest are in code this pull request adds. The ones that mattered most: - Backing out during «Передаём сессию серверу…» cancelled the phone's request while our server went on to adopt the session, leaving a sealed diary credential nobody could sign out of, and a second sign-in minted another. Back, «Не сейчас» and «начать заново» are now refused while a sign-in is under way; the diary sign-in and the registration run to their end whatever the screen does, a session opened after a leave is ended at the diary, and a registration that lands after a cancel keeps its bearer so the server row always has a key. - A join whose screen was gone before it landed left its result behind, and the next «Добавить класс» sheet closed itself on it; in the first run the stale result could finish the flow and skip the class's diary sign-in (#161). Every join now reports under a ticket its own screen keeps; back is held while a code is out. - A diary view model left from an earlier diary home chose the pupil during a later import, so a two-child family never saw the chooser. The import now asks only while nothing holds the shell. - The diary home's sign-out sheet promised «сервер забудет свою копию входа» unconditionally; offline the logout is skipped. It now says what happens offline, and the privacy policy's promise is unchanged because it already said so. - The «Войти ещё раз» sign-in after the diary ended an import had no way out; it now offers «Выйти из дневника и начать заново». A restore after process death no longer reopens a form over a credential written in the background. And the smaller ones: «Забыли пароль?» named the region picked earlier rather than the diary the password goes to, and said nothing on a phone with no browser; the school step ignored a new name for the same region; the import and the diary home offered «Повторить» where a retry cannot help (a 502 among them); «Почему?» for an unreachable region recommended that region's diary; the summary promised a class family that opening the app keeps the diary sign-in alive, in a one-line marquee; the login field trimmed on every keystroke; the generic-name note promised a school step most regions do not have; a passing directory failure read as «search does not work on this server»; failures in the first run pointed at «Синхронизация», which the flow cannot reach; «Вход выполнен» stayed after a lapsed sign-in; a second first run pre-filled the signed-out login; UpstreamJson still accepted raw control characters inside strings. Five tests that passed without their feature now check it (the region row's match, the pupil chooser, the summary's content, the widget's mode read), and the in-app guide says what the import and the summary now do, identically in both languages. Gates: `./gradlew test` 1408 JVM tests (1371 before), `assembleDebug` and `assembleRelease` green; the shared protocol vectors 128 passed on the server. Not covered: nothing composes the real shell swap or the sign-in page in a test, so the join's disposal race and the no-browser line are held by the view models and pure rules; nothing has run on a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .../lessons/ui/diary/DiaryAccountPage.kt | 24 +- .../lessons/ui/diary/DiaryCredentialFields.kt | 11 +- .../lessons/ui/diary/DiaryProblemText.kt | 32 +- .../lessons/ui/diary/DiaryScreen.kt | 23 +- .../lessons/ui/diary/DiaryViewModel.kt | 33 +- .../lessons/ui/join/JoinScreen.kt | 62 ++-- .../lessons/ui/join/JoinViewModel.kt | 68 +++- .../lessons/ui/onboarding/ImportPage.kt | 25 +- .../lessons/ui/onboarding/ImportRunner.kt | 31 ++ .../ui/onboarding/OnboardingCatalog.kt | 31 +- .../lessons/ui/onboarding/OnboardingParts.kt | 12 +- .../lessons/ui/onboarding/OnboardingScreen.kt | 8 +- .../ui/onboarding/OnboardingViewModel.kt | 98 +++++- .../lessons/ui/onboarding/ProviderStep.kt | 5 +- .../lessons/ui/onboarding/RegionFinder.kt | 25 +- .../lessons/ui/onboarding/RegionStep.kt | 3 +- .../lessons/ui/onboarding/SchoolFinder.kt | 23 +- .../lessons/ui/onboarding/SignInPage.kt | 88 ++++- .../lessons/ui/onboarding/SignInStep.kt | 69 +++- .../lessons/ui/onboarding/SummaryPage.kt | 44 ++- .../lessons/ui/settings/ClassRows.kt | 28 +- .../src/main/res/values-en/strings_diary.xml | 9 +- .../main/res/values-en/strings_onboarding.xml | 10 +- .../app/src/main/res/values/strings_diary.xml | 11 +- .../main/res/values/strings_onboarding.xml | 14 +- .../lessons/ui/diary/DiaryHomeScreenTest.kt | 63 ++++ .../ui/diary/DiaryOnboardingHoldTest.kt | 105 ++++++ .../lessons/ui/diary/DiaryProblemTextTest.kt | 64 ++++ .../lessons/ui/join/JoinOneShotTest.kt | 122 +++++++ .../lessons/ui/join/JoinTestSupport.kt | 66 ++++ .../ui/onboarding/OnboardingCatalogTest.kt | 22 +- .../ui/onboarding/OnboardingFormTest.kt | 128 ++++++++ .../ui/onboarding/OnboardingPromisesTest.kt | 18 ++ .../ui/onboarding/OnboardingStepsTest.kt | 146 +++++++++ .../ui/onboarding/OnboardingTestSupport.kt | 36 ++- .../ui/onboarding/OnboardingTextTest.kt | 37 +++ .../ui/onboarding/OnboardingViewModelTest.kt | 306 +++++++++++++++++- .../data/repository/DiarySignInProblem.kt | 8 +- .../core/data/upstream/UpstreamJson.kt | 27 ++ .../data/repository/DiarySignInProblemTest.kt | 6 +- .../lessons/widget/LessonsWidget.kt | 23 +- .../lessons/widget/WidgetModeReadTest.kt | 73 +++++ .../lessons/widget/ui/EmptyTextTest.kt | 6 +- docs/app/guide.en.md | 6 +- docs/app/guide.ru.md | 6 +- server/tests/vectors/diary_protocol.json | 8 +- 46 files changed, 1897 insertions(+), 166 deletions(-) create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOnboardingHoldTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinOneShotTest.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinTestSupport.kt create mode 100644 android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFormTest.kt create mode 100644 android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetModeReadTest.kt diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt index 6a19f03e..482c3423 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryAccountPage.kt @@ -16,6 +16,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R @@ -29,6 +30,7 @@ import com.lumenpearson.lessons.core.designsystem.text.Text import com.lumenpearson.lessons.core.designsystem.text.correctedString import com.lumenpearson.lessons.core.designsystem.theme.accentTone import com.lumenpearson.lessons.core.designsystem.theme.errorTone +import com.lumenpearson.lessons.ui.join.JoinViewModel import com.lumenpearson.lessons.ui.settings.AddClassSheet /** @@ -49,11 +51,15 @@ import com.lumenpearson.lessons.ui.settings.AddClassSheet * * It reads the view model the home uses (the activity's), so the pupil chosen * here is the pupil the home shows. + * + * @param joinFactory what builds the class sheet's view model — the app's own, + * or a test's, which has no `Graph` to build it from. */ @Composable fun DiaryAccountPage( modifier: Modifier = Modifier, viewModel: DiaryViewModel = viewModel(factory = DiaryViewModel.Factory), + joinFactory: ViewModelProvider.Factory = JoinViewModel.Factory, ) { val state by viewModel.uiState.collectAsStateWithLifecycle() var confirmSignOut by rememberSaveable { mutableStateOf(false) } @@ -70,7 +76,13 @@ fun DiaryAccountPage( ) } if (addingClass) { - AddClassSheet(onDismiss = { addingClass = false }) + // A first class, not a second: this page exists only on a phone in + // none, where the sheet's own sentence spoke of classes already here. + AddClassSheet( + onDismiss = { addingClass = false }, + message = R.string.diary_account_join_class_message, + viewModel = viewModel(factory = joinFactory), + ) } val target = state.session?.target ?: state.signInTarget @@ -80,9 +92,17 @@ fun DiaryAccountPage( item(key = "header") { ScreenHeader( title = state.student?.fullName ?: correctedString(R.string.diary_title), + // «Вход выполнен» only while it is: the mode follows the stored + // target, not a live session, so a bare `401` leaves the phone + // on this page with the pupils gone and the login still known. subtitle = state.student?.let { student -> listOfNotNull(student.className, student.school).joinToString(" · ").ifBlank { null } - } ?: correctedString(R.string.diary_signed_in_as, target.login), + } ?: when { + state.signedIn -> correctedString(R.string.diary_signed_in_as, target.login) + // Nothing either way before the stored session is read. + !state.ready -> null + else -> correctedString(R.string.diary_reauth_title) + }, ) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt index acc37b8f..b8d48979 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryCredentialFields.kt @@ -45,7 +45,12 @@ import com.lumenpearson.lessons.core.designsystem.text.correctedString * The login is hoisted ([login], [onLoginChange]) because it is not a secret * and the caller may want it to survive a recreation, which the onboarding does. * - * @param login the login shown; trimmed as it is typed. + * @param login the login shown, as typed. Not trimmed per keystroke: the + * field hands back the value it is given, so a space trimmed off the end is + * a space that can never be followed by a letter — and «Сетевой город» + * logins may have one inside («Иванова Мария»). The ends are cleaned where + * the login is sent (`DiaryLogin.clean`, the server's own rule) and in the + * [onSubmit] argument. * @param loginEditable `false` on a re-authentication, where the login is known * and a field that could be changed invites signing in as somebody else. * @param busy a sign-in is in flight: both fields and the button are held. @@ -79,7 +84,7 @@ fun DiaryCredentialFields( val canSubmit = password.isNotBlank() && login.isNotBlank() && !busy fun submit() { - if (canSubmit) onSubmit(login, password) + if (canSubmit) onSubmit(login.trim(), password) } RoundedCardContainer(modifier = modifier) { @@ -87,7 +92,7 @@ fun DiaryCredentialFields( OutlinedTextField( value = login, onValueChange = { - onLoginChange(it.trim()) + onLoginChange(it) onEdited() }, modifier = Modifier diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt index b0ee992e..e36f4f97 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemText.kt @@ -47,8 +47,23 @@ sealed interface DiaryProblemMessage { DiaryProblemMessage } -/** Which sentence [problem] gets. Pure, so a test can hold every case of it. */ -fun diaryProblemMessage(problem: DiarySignInProblem): DiaryProblemMessage = when (problem) { +/** + * Which sentence [problem] gets. Pure, so a test can hold every case of it. + * + * Two sentences depend on who reads them, and say something false to the + * wrong reader. + * + * @param firstRun read in the first run, where there are no settings yet: the + * server's address is not «в разделе «Синхронизация»», which does not exist + * until the flow is over, but on the steps themselves. + * @param inClass read on a phone already in a class: the way round a diary + * that refuses our server is not a class code — the family has one. + */ +fun diaryProblemMessage( + problem: DiarySignInProblem, + firstRun: Boolean = false, + inClass: Boolean = false, +): DiaryProblemMessage = when (problem) { is DiarySignInProblem.WrongPassword -> { val main = DiaryProblemMessage.Line(R.string.diary_problem_wrong_password) val said = problem.upstreamMessage?.trim()?.take(UpstreamMessageMax) @@ -69,13 +84,17 @@ fun diaryProblemMessage(problem: DiarySignInProblem): DiaryProblemMessage = when hosted(problem.host, R.string.diary_problem_host_offline, R.string.diary_problem_offline_upstream) is DiarySignInProblem.Timeout -> hosted(problem.host, R.string.diary_problem_host_timeout, R.string.diary_problem_timeout) - DiarySignInProblem.Offline -> line(R.string.diary_problem_offline) + DiarySignInProblem.Offline -> + line(if (firstRun) R.string.diary_problem_offline_first_run else R.string.diary_problem_offline) DiarySignInProblem.RegisterUnreachable -> line(R.string.diary_problem_register_unreachable) - DiarySignInProblem.ServerMissing -> line(R.string.diary_problem_server_missing) + DiarySignInProblem.ServerMissing -> + line(if (firstRun) R.string.diary_problem_server_missing_first_run else R.string.diary_problem_server_missing) DiarySignInProblem.ServerTooOld -> line(R.string.diary_problem_server_too_old) DiarySignInProblem.ServerDisabled -> line(R.string.diary_problem_server_disabled) DiarySignInProblem.RegionNotServed -> line(R.string.diary_problem_region_not_served) - DiarySignInProblem.ServerRefusedSession -> line(R.string.diary_problem_server_refused_session) + DiarySignInProblem.ServerRefusedSession -> line( + if (inClass) R.string.diary_problem_server_refused_session_in_class else R.string.diary_problem_server_refused_session, + ) DiarySignInProblem.ServerAddressRefused -> line(R.string.diary_problem_server_address_refused) DiarySignInProblem.NoStudent -> line(R.string.diary_problem_no_student) is DiarySignInProblem.TooManyAttempts -> problem.retryAfterSeconds @@ -106,7 +125,8 @@ val DiarySignInProblem.offersRetry: Boolean /** [diaryProblemMessage], read out of the resources — through correction mode. */ @Composable -fun DiarySignInProblem.asText(): String = diaryProblemMessage(this).asText() +fun DiarySignInProblem.asText(firstRun: Boolean = false, inClass: Boolean = false): String = + diaryProblemMessage(this, firstRun = firstRun, inClass = inClass).asText() @Composable private fun DiaryProblemMessage.asText(): String = when (this) { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt index 01a1f52f..ef69f5df 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryScreen.kt @@ -29,12 +29,14 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.lumenpearson.lessons.R import com.lumenpearson.lessons.core.data.repository.DiaryFailure +import com.lumenpearson.lessons.core.data.repository.DiarySessionIdleDays import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryStudent import com.lumenpearson.lessons.core.designsystem.component.AccentIconTile @@ -133,6 +135,9 @@ fun DiaryScreen( // gave it something to say. DiarySignInOutcomeDialog( outcome = state.signInOutcome, + // Drawn as a section only on a phone in a class; the home is the + // diary of a phone in none. + inClass = !asHome, onDismiss = viewModel::consumeSignInOutcome, ) @@ -390,6 +395,7 @@ private fun DiarySavedAtNote(text: String) { @Composable private fun DiarySignInOutcomeDialog( outcome: DiarySignInOutcome?, + inClass: Boolean, onDismiss: () -> Unit, ) { when (outcome) { @@ -408,7 +414,7 @@ private fun DiarySignInOutcomeDialog( title = correctedString(R.string.diary_sign_in_failed_title), // The one mapping, which knows a refused password from a diary // that is down, a throttle and a server that is switched off. - message = outcome.problem.asText(), + message = outcome.problem.asText(inClass = inClass), confirmLabel = correctedString(R.string.diary_dialog_dismiss), onDismiss = onDismiss, ) @@ -446,10 +452,19 @@ internal fun DiarySignOutSheet( onDismissRequest = onDismiss, title = correctedString(R.string.diary_sign_out_title), ) { + // On the home the sheet says what the server does, and so has to say + // what it does when the phone cannot tell it: the sign-out is local + // first (`DiaryRepository.signOut`), and a goodbye that never arrives + // leaves the session to the idle purge — with a «Сетевой город» one + // kept open until then. The privacy policy says the same; a sheet that + // promised the forgetting outright was false in airplane mode. + val days = DiarySessionIdleDays.toInt() Text( - text = correctedString( - if (leavesTheApp) R.string.diary_sign_out_home_text else R.string.diary_sign_out_message, - ), + text = if (leavesTheApp) { + pluralStringResource(R.plurals.diary_sign_out_home, days, days) + } else { + correctedString(R.string.diary_sign_out_message) + }, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = ScreenPadding), diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index da37c767..d374e5fb 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -188,6 +188,8 @@ class DiaryViewModel( binding: Flow = flowOf(null), private val describe: suspend (DiaryTarget) -> DiaryPlace? = { null }, private val clock: Clock = Clock.systemUTC(), + /** The shell's hold: the first run owns the screen; see [onboarding]. */ + held: Flow = flowOf(false), ) : ViewModel() { private val state = MutableStateFlow( @@ -211,6 +213,22 @@ class DiaryViewModel( private var storedTarget: DiaryTarget? = null private var boundTarget: DiaryTarget? = null + /** + * The first run holds the screen, and its import is the one reading the + * diary — pupils included. + * + * This view model is the activity's, so one made by an earlier diary home + * (or by «Настройки → Дневник» on a class phone) is still collecting when a + * later first run signs in. It used to take that session for its own: it + * read the pupils, wrote the first of two as the stored choice — the key + * the import asks before it offers its chooser, so a family with two + * children was never asked — and kept that child in memory even when the + * chooser won, so the home opened on the pupil nobody picked. While held + * it loads nothing; on the release it reads the pupils and the choice the + * import stored, as a home opened for the first time would. + */ + private var onboarding = false + init { viewModelScope.launch { repository.session.collect { session -> @@ -250,7 +268,19 @@ class DiaryViewModel( ) } settleTarget() - if (session != null && state.value.students.isEmpty()) loadStudents() + if (session != null && state.value.students.isEmpty() && !onboarding) loadStudents() + } + } + viewModelScope.launch { + held.distinctUntilChanged().collect { holding -> + onboarding = holding + if (holding) { + // What an earlier session left running is not the new one's. + loadJob?.cancel() + state.update { it.copy(students = emptyList(), selectedStudentId = null, studentsLoading = false) } + } else if (state.value.session != null && state.value.students.isEmpty()) { + loadStudents() + } } } viewModelScope.launch { @@ -847,6 +877,7 @@ class DiaryViewModel( cache = container.diaryCache, binding = container.sessionRepository.session.map { it?.diary }, describe = { target -> diaryPlaceOf(container.regionLookup.catalog(), target) }, + held = container.shellMode.state.map { it.held }, ) } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt index 06a0b684..7801f57b 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinScreen.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.ui.join +import androidx.activity.compose.BackHandler import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Column @@ -82,9 +83,9 @@ import com.lumenpearson.lessons.ui.onboarding.OnboardingActions * * @param onBack the first run's way back to the chooser. `null` where there is * nothing behind the screen, so the square is absent rather than dead. - * @param onJoined the class just joined, once per join; the first run decides - * there whether the class's diary is offered next. `AddClassSheet` passes - * nothing and keeps its own reading of the one-shot. + * @param onJoined the class just joined, once per join this screen started; + * the first run decides there whether the class's diary is offered next. + * `AddClassSheet` reads the same one-shot through [rememberJoinSubmit]. */ @Composable fun JoinScreen( @@ -95,20 +96,15 @@ fun JoinScreen( ) { val state by viewModel.uiState.collectAsStateWithLifecycle() var showServerSheet by rememberSaveable { mutableStateOf(false) } - val joined by rememberUpdatedState(onJoined) + val submit = rememberJoinSubmit(viewModel, state.joined) { classId -> onJoined?.invoke(classId) } - // A one-shot belongs to whoever sees it first, and this screen sees it - // first. It hands it to [onJoined] when there is one — the first run — and - // consumes it either way, because leaving it set hands the next observer - // somebody else's join. `AddClassSheet` resolves the same view model - // against the Activity's store, so a class joined during onboarding was - // still announced when «Добавить класс» was opened an hour later, and the - // sheet dismissed itself before the user could type a second code. - LaunchedEffect(state.joinedClassId) { - val classId = state.joinedClassId ?: return@LaunchedEffect - joined?.invoke(classId) - viewModel.consumeJoined() - } + // Back is held while the code is out. The join cannot be called back — + // the server has the code — so leaving let it land under whatever came + // next: the first run's chooser, which then offered «Найти свою школу» to + // a family whose class, with its own diary, had just been joined behind + // it. Taken rather than disabled, so the gesture does not fall through to + // the flow's own handler; composed after that one, so it is asked first. + BackHandler(enabled = onBack != null && state.isSubmitting) {} if (showServerSheet) { ServerUrlSheet( @@ -178,7 +174,7 @@ fun JoinScreen( error = state.error, enabled = !state.isSubmitting, onCodeChange = viewModel::onCodeChange, - onSubmit = viewModel::submit, + onSubmit = submit, ) Spacer(Modifier.height(GroupSpacing)) @@ -210,12 +206,42 @@ fun JoinScreen( onBack = onBack, enabled = state.canSubmit, busy = state.isSubmitting, - onClick = viewModel::submit, + onClick = submit, ) } } } +/** + * The caller's half of [JoinViewModel.submit]: the submit to wire to its + * button, and [onJoined] once for the join that submit started. + * + * The view model is the activity's and its one-shot outlives every screen that + * reads it, so a join is acted on only by the caller holding its ticket — kept + * saveable, so a rotation between the press and the answer still finds it. A + * join somebody else started is consumed and dropped: its caller was disposed + * before it reported (the shell swaps on the session, which the join writes + * before its first sync), and nobody else has any use for it. + */ +@Composable +internal fun rememberJoinSubmit( + viewModel: JoinViewModel, + joined: JoinedClass?, + onJoined: (classId: Long) -> Unit, +): () -> Unit { + var ticket by rememberSaveable { mutableStateOf(null) } + val latest by rememberUpdatedState(onJoined) + LaunchedEffect(joined) { + val landed = joined ?: return@LaunchedEffect + viewModel.consumeJoined(landed) + if (landed.ticket == ticket) { + ticket = null + latest(landed.classId) + } + } + return { viewModel.submit()?.let { ticket = it } } +} + /** * The three rows that say what a class code actually buys. * diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt index f2555025..fff904d8 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/join/JoinViewModel.kt @@ -13,6 +13,7 @@ import com.lumenpearson.lessons.core.data.repository.SessionRepository import com.lumenpearson.lessons.core.data.repository.SettingsRepository import com.lumenpearson.lessons.core.data.repository.TimetableRepository import com.lumenpearson.lessons.ui.common.ClassCodeLengths +import java.util.UUID import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -118,7 +119,7 @@ data class JoinUiState( val isSubmitting: Boolean = false, val error: JoinError? = null, /** - * The class just joined, until somebody consumes it. + * The join that just finished, until somebody consumes it. * * Joining writes a session, and outside the first run the shell navigates * on the session. Two callers need more than that. The «Добавить класс» @@ -130,22 +131,43 @@ data class JoinUiState( * class already on screen is a real case — it is how somebody whose device * was revoked gets back in — and it leaves the active class exactly as it * was while having plainly succeeded. + * + * Only the caller holding [JoinedClass.ticket] may act on it; see + * [JoinViewModel.submit]. */ - val joinedClassId: Long? = null, + val joined: JoinedClass? = null, ) { /** The button is only live for a complete code with no request running. */ val canSubmit: Boolean get() = code.length in ClassCodeLengths && !isSubmitting } +/** + * A finished join, and the ticket of the [JoinViewModel.submit] that started it. + * + * @property ticket what that call returned; a caller acts on a join only when + * the ticket is the one it was handed. + */ +data class JoinedClass(val ticket: String, val classId: Long) + /** * The join screen's state, for the first run's class-code step and the * «Добавить класс» sheet alike. * - * Success is reported as a one-shot ([JoinUiState.joinedClassId]) rather than a + * Success is reported as a one-shot ([JoinUiState.joined]) rather than a * callback held by this view model: it is resolved against the activity's * store and outlives either screen, and a callback kept here would outlive the * screen that passed it. * + * The one-shot outlives the screen too, which is why it carries a ticket. The + * join writes the session before its first sync, and the session is what swaps + * the shell — so the screen that pressed «Подключиться» is usually gone by the + * time the join reports (the first run's join screen on a class with no diary, + * the «Добавить класс» sheet on the diary home), and the report used to wait + * for whoever came next. That was the class-code step of a later first run, + * which took it for its own join and finished a flow with no class in it, or + * the next «Добавить класс» sheet, which closed itself before anything could + * be typed. + * * @param deviceName sent with the join request so a teacher can tell one pupil's * phone from another in the class admin panel. */ @@ -159,7 +181,7 @@ class JoinViewModel( private val code = MutableStateFlow("") private val submitting = MutableStateFlow(false) private val error = MutableStateFlow(null) - private val joined = MutableStateFlow(null) + private val joined = MutableStateFlow(null) val uiState: StateFlow = combine( code, @@ -167,13 +189,13 @@ class JoinViewModel( error, joined, settingsRepository.settings.map { it.baseUrl }, - ) { code, isSubmitting, error, joinedClassId, baseUrl -> + ) { code, isSubmitting, error, joined, baseUrl -> JoinUiState( code = code, baseUrl = baseUrl, isSubmitting = isSubmitting, error = error, - joinedClassId = joinedClassId, + joined = joined, ) }.stateIn( scope = viewModelScope, @@ -201,14 +223,24 @@ class JoinViewModel( } } - /** Sends the code. The result reaches the UI as a session, or as an error. */ - fun submit() { + /** + * Sends the code. The result reaches the UI as a session, or as an error. + * + * Returns the ticket this join will report under in [JoinUiState.joined], + * or `null` when nothing was sent — a code of the wrong length, or a join + * already running. The caller keeps it (across a rotation, too) and acts + * only on a join carrying it. + */ + fun submit(): String? { val value = code.value if (value.length !in ClassCodeLengths) { error.value = JoinError.InvalidCode - return + return null } - if (submitting.value) return + if (submitting.value) return null + // Random rather than counted: a caller's saved ticket survives a + // process death that restarts any counter at zero. + val ticket = UUID.randomUUID().toString() viewModelScope.launch { submitting.value = true @@ -229,15 +261,23 @@ class JoinViewModel( // has just this second joined a class. timetableRepository.refresh() submitting.value = false + // The code has been spent. Cleared here rather than by the caller, + // which may have been disposed with the shell it was drawn in, and + // would leave the next «Добавить класс» sheet opening on it. + code.value = "" // Last, so that whoever is watching for it sees a finished join // rather than one still fetching its first week. - joined.value = result.getOrNull()?.classId + joined.value = result.getOrNull()?.let { JoinedClass(ticket, it.classId) } } + return ticket } - /** Clears the one-shot in [JoinUiState.joinedClassId]. */ - fun consumeJoined() { - joined.value = null + /** + * Clears the one-shot, if it is still [landed] — a join that reported + * after it was read is not thrown away with it. + */ + fun consumeJoined(landed: JoinedClass) { + joined.compareAndSet(landed, null) } companion object { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt index 869f2071..12040899 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportPage.kt @@ -77,25 +77,32 @@ internal fun ImportPage(viewModel: OnboardingViewModel) { } val failed = ui.failed + val action = importActionOf(ui) StepScaffold( actions = { - when { - ui.done != null -> OnboardingActions( + when (action) { + ImportAction.CONTINUE -> OnboardingActions( label = correctedString(R.string.onboarding_action_continue), icon = Icons.AutoMirrored.Rounded.ArrowForward, onClick = viewModel::importShown, ) - failed != null && failed.needsSignIn -> OnboardingActions( + ImportAction.SIGN_IN_AGAIN -> OnboardingActions( label = correctedString(R.string.onboarding_import_sign_in_again), icon = Icons.AutoMirrored.Rounded.ArrowForward, onClick = viewModel::signInAgain, ) - failed != null -> OnboardingActions( + ImportAction.RETRY -> OnboardingActions( label = correctedString(R.string.onboarding_action_retry), icon = Icons.Rounded.Refresh, onClick = viewModel::retryImport, ) - else -> OnboardingActions( + // The way out below the card becomes the one action. + ImportAction.START_OVER -> OnboardingActions( + label = correctedString(R.string.onboarding_import_restart), + icon = Icons.AutoMirrored.Rounded.ArrowForward, + onClick = viewModel::startOver, + ) + ImportAction.RUNNING -> OnboardingActions( label = correctedString(R.string.onboarding_import_running), icon = Icons.Rounded.CloudDownload, busy = true, @@ -150,11 +157,13 @@ internal fun ImportPage(viewModel: OnboardingViewModel) { if (failed.needsSignIn) { correctedString(R.string.onboarding_import_expired) } else { - correctedString(R.string.onboarding_import_failed, failed.problem.asText()) + correctedString(R.string.onboarding_import_failed, failed.problem.asText(firstRun = true)) }, ) - TextButton(onClick = viewModel::startOver, modifier = Modifier.fillMaxWidth()) { - Text(correctedString(R.string.onboarding_import_restart)) + if (action != ImportAction.START_OVER) { + TextButton(onClick = viewModel::startOver, modifier = Modifier.fillMaxWidth()) { + Text(correctedString(R.string.onboarding_import_restart)) + } } } Spacer(Modifier.height(24.dp)) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt index 146b5a24..830f6cca 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ImportRunner.kt @@ -6,6 +6,7 @@ import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.ui.diary.offersRetry import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -58,6 +59,36 @@ data class ImportUi( val failed: ImportFailure? = null, ) +/** The import screen's one action, by what the import is doing. */ +enum class ImportAction { + RUNNING, + CONTINUE, + + /** The diary ended the session: a new sign-in continues. */ + SIGN_IN_AGAIN, + + /** «Повторить»: the failure is one a second try can get past. */ + RETRY, + + /** + * «Выйти из дневника и начать заново» and nothing else: a retry would meet + * the same answer — an account with no pupil, a diary that refuses our + * server's address (#153's rule, as `offersRetry` has it elsewhere). + */ + START_OVER, +} + +fun importActionOf(ui: ImportUi): ImportAction { + val failed = ui.failed + return when { + ui.done != null -> ImportAction.CONTINUE + failed == null -> ImportAction.RUNNING + failed.needsSignIn -> ImportAction.SIGN_IN_AGAIN + failed.problem.offersRetry -> ImportAction.RETRY + else -> ImportAction.START_OVER + } +} + /** One row of the import screen. */ enum class StageState { WAITING, RUNNING, DONE, SKIPPED, FAILED } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt index db4809df..34df34c5 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalog.kt @@ -10,6 +10,7 @@ import com.lumenpearson.lessons.core.data.repository.DiaryBinding import com.lumenpearson.lessons.core.data.repository.DiaryProviderKey import com.lumenpearson.lessons.core.data.repository.DiaryTarget import com.lumenpearson.lessons.ui.diary.httpsHostOf +import java.util.Locale /* * The region, school and provider steps, read out of the bundled catalog into @@ -207,17 +208,31 @@ fun regionRowOf(catalog: RegionCatalog, region: CatalogRegion, via: MatchVia = M ) /** - * The search hands back the words it matched folded (lower case, ё as е); the - * row names the city as the catalog spells it. + * The search hands back the words it matched normalised — folded (lower case, + * ё as е, a dash a space) and without the region-type words, so «Читинская + * область» comes back as «читинская»; the row names the city or the alias as + * the catalog spells it, by normalising each candidate the same way. */ -private fun original(catalog: RegionCatalog, candidates: List, folded: String): String = - candidates.firstOrNull { fold(catalog, it) == fold(catalog, folded) } ?: folded +private fun original(catalog: RegionCatalog, candidates: List, matched: String): String { + val words = matched.split(' ').filter { it.isNotEmpty() } + val stop = catalog.search.stopWords.flatMap { tokens(catalog, it) }.toSet() + return candidates.firstOrNull { candidate -> tokens(catalog, candidate).filter { it !in stop } == words } ?: matched +} -/** The search's own folding, from the catalog's table: no Cyrillic is written in Kotlin. */ -private fun fold(catalog: RegionCatalog, text: String): String { +/** + * `RegionSearch.normalise`'s tokens, from the catalog's own table (no Cyrillic + * is written in Kotlin): lower case, folded, anything but a letter or a digit + * a space. That function is internal to `:core:data`, which is why this is a + * copy of its loop rather than a call. + */ +private fun tokens(catalog: RegionCatalog, text: String): List { val table = catalog.search.fold - return text.lowercase().map { char -> table[char.toString()] ?: char.toString() }.joinToString("") - .split(' ').filter { it.isNotBlank() }.joinToString(" ") + val folded = buildString { + for (char in text.lowercase(Locale.ROOT)) { + for (c in table[char.toString()] ?: char.toString()) append(if (c.isLetterOrDigit()) c else ' ') + } + } + return folded.split(' ').filter { it.isNotEmpty() } } /** diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt index fa6e8869..2939bfe4 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingParts.kt @@ -106,7 +106,10 @@ internal fun OnboardingActions( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - if (onBack != null) BackSquare(onBack) + // Dead while [busy]: what is running was sent and will land + // whether or not the step is left, and it would land behind the + // step before — the class-code step's join under the chooser. + if (onBack != null) BackSquare(onBack, enabled = !busy) Button( onClick = { @@ -151,26 +154,27 @@ internal fun OnboardingActions( * because the password must not leave the form to reach a button out here. */ @Composable -internal fun OnboardingBackRow(onBack: () -> Unit, modifier: Modifier = Modifier) { +internal fun OnboardingBackRow(onBack: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true) { Row( modifier = modifier .fillMaxWidth() .navigationBarsPadding() .padding(ScreenPadding), ) { - BackSquare(onBack) + BackSquare(onBack, enabled) } } /** The square way back, the same on every step. */ @Composable -private fun BackSquare(onBack: () -> Unit) { +private fun BackSquare(onBack: () -> Unit, enabled: Boolean = true) { val view = rememberHapticView() OutlinedButton( onClick = { LessonsHaptics.press(view) onBack() }, + enabled = enabled, modifier = Modifier.size(ActionHeight), shape = MaterialTheme.shapes.large, contentPadding = PaddingValues(0.dp), diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt index 9a2f439f..1562ef53 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingScreen.kt @@ -137,7 +137,13 @@ fun OnboardingScreen( // once — so two back events drained in one input pass both see it // true. Reachable by tapping back twice during the slide, which is // exactly where this screen is slowest. - BackHandler(enabled = state.canGoBack) { viewModel.back() } + // + // While the sign-in is under way the gesture is taken and does nothing + // (`back()` refuses then too): left alone at the floor it would finish + // the activity, and cancel a registration our server completes anyway. + val signingIn by viewModel.signIn.state.collectAsStateWithLifecycle() + val busy = state.current == OnboardingStep.SIGN_IN && signingIn.busy + BackHandler(enabled = state.canGoBack || busy) { viewModel.back() } val onBack: (() -> Unit)? = if (state.canGoBack) viewModel::back else null Column(modifier = Modifier.fillMaxSize()) { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt index ed09cc49..f482edcf 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModel.kt @@ -114,7 +114,8 @@ data class SummaryUi( * keep the flow on screen, because the join and the registration each write a * credential that would otherwise swap the flow for a home mid-way; [finish] * releases it. After a process death with no saved state, [start] resumes by - * [OnboardingFlow.resume]. + * [OnboardingFlow.resume]; with saved state, by the saved path squared with + * the credentials stored since ([reconciled]). */ class OnboardingViewModel( private val saved: SavedStateHandle, @@ -181,11 +182,17 @@ class OnboardingViewModel( */ fun start(introduced: Boolean) { if (mutable.value != null && !finished) return + // The step holders live as long as this view model, and a finished + // flow left its answers in them: the next first run — after «Выйти из + // дневника», say — opened on the old region's rows and on a sign-in + // form holding the login that sign-out had just forgotten. Only after + // a finish: a first start keeps what a recreation left in memory. + if (finished) forgetFinishedFlow() finished = false generation += 1 mutable.value = null - onboardingStateOf(OnboardingKeys.all.associateWith { saved.get(it) })?.let { - mutable.value = it + onboardingStateOf(OnboardingKeys.all.associateWith { saved.get(it) })?.let { restored -> + viewModelScope.launch { reconciled(restored)?.let(::set) ?: finish() } return } viewModelScope.launch { @@ -203,6 +210,15 @@ class OnboardingViewModel( } } + private fun forgetFinishedFlow() { + signIn.reset() + region.reset() + school.reset() + header.value = null + summaryState.value = null + target = null + } + // --- The introduction and the chooser ------------------------------------------------- /** The introduction's own «next»: the steps run in order up to the chooser. */ @@ -233,10 +249,19 @@ class OnboardingViewModel( viewModelScope.launch { deps.settings.update { it.copy(baseUrl = url) } } } + /** + * One step back. Refused on the sign-in while it is under way: once the + * password has gone, our server may be adopting the session, and leaving + * would keep a server row whose bearer nobody is left to hear — a + * credential no sign-out can reach, and a second one with the next try. + */ fun back() { val state = mutable.value ?: return if (!state.canGoBack) return - if (state.current == OnboardingStep.SIGN_IN) signIn.abandon() + if (state.current == OnboardingStep.SIGN_IN) { + if (signIn.state.value.busy) return + signIn.abandon() + } set(OnboardingFlow.back(state)) } @@ -310,18 +335,39 @@ class OnboardingViewModel( fun onJoined() { viewModelScope.launch { val state = mutable.value ?: return@launch - val usable = classTargetOf(catalog(), deps.currentClass()?.diary) != null - if (usable && deps.currentDiary() == null) { - set( - OnboardingFlow.commit(state, OnboardingStep.SIGN_IN) - .let { it.copy(choices = it.choices.copy(classBound = true)) }, - ) - } else { - finish() - } + afterJoin(state)?.let(::set) ?: finish() } } + /** Where a joined class leaves [state]: its diary's sign-in, or `null` for «done». */ + private suspend fun afterJoin(state: OnboardingState): OnboardingState? { + val usable = classTargetOf(catalog(), deps.currentClass()?.diary) != null + if (!usable || deps.currentDiary() != null) return null + return OnboardingFlow.commit(state, OnboardingStep.SIGN_IN) + .let { it.copy(choices = it.choices.copy(classBound = true)) } + } + + /** + * A saved flow, squared with the credentials stored since it was saved. + * + * The bundle is written when the activity stops, and a join or a + * registration still under way then lands after it: its commit reaches + * the in-memory handle only. After a process death the saved path would + * reopen the join screen over a class already joined, or the sign-in form + * over a diary already registered — where a second sign-in would orphan + * the first server row. So the stored credential wins: a join goes on as + * [onJoined] would, a registration on to its import. A sign-in reopened + * after an import the diary ended ([OnboardingChoices.resumeFrom]) started + * with a session stored, so a stored one proves nothing there. + */ + private suspend fun reconciled(restored: OnboardingState): OnboardingState? = when { + restored.current == OnboardingStep.CLASS_CODE && deps.currentClass() != null -> afterJoin(restored) + restored.current == OnboardingStep.SIGN_IN && + restored.choices.resumeFrom == null && + deps.currentDiary() != null -> OnboardingFlow.commit(restored, OnboardingStep.IMPORT) + else -> restored + } + // --- Sign-in -------------------------------------------------------------------------- fun submitSignIn(password: String) { @@ -331,8 +377,13 @@ class OnboardingViewModel( fun retrySignIn() = signIn.retry(onRegistered = ::registered) - /** «Не сейчас» on a class's diary: the class is joined, and the diary can wait for settings. */ + /** + * «Не сейчас» on a class's diary: the class is joined, and the diary can + * wait for settings. Refused while the sign-in is under way, for [back]'s + * reason. + */ fun skipSignIn() { + if (signIn.state.value.busy) return signIn.abandon() finish() } @@ -370,8 +421,14 @@ class OnboardingViewModel( * «Выйти из дневника и начать заново»: best-effort sign-out, then the * chooser — or, on a class's diary, the end of the flow, since the class is * still there to go home to. + * + * Offered by the import and by a sign-in with no way back (one reopened + * after an import the diary ended), which is why it leaves the sign-in the + * way [back] does — and, like it, not while a sign-in is under way. */ fun startOver() { + if (signIn.state.value.busy) return + signIn.abandon() viewModelScope.launch { importing.stop() deps.signOutDiary() @@ -477,14 +534,23 @@ class OnboardingViewModel( if (signIn.state.value.login.isBlank() && stored?.provider == chosen.provider) { signIn.setLogin(stored.login) } - val system = catalog.region(choices.region)?.let { region -> choices.system?.let(region.systems::getOrNull) } + // The picked system's own site only when the form really signs in to + // it. A class's diary, or the stored one, can differ from a system + // picked earlier and walked back from — and «Забыли пароль?» must not + // send a parent to reset a password in another region's diary. + val signsInToPicked = !choices.classBound && picked != null + val pickedSite = if (signsInToPicked) { + catalog.region(choices.region)?.let { region -> choices.system?.let(region.systems::getOrNull) }?.webUrl + } else { + null + } header.value = SignInHeader( provider = chosen.provider, place = diaryPlaceOf(catalog, chosen), schoolName = chosen.schoolName, classBound = choices.classBound, className = if (choices.classBound) cls?.className else null, - forgotUrl = (system?.webUrl ?: forgotUrlOf(catalog, chosen))?.takeIf { it.startsWith("https://") }, + forgotUrl = (pickedSite ?: forgotUrlOf(catalog, chosen))?.takeIf { it.startsWith("https://") }, ) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt index 88b15bbf..6edf98fa 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/ProviderStep.kt @@ -367,7 +367,10 @@ fun whyLines( WhyReason.FRONT_END -> WhyLine(R.string.onboarding_why_front_end, listOf(region, system, mainSystem ?: system)) WhyReason.MOVING_TO -> WhyLine(R.string.onboarding_why_moving_to, listOf(region, system)) - WhyReason.UNREACHABLE -> WhyLine(R.string.onboarding_why_unreachable, listOf(region, system)) + // The generator recommends the unreachable diary itself here + // (nothing else is the region's), so the sentence names no system + // as the answer: it says why this one cannot be opened. + WhyReason.UNREACHABLE -> WhyLine(R.string.onboarding_why_unreachable, listOf(region)) WhyReason.UNSUPPORTED -> WhyLine(R.string.onboarding_why_unsupported, listOf(region, system)) WhyReason.NO_DIARY -> WhyLine(R.string.onboarding_why_no_diary, listOf(region, year)) }, diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt index 972d407b..e7b84173 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionFinder.kt @@ -17,8 +17,17 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -/** Why the school-name search said nothing useful. Every one ends in «выберите регион из списка». */ -enum class DirectoryFailure { WAIT, NO_SERVER, OFFLINE, OFF } +/** + * Why the school-name search said nothing useful. Every one ends in «выберите + * регион из списка». + * + * [OFF] is for a server that cannot search at all — no key, or too old to + * have the directory — and says so for good. [DOWN] is the directory failing + * this once (DaData slow or refusing, an answer nobody could read), and says + * «сейчас»: telling a family the search does not work here, a minute before + * it does, is telling them not to try the name again. + */ +enum class DirectoryFailure { WAIT, NO_SERVER, OFFLINE, OFF, DOWN } /** What the directory said about the name typed, if it was asked. */ sealed interface SchoolAnswer { @@ -101,6 +110,13 @@ class RegionFinder( } } + /** Nothing typed and nothing asked, for a flow that starts again. */ + fun reset() { + nameJob?.cancel() + schoolJob?.cancel() + mutable.value = RegionSearchUi() + } + /** The keyboard's search key: ask now rather than after the pause. */ fun submit() { val query = mutable.value.query @@ -120,7 +136,7 @@ class RegionFinder( current.copy( searching = false, rows = result?.byName?.map { match -> regionRowOf(book, match) } ?: current.rows, - school = result?.bySchool?.let(::answerOf) ?: SchoolAnswer.Failed(DirectoryFailure.OFF), + school = result?.bySchool?.let(::answerOf) ?: SchoolAnswer.Failed(DirectoryFailure.DOWN), ) } } @@ -148,7 +164,8 @@ fun answerOf(lookup: SchoolLookup): SchoolAnswer = when (lookup) { is DirectoryProblem.Spent -> SchoolAnswer.Failed(DirectoryFailure.WAIT, minutesOf(problem.retryAfterSeconds)) DirectoryProblem.ServerMissing -> SchoolAnswer.Failed(DirectoryFailure.NO_SERVER) DirectoryProblem.Offline -> SchoolAnswer.Failed(DirectoryFailure.OFFLINE) - else -> SchoolAnswer.Failed(DirectoryFailure.OFF) + DirectoryProblem.Disabled, DirectoryProblem.ServerTooOld -> SchoolAnswer.Failed(DirectoryFailure.OFF) + else -> SchoolAnswer.Failed(DirectoryFailure.DOWN) } } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt index bd5ca840..88bde362 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/RegionStep.kt @@ -151,6 +151,7 @@ private fun androidx.compose.foundation.lazy.LazyListScope.schoolAnswer( DirectoryFailure.NO_SERVER -> correctedString(R.string.onboarding_region_school_no_server) DirectoryFailure.OFFLINE -> correctedString(R.string.onboarding_region_school_offline) DirectoryFailure.OFF -> correctedString(R.string.onboarding_region_school_off) + DirectoryFailure.DOWN -> correctedString(R.string.onboarding_region_school_down) }, ) } @@ -279,7 +280,7 @@ internal fun SchoolStep( val problem = search.problem ?: return@item EmptyState( title = correctedString(R.string.diary_failure_title), - description = problem.asText(), + description = problem.asText(firstRun = true), actionLabel = correctedString(R.string.onboarding_action_retry).takeIf { problem.offersRetry }, onActionClick = viewModel.school::retry.takeIf { problem.offersRetry }, ) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt index bc502401..0c8becc9 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SchoolFinder.kt @@ -44,14 +44,33 @@ class SchoolFinder( private var job: Job? = null - /** A region picked: start over, with the query the region step carried, asked at once. */ + /** The prefill the search last started from; see [open]. */ + private var openedWith: String? = null + + /** + * A region picked: start over, with the query the region step carried, + * asked at once. + * + * Arriving again with the same region and the same prefill — back from + * the provider step — keeps what was typed here since. A new school name + * carried from the region step is a new question, even in the same region. + */ fun open(regionKey: String, prefill: String) { - if (mutable.value.regionKey == regionKey && mutable.value.query.isNotEmpty()) return + val current = mutable.value + if (current.regionKey == regionKey && openedWith == prefill && current.query.isNotEmpty()) return + openedWith = prefill job?.cancel() mutable.value = SchoolSearchUi(regionKey = regionKey, query = prefill) search(prefill, debounce = false) } + /** Nothing typed and nothing asked, for a flow that starts again. */ + fun reset() { + job?.cancel() + openedWith = null + mutable.value = SchoolSearchUi() + } + fun type(query: String) { mutable.update { it.copy(query = query) } search(query, debounce = true) diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt index f816a923..c886bc65 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInPage.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.ui.onboarding +import android.content.Context import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -14,8 +15,10 @@ import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material3.MaterialTheme import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier @@ -55,6 +58,9 @@ import com.lumenpearson.lessons.ui.diary.systemName * what can be done about it stays on the page after the pop-up is gone: * re-sending the held session without the password, setting the server, the * class code, or the Госуслуги page in the browser. + * + * The way out is [signInExitOf]'s, and it is held while a sign-in is under + * way (see [OnboardingViewModel.back]). */ @Composable internal fun SignInPage( @@ -65,6 +71,7 @@ internal fun SignInPage( val ui by viewModel.signIn.state.collectAsStateWithLifecycle() val baseUrl by viewModel.baseUrl.collectAsStateWithLifecycle() val context = LocalContext.current + val links = remember(context) { BrowserLinks(context) } var editingServer by rememberSaveable { mutableStateOf(false) } val current = header val problem = ui.problem @@ -83,23 +90,28 @@ internal fun SignInPage( if (ui.dialog && problem != null) { LessonsDialog( title = correctedString(R.string.diary_sign_in_failed_title), - message = problem.asText(), + // The first run's wording: no settings exist yet, and a family that + // came through its class is not advised to join one. + message = problem.asText(firstRun = true, inClass = current?.classBound == true), confirmLabel = correctedString(R.string.diary_dialog_dismiss), onDismiss = viewModel.signIn::dismissDialog, ) } + val exit = signInExitOf(classBound = current?.classBound == true, canGoBack = onBack != null) StepScaffold( actions = { - when { - current?.classBound == true -> OnboardingActions( + when (exit) { + SignInExit.SKIP -> OnboardingActions( label = correctedString(R.string.onboarding_sign_in_skip), icon = Icons.AutoMirrored.Rounded.ArrowForward, onBack = onBack, enabled = !ui.busy, onClick = viewModel::skipSignIn, ) - onBack != null -> OnboardingBackRow(onBack = onBack) + SignInExit.BACK -> onBack?.let { OnboardingBackRow(onBack = it, enabled = !ui.busy) } + // In the page, under the form, as the import page has it. + SignInExit.START_OVER -> Unit } }, ) { @@ -110,6 +122,7 @@ internal fun SignInPage( Spacer(Modifier.height(8.dp)) if (current == null) { NoteCard(correctedString(R.string.onboarding_sign_in_no_target)) + if (exit == SignInExit.START_OVER) StartOverButton(enabled = !ui.busy, onClick = viewModel::startOver) return@Column } val system = current.place.systemName().orEmpty() @@ -181,15 +194,26 @@ internal fun SignInPage( onRetry = viewModel::retrySignIn, onServer = { editingServer = true }, onClassCode = viewModel::toClassCode, - onOpen = { url -> openInBrowser(context, url) }, + onOpen = links::open, ) } current.forgotUrl?.let { url -> - TextButton(onClick = { openInBrowser(context, url) }, modifier = Modifier.fillMaxWidth()) { + TextButton(onClick = { links.open(url) }, modifier = Modifier.fillMaxWidth()) { Text(correctedString(R.string.onboarding_sign_in_forgot)) } } + // The handoff sheet's own sentence: a tap that opened nothing + // must not read as a button that does nothing. + if (links.failed) { + Text( + text = correctedString(R.string.onboarding_handoff_no_browser), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + + if (exit == SignInExit.START_OVER) StartOverButton(enabled = !ui.busy, onClick = viewModel::startOver) // The server that will hold the session, named where the session is // about to be sent to it. @@ -211,6 +235,14 @@ internal fun SignInPage( } } +/** «Выйти из дневника и начать заново», drawn as the import page draws it. */ +@Composable +private fun StartOverButton(enabled: Boolean, onClick: () -> Unit) { + TextButton(onClick = onClick, enabled = enabled, modifier = Modifier.fillMaxWidth()) { + Text(correctedString(R.string.onboarding_import_restart)) + } +} + /** What can be done about [problem], as buttons that outlive its pop-up. */ @Composable private fun ProblemActions( @@ -224,7 +256,10 @@ private fun ProblemActions( ) { val handoff = (problem as? DiarySignInProblem.GosuslugiOnly)?.handoffUrl?.takeIf { it.startsWith("https://") } val retry = sessionHeld && problem.retryKeepsSession - val server = problem.action == DiarySignInProblem.Action.SET_SERVER + // No answer from our server is as often a mistyped address as no network, + // and the address is on this page. + val server = problem.action == DiarySignInProblem.Action.SET_SERVER || + problem == DiarySignInProblem.Offline // A class code is the way round a diary that refuses our server — unless a // class is what brought the family here. val code = problem is DiarySignInProblem.ServerRefusedSession && !classBound @@ -260,3 +295,42 @@ private fun ProblemActions( } } } + +/** What leaves the sign-in, other than signing in. */ +internal enum class SignInExit { + /** «Не сейчас»: a class's diary, whose class is joined whatever happens here. */ + SKIP, + + /** The back square, to the step the form was reached from. */ + BACK, + + /** + * «Выйти из дневника и начать заново», the import page's own way out, for + * a sign-in with nothing behind it — one reopened after an import the + * diary ended sits on the floor. Without it a sign-in that keeps failing + * there has no exit short of killing the app. + */ + START_OVER, +} + +internal fun signInExitOf(classBound: Boolean, canGoBack: Boolean): SignInExit = when { + classBound -> SignInExit.SKIP + canGoBack -> SignInExit.BACK + else -> SignInExit.START_OVER +} + +/** + * Opens the diary's pages from the sign-in — «Забыли пароль?» and the + * Госуслуги handoff — and remembers that nothing on the phone could, so the + * page can say so as the handoff sheet does. [openInBrowser] answers `false` + * on a phone with no browser, and a dropped answer is a tap that does nothing. + */ +@Stable +internal class BrowserLinks(private val context: Context) { + var failed by mutableStateOf(false) + private set + + fun open(url: String) { + failed = !openInBrowser(context, url) + } +} diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt index eb472e02..2ee8efd7 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SignInStep.kt @@ -8,11 +8,16 @@ import com.lumenpearson.lessons.core.data.repository.DiaryTarget import com.lumenpearson.lessons.core.data.upstream.UpstreamSession import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.job import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext /** * The diary's session between the phone's sign-in and our server's answer, as @@ -97,6 +102,17 @@ data class SignInUi( * failure that already discarded it, and on [abandon] — leaving the step — * which also says goodbye to it upstream. The password is never a field at * all: it arrives as [submit]'s argument and leaves as [OnboardingSignIn.open]'s. + * + * Once the password has gone to the diary, nothing on this side may drop the + * answer on the floor. [OnboardingSignIn.open] and [OnboardingSignIn.register] + * run to their end even when the step is cancelled: a cancelled `open` may + * still have opened a session upstream, and a cancelled `register` still has + * the whole request on our server, which finishes it and keeps a row whose + * bearer only this phone would ever have been told. A session the diary + * opened after the step was left is discarded; one our server took is stored + * by the registration itself, so the phone holds the only key to that row. + * The view model refuses to leave the step while [SignInUi.busy], so in + * practice only the process ending cancels one of these. */ class SignInStep( private val scope: CoroutineScope, @@ -130,8 +146,18 @@ class SignInStep( mutable.update { it.copy(stage = SignInStage.CHECKING, problem = null, dialog = false, sessionHeld = false) } signIn.preflight(withLogin).onFailure { fail(it); return@launch } mutable.update { it.copy(stage = SignInStage.UPSTREAM) } - val session = signIn.open(withLogin, password).getOrElse { fail(it); return@launch } - held = session + val step = currentCoroutineContext().job + val opened = withContext(NonCancellable) { + signIn.open(withLogin, password).onSuccess { session -> + // Left while the diary was answering: nobody will hold + // this one, so it is ended now rather than left to idle. + // Otherwise it is held before this block returns, so a + // leave landing on the way out finds it in [abandon]. + if (step.isCancelled) signIn.discard(session) else held = session + } + } + currentCoroutineContext().ensureActive() + opened.onFailure { fail(it); return@launch } registerHeld(onRegistered) } } @@ -144,7 +170,9 @@ class SignInStep( /** * Leaving the step: whatever is in flight stops, and a session the server - * never took is ended with the diary rather than left to idle there. + * never took is ended with the diary rather than left to idle there. A + * session out for registration is not [held] (see [registerHeld]), so it + * is never ended upstream under our server while the server adopts it. */ fun abandon() { job?.cancel() @@ -155,22 +183,39 @@ class SignInStep( if (stale != null) scope.launch { signIn.discard(stale) } } + /** + * [abandon], and the login with it: a flow that has finished is over for + * whoever typed it, and the next one may be somebody else's. + */ + fun reset() { + abandon() + mutable.value = SignInUi() + } + private suspend fun registerHeld(onRegistered: () -> Unit) { val session = held ?: return + // Out of [held] while it is out for registration: [abandon] must not + // say goodbye upstream to a session our server may be adopting. + held = null mutable.update { it.copy(stage = SignInStage.REGISTER, problem = null, dialog = false) } - signIn.register(session).fold( + val step = currentCoroutineContext().job + val outcome = withContext(NonCancellable) { + signIn.register(session).onFailure { failure -> + // `register` has already discarded a session it will not see + // again; holding it here would offer a retry that cannot work. + if (!problemOf(failure).retryKeepsSession) return@onFailure + // Left while our server was answering, and it did not keep + // the session: nobody is left to retry it, so it is ended. + if (step.isCancelled) signIn.discard(session) else held = session + } + } + currentCoroutineContext().ensureActive() + outcome.fold( onSuccess = { - held = null mutable.update { it.copy(stage = null, problem = null, dialog = false, sessionHeld = false) } onRegistered() }, - onFailure = { failure -> - val problem = problemOf(failure) - // `register` has already discarded a session it will not see - // again; holding it here would offer a retry that cannot work. - if (!problem.retryKeepsSession) held = null - fail(problem) - }, + onFailure = ::fail, ) } diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt index f721f341..8ba22495 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/onboarding/SummaryPage.kt @@ -1,6 +1,7 @@ package com.lumenpearson.lessons.ui.onboarding import androidx.activity.compose.BackHandler +import androidx.annotation.PluralsRes import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons @@ -99,17 +100,7 @@ internal fun SummaryPage( icon = Icons.AutoMirrored.Rounded.MenuBook, tone = accentTone(2), ) - GroupItem( - title = pluralStringResource( - R.plurals.onboarding_summary_keepalive, - DiarySessionIdleDays.toInt(), - DiarySessionIdleDays.toInt(), - ), - subtitle = correctedString(R.string.onboarding_summary_petersburg_note) - .takeIf { current.petersburg }, - icon = Icons.Rounded.Timer, - tone = accentTone(4), - ) + KeepAliveItem(inClass = current.inClass, petersburg = current.petersburg) } Spacer(Modifier.height(GroupSpacing)) @@ -174,3 +165,34 @@ internal fun SummaryPage( Spacer(Modifier.height(24.dp)) } } + +/** + * What keeping the diary's sign-in costs (G8), under a short title. + * + * The sentence is the subtitle, which wraps: a row's title is one line that + * scrolls when it does not fit, and two sentences of warning crawling past + * one line at a time is a warning nobody reads. + */ +@Composable +internal fun KeepAliveItem(inClass: Boolean, petersburg: Boolean) { + val days = DiarySessionIdleDays.toInt() + GroupItem( + title = correctedString(R.string.onboarding_summary_keepalive_title), + subtitle = listOfNotNull( + pluralStringResource(keepAliveText(inClass), days, days), + correctedString(R.string.onboarding_summary_petersburg_note).takeIf { petersburg }, + ).joinToString(" "), + icon = Icons.Rounded.Timer, + tone = accentTone(4), + ) +} + +/** + * Which sentence says what keeps the sign-in. Only a diary read moves the + * server's idle clock, and the one read nobody presses for is the diary + * home's refresh on start: a phone in a class opens on the class's timetable, + * and there it is opening the diary — «Настройки → Дневник» — that counts. + */ +@PluralsRes +internal fun keepAliveText(inClass: Boolean): Int = + if (inClass) R.plurals.onboarding_summary_keepalive_class else R.plurals.onboarding_summary_keepalive diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ClassRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ClassRows.kt index 972c80ab..a29c8341 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ClassRows.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/settings/ClassRows.kt @@ -1,5 +1,6 @@ package com.lumenpearson.lessons.ui.settings +import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -21,7 +22,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment @@ -44,6 +44,7 @@ import com.lumenpearson.lessons.core.designsystem.theme.emphasised import com.lumenpearson.lessons.core.designsystem.theme.errorTone import com.lumenpearson.lessons.ui.common.ClassCodeLengths import com.lumenpearson.lessons.ui.join.JoinViewModel +import com.lumenpearson.lessons.ui.join.rememberJoinSubmit import com.lumenpearson.lessons.ui.join.asText /** @@ -148,11 +149,15 @@ internal fun LazyListScope.classRows( * whose device was revoked gets back in — and it succeeds without changing * which class is active, so a sheet keyed on that sat there after a successful * join with the code still in the field and nothing to say it had worked. + * + * @param message the sentence under the title. A second class by default; the + * diary home, where the phone is in no class, passes one about a first. */ @Composable internal fun AddClassSheet( onDismiss: () -> Unit, modifier: Modifier = Modifier, + @StringRes message: Int = R.string.settings_class_add_message, viewModel: JoinViewModel = viewModel(factory = JoinViewModel.Factory), ) { val join by viewModel.uiState.collectAsStateWithLifecycle() @@ -168,16 +173,13 @@ internal fun AddClassSheet( onDismiss() } - // In an effect rather than in the body: dismissing is a state change, and - // composition is not allowed to make one. Done inline it dismissed on the - // same frame it was deciding what to draw, which Compose is entitled to - // treat as an infinite recomposition. - LaunchedEffect(join.joinedClassId) { - if (join.joinedClassId != null) { - viewModel.consumeJoined() - close() - } - } + // Dismissed from an effect rather than in the body: dismissing is a state + // change, and composition is not allowed to make one. Done inline it + // dismissed on the same frame it was deciding what to draw, which Compose + // is entitled to treat as an infinite recomposition. Only on this sheet's + // own join: another caller's, landing late, closed it before a code could + // be typed. + val submit = rememberJoinSubmit(viewModel, join.joined) { close() } val interactionSource = remember { MutableInteractionSource() } val focused by interactionSource.collectIsFocusedAsState() @@ -189,7 +191,7 @@ internal fun AddClassSheet( title = correctedString(R.string.settings_class_add), ) { Text( - text = correctedString(R.string.settings_class_add_message), + text = correctedString(message), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = ScreenPadding), @@ -236,7 +238,7 @@ internal fun AddClassSheet( TextButton(onClick = close) { Text(text = correctedString(R.string.action_cancel)) } - Button(onClick = viewModel::submit, enabled = join.canSubmit) { + Button(onClick = submit, enabled = join.canSubmit) { Text(text = correctedString(R.string.join_action)) } } diff --git a/android/app/src/main/res/values-en/strings_diary.xml b/android/app/src/main/res/values-en/strings_diary.xml index e0849c0d..abb5126e 100644 --- a/android/app/src/main/res/values-en/strings_diary.xml +++ b/android/app/src/main/res/values-en/strings_diary.xml @@ -34,6 +34,7 @@ The diary is not answering. Try again later. The diary answered in a way the server could not read: the service changed, and that is fixed on the server rather than in the app. No connection to the server. Check the network and the server address under “Sync”. + No connection to the server. Check the network and the server address. That date range is too wide - the diary serves at most 62 days at a time. This account has no such pupil. It did not work: %1$s @@ -126,10 +127,12 @@ No answer came in time. Try again. The diary let you in, but the server cannot be reached right now. Try again - no need to type the password. No server address is set. Set one under “Sync”. + No server address is set, and signing in needs one. This server cannot take a sign-in opened on the phone. It needs a newer server, or another address. The diary is switched off on this server. Only whoever runs the server can switch it on. This server does not work with your region\'s diary. The diary let you in, but refused the sign-in from the server\'s address. It is not the password, and trying again will not help. You can join a class by its code instead. + The diary let you in, but refused the sign-in from the server\'s address. It is not the password, and trying again will not help. The diary is not answering the server: it refuses requests from its address. It is not the password. The diary shows no pupil for this account. Too many attempts. Wait a little and try again. @@ -148,7 +151,11 @@ School Join a class by code If an administrator sets up your school\'s class in the bot, its code adds the class timetable, the widget and the bell reminders. - The phone goes back to the start. Lessons and marks saved on the phone are deleted, and the server forgets its copy of the sign-in. + Enter the class code the administrator gave you in the bot. The diary stays: it moves to Settings → Diary. + + The phone goes back to the start. Lessons and marks saved on the phone are deleted, and the server deletes its copy of the sign-in. If the phone is offline right now, the server deletes it by itself %1$d day after the diary was last used, and keeps a Setevoy Gorod session open until then. + The phone goes back to the start. Lessons and marks saved on the phone are deleted, and the server deletes its copy of the sign-in. If the phone is offline right now, the server deletes it by itself %1$d days after the diary was last used, and keeps a Setevoy Gorod session open until then. + Choose a diary diff --git a/android/app/src/main/res/values-en/strings_onboarding.xml b/android/app/src/main/res/values-en/strings_onboarding.xml index 45208c79..d5232749 100644 --- a/android/app/src/main/res/values-en/strings_onboarding.xml +++ b/android/app/src/main/res/values-en/strings_onboarding.xml @@ -47,7 +47,7 @@ %1$s: %2$s There are more matches than shown. If your region is not here, pick it from the list. - Schools with this name are all over the country. Pick the region from the list — the next step finds the school. + Schools with this name are all over the country. Pick the region from the list. No such school in the company register. Pick the region from the list. The school-name search is resting for another %1$d minute. Pick the region from the list. @@ -57,6 +57,7 @@ The server looks schools up by name, and none is set. Pick the region from the list. The server cannot be reached, so the school cannot be looked up by name. Pick the region from the list — it works offline. This server cannot look schools up by name. Pick the region from the list. + The school-name search is not answering right now. Pick the region from the list, or try the name again a little later. Your school %1$s · %2$s @@ -103,7 +104,7 @@ %1$s keeps its diary in %2$s, which opens only through Gosuslugi. Schools in %1$s show their marks in %2$s, while the diary itself is %3$s. The app cannot sign in there, so it recommends what opens for everyone. %1$s is moving to %2$s school by school. If yours already has, choose this one. - The diary of schools in %1$s takes no secure connections, and the app sends no password without one. So it recommends %2$s. + The diary of schools in %1$s takes no secure connections, and the app sends no password without one, so it cannot sign in there. A class code still brings the class timetable. Schools in %1$s use %2$s. The app cannot read it yet; a class code still brings the class timetable. In the %2$s school year schools in %1$s keep paper registers — there is no electronic diary. A regional portal, the ministry or the diary\'s operator confirms it. @@ -166,10 +167,15 @@ Class No class The bot does not know about you: the app shows only your diary. The widget, the notifications and the Today and Calendar tabs run on a class. If an admin sets your class up in the bot, join with its code in settings. + Diary sign-in The diary stays signed in while you open the app. After %1$d day without it you will have to sign in again — the widget does not extend it. The diary stays signed in while you open the app. After %1$d days without it you will have to sign in again — the widget does not extend it. + + The diary stays signed in while you open the diary: Settings → Diary. After %1$d day without it you will have to sign in again — the class timetable and the widget do not extend it. + The diary stays signed in while you open the diary: Settings → Diary. After %1$d days without it you will have to sign in again — the class timetable and the widget do not extend it. + The Petersburg diary may end the session sooner — the app then asks for the password again. Settings Notifications diff --git a/android/app/src/main/res/values/strings_diary.xml b/android/app/src/main/res/values/strings_diary.xml index 1717f605..118d6a4d 100644 --- a/android/app/src/main/res/values/strings_diary.xml +++ b/android/app/src/main/res/values/strings_diary.xml @@ -34,6 +34,7 @@ Дневник не отвечает. Попробуйте позже. Дневник ответил непонятно: сервис изменился, и это чинится на сервере, а не в приложении. Нет связи с сервером. Проверьте интернет и адрес сервера в разделе «Синхронизация». + Нет связи с сервером. Проверьте интернет и адрес сервера. Слишком широкий промежуток дат — дневник отдаёт не больше 62 дней за раз. Этого ученика нет в аккаунте. Не получилось: %1$s @@ -132,10 +133,12 @@ Ответа не дождались. Попробуйте ещё раз. Дневник вас впустил, но сервер сейчас недоступен. Повторите — пароль вводить заново не нужно. Не указан адрес сервера. Задайте его в разделе «Синхронизация». + Не указан адрес сервера, а без него войти не получится. Этот сервер не умеет принимать вход, открытый на телефоне. Нужен сервер новее или другой адрес. Дневник выключен на этом сервере. Включить его может только тот, кто обслуживает сервер. Этот сервер не работает с дневником вашего региона. Дневник вас впустил, но не принял вход с адреса сервера. Пароль тут ни при чём, и повтор не поможет. Можно подключиться к классу по коду. + Дневник вас впустил, но не принял вход с адреса сервера. Пароль тут ни при чём, и повтор не поможет. Дневник не отвечает серверу: запросы с его адреса он отклоняет. Пароль тут ни при чём. Для этого аккаунта дневник не показывает ни одного ученика. Слишком много попыток. Подождите немного и попробуйте снова. @@ -156,7 +159,13 @@ Школа Подключиться к классу по коду Если администратор заведёт класс вашей школы в боте, его код добавит расписание класса, виджет и напоминания о звонках. - Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер забудет свою копию входа. + Введите код класса от администратора в боте. Дневник останется — он будет в «Настройки → Дневник». + + Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер удалит свою копию входа. Если телефон сейчас не в сети, сервер удалит её сам через %1$d день после того, как дневником пользовались в последний раз, а сессию «Сетевого города» до тех пор будет держать открытой. + Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер удалит свою копию входа. Если телефон сейчас не в сети, сервер удалит её сам через %1$d дня после того, как дневником пользовались в последний раз, а сессию «Сетевого города» до тех пор будет держать открытой. + Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер удалит свою копию входа. Если телефон сейчас не в сети, сервер удалит её сам через %1$d дней после того, как дневником пользовались в последний раз, а сессию «Сетевого города» до тех пор будет держать открытой. + Телефон вернётся к началу. Уроки и оценки, сохранённые на телефоне, удалятся, а сервер удалит свою копию входа. Если телефон сейчас не в сети, сервер удалит её сам через %1$d дня после того, как дневником пользовались в последний раз, а сессию «Сетевого города» до тех пор будет держать открытой. + Выбрать дневник diff --git a/android/app/src/main/res/values/strings_onboarding.xml b/android/app/src/main/res/values/strings_onboarding.xml index 509fa53a..6a3765e0 100644 --- a/android/app/src/main/res/values/strings_onboarding.xml +++ b/android/app/src/main/res/values/strings_onboarding.xml @@ -63,7 +63,7 @@ %1$s: %2$s Совпадений больше, чем показано. Если вашего региона здесь нет, выберите его из списка. - Школ с таким названием много по всей стране. Выберите регион из списка — школу найдём на следующем шаге. + Школ с таким названием много по всей стране. Выберите регион из списка. В реестре организаций такой школы нет. Выберите регион из списка. Поиск школ по названию отдыхает ещё %1$d минуту. Выберите регион из списка. @@ -75,6 +75,7 @@ Школу по названию ищет сервер, а он не задан. Выберите регион из списка. Нет связи с сервером, и школу по названию найти не получится. Выберите регион из списка — он работает и без сети. Поиск школ по названию на этом сервере не работает. Выберите регион из списка. + Поиск школ по названию сейчас не отвечает. Выберите регион из списка или попробуйте название чуть позже. Ваша школа @@ -132,7 +133,8 @@ Регион «%1$s» ведёт дневник в «%2$s»: он открывается только через Госуслуги. Оценки школ региона «%1$s» видны в «%2$s», а сам дневник — «%3$s». Приложение туда войти не может, поэтому рекомендуем то, что открывается у всех. Регион «%1$s» переходит на «%2$s» по частям. Если ваша школа уже перешла — выбирайте этот вариант. - Дневник школ региона «%1$s» не принимает защищённые соединения, а приложение без них пароль не отправляет. Поэтому рекомендуем «%2$s». + + Дневник школ региона «%1$s» не принимает защищённые соединения, а приложение без них пароль не отправляет, поэтому войти в него из приложения нельзя. Расписание класса можно получить по коду класса. Дневник школ региона «%1$s» — «%2$s». Приложение пока не умеет его читать; расписание класса можно получить по коду. В %2$s учебном году школы региона «%1$s» ведут бумажные журналы — электронного дневника нет. Это подтверждает региональный портал, министерство или оператор дневника. @@ -203,12 +205,20 @@ Класс Без класса Бот о вас не знает: приложение показывает только ваш дневник. Виджет, уведомления и вкладки «Сегодня» и «Календарь» работают от класса. Если администратор заведёт ваш класс в боте, подключитесь по его коду в настройках. + Вход в дневник Вход в дневник держится, пока вы открываете приложение. После %1$d дня без этого войти придётся заново — виджет вход не продлевает. Вход в дневник держится, пока вы открываете приложение. После %1$d дней без этого войти придётся заново — виджет вход не продлевает. Вход в дневник держится, пока вы открываете приложение. После %1$d дней без этого войти придётся заново — виджет вход не продлевает. Вход в дневник держится, пока вы открываете приложение. После %1$d дня без этого войти придётся заново — виджет вход не продлевает. + + + Вход в дневник держится, пока вы открываете дневник: «Настройки → Дневник». После %1$d дня без этого войти придётся заново — расписание класса и виджет вход не продлевают. + Вход в дневник держится, пока вы открываете дневник: «Настройки → Дневник». После %1$d дней без этого войти придётся заново — расписание класса и виджет вход не продлевают. + Вход в дневник держится, пока вы открываете дневник: «Настройки → Дневник». После %1$d дней без этого войти придётся заново — расписание класса и виджет вход не продлевают. + Вход в дневник держится, пока вы открываете дневник: «Настройки → Дневник». После %1$d дня без этого войти придётся заново — расписание класса и виджет вход не продлевают. + Дневник Петербурга может закончить вход и раньше — тогда приложение попросит пароль ещё раз. Настройки Уведомления diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt index 1c885b40..104efb1f 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryHomeScreenTest.kt @@ -13,6 +13,7 @@ import com.lumenpearson.lessons.core.data.repository.DiarySession import com.lumenpearson.lessons.core.data.repository.DiaryStudent import com.lumenpearson.lessons.core.data.repository.DiaryTarget import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.ui.join.JoinRig import org.junit.Assert.assertNull import org.junit.Rule import org.junit.Test @@ -101,6 +102,57 @@ class DiaryHomeScreenTest { assertNull(repository.sessions.value) } + /** + * The sign-out is local first: offline, the goodbye never reaches the + * server, which keeps the session until the idle purge. The sheet used to + * promise the forgetting outright; it now says what the privacy policy + * says, in both halves. + */ + @Test + fun `the sign-out sheet says what the server does when the phone is offline`() { + val model = model() + compose.setContent { + LessonsTheme { DiaryAccountPage(viewModel = model) } + } + + compose.onNodeWithText("Выйти из дневника").performScrollTo().performClick() + compose.onNodeWithText("сервер удалит свою копию входа", substring = true).assertIsDisplayed() + compose.onNodeWithText("Если телефон сейчас не в сети", substring = true).assertIsDisplayed() + compose.onNodeWithText("через 30 дней", substring = true).assertIsDisplayed() + } + + /** + * The mode follows the stored target, not a live session: after a bare + * `401` the phone stays on the diary home with the login known and the + * pupils gone, and the page said «Вход выполнен» about it. + */ + @Test + fun `a lapsed sign-in is not called a sign-in on the account page`() { + val target = DiaryTarget.netschool("samara", 5, "Школа № 5", "ivanova", "Europe/Samara") + val lapsed = FakeDiaryRepository().apply { targets.value = target } + val model = DiaryViewModel(lapsed) + compose.setContent { + LessonsTheme { DiaryAccountPage(viewModel = model) } + } + + compose.onAllNodesWithText("Вход выполнен", substring = true).assertCountEquals(0) + compose.onNodeWithText("Сессия дневника закончилась").assertIsDisplayed() + compose.onNodeWithText("ivanova").performScrollTo().assertIsDisplayed() + } + + /** This page exists only on a phone in no class, so the sheet asks for a first one. */ + @Test + fun `the account page asks for a first class, not a second`() { + val model = model() + compose.setContent { + LessonsTheme { DiaryAccountPage(viewModel = model, joinFactory = JoinRig().factory()) } + } + + compose.onNodeWithText("Подключиться к классу по коду").performScrollTo().performClick() + compose.onNodeWithText("Введите код класса от администратора", substring = true).assertIsDisplayed() + compose.onAllNodesWithText("второго класса", substring = true).assertCountEquals(0) + } + /** * The card under a week that could not be read. It said «Дневник не * отвечает. Попробуйте позже.» for a throttle and for a diary switched off @@ -126,6 +178,17 @@ class DiaryHomeScreenTest { compose.onAllNodesWithText("Повторить").assertCountEquals(0) } + /** Our server's 502: the sentence says the fix is on the server, so no button says try again. */ + @Test + fun `an answer nobody could read says so, and offers no retry`() { + compose.setContent { + LessonsTheme { DiaryFailureCard(DiaryFailure.Unreadable, onRetry = {}) } + } + + compose.onNodeWithText("Дневник ответил непонятно", substring = true).assertIsDisplayed() + compose.onAllNodesWithText("Повторить").assertCountEquals(0) + } + @Test fun `a diary that is down still offers a retry`() { compose.setContent { diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOnboardingHoldTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOnboardingHoldTest.kt new file mode 100644 index 00000000..64c63f68 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryOnboardingHoldTest.kt @@ -0,0 +1,105 @@ +package com.lumenpearson.lessons.ui.diary + +import com.lumenpearson.lessons.core.data.repository.DiarySession +import com.lumenpearson.lessons.core.data.repository.DiaryStudent +import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A diary view model left over from an earlier home, while a later first run + * signs in and imports. + * + * The view model is the activity's, so it outlives the diary home it was made + * for — «Выйти из дневника» sends the phone back to the first run and leaves + * it collecting. It took the first run's new session for its own: read the + * pupils, and wrote the first of two as the stored choice, which is the key the + * import asks before it offers a family its chooser. So a two-child family was + * never asked, or was asked and then opened the home on the child it had not + * picked. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DiaryOnboardingHoldTest { + + private val now: Instant = Instant.parse("2026-09-23T09:00:00Z") + private val clock: Clock = Clock.fixed(now, ZoneOffset.UTC) + + private fun pupil(id: Long, name: String) = DiaryStudent( + id = id, + firstName = name, + lastName = "Иванов", + middleName = null, + fullName = "Иванов $name", + school = null, + className = null, + ) + + private val first = pupil(1, "Пётр") + private val second = pupil(2, "Анна") + + private val repository = FakeDiaryRepository().apply { students = listOf(first, second) } + private val cache = FakeDiaryCache() + private val held = MutableStateFlow(false) + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private val session = DiarySession( + login = "parent@example.com", + token = "t", + target = DiaryTarget.petersburg("parent@example.com"), + ) + + @Test + fun `a view model from an earlier home leaves the first run's pupil to the first run`() { + // The earlier home: signed out, and the phone back at the first run. + val model = DiaryViewModel(repository, cache = cache, clock = clock, held = held) + held.value = true + + // The first run's registration and its seed land. + cache.saveStudents(listOf(first, second), at = now) + repository.sessions.value = session + + assertNull("the view model chose for the import's chooser", cache.selected.value) + assertEquals("the view model read the diary alongside the import", 0, repository.studentReads) + + // The family picks the second child, and the first run lets go. + cache.selected.value = second.id + held.value = false + + assertEquals(second.id, model.uiState.value.selectedStudentId) + assertEquals(second.id, cache.selected.value) + } + + @Test + fun `a load an earlier session started does not land inside the hold`() { + repository.sessions.value = session + val model = DiaryViewModel(repository, cache = cache, clock = clock, held = held) + assertEquals(listOf(first, second), model.uiState.value.students) + + held.value = true + + assertTrue(model.uiState.value.students.isEmpty()) + assertNull(model.uiState.value.selectedStudentId) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt index abb18fe3..f4073626 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/diary/DiaryProblemTextTest.kt @@ -6,6 +6,7 @@ import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.Counted import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.Line import com.lumenpearson.lessons.ui.diary.DiaryProblemMessage.WithUpstream +import java.io.File import java.io.IOException import java.net.SocketTimeoutException import org.junit.Assert.assertEquals @@ -145,4 +146,67 @@ class DiaryProblemTextTest { assertFalse(DiarySignInProblem.ServerAddressRefused.offersRetry) assertFalse(DiarySignInProblem.TooManyAttempts(60).offersRetry) } + + /** + * Both sentences for an unreadable answer say the fix is on the server or + * in an update; a «Повторить» under them asked for the same answer again. + * The week's card had excluded our server's 502 on purpose, and lost that + * when it started asking the problem type instead. + */ + @Test + fun `an answer nobody could read offers no retry, on a read or a sign-in`() { + assertFalse(DiarySignInProblem.ProviderUnreadable(null).offersRetry) + assertFalse(DiarySignInProblem.ProviderUnreadable(host).offersRetry) + assertEquals(false, DiaryFailure.Unreadable.asProblem()?.offersRetry) + } + + /** + * The first run has no settings, so «в разделе «Синхронизация»» names a + * place the family cannot open; the address is on the steps themselves. + */ + @Test + fun `the first run is not sent to a settings section it does not have`() { + assertEquals(Line(R.string.diary_problem_offline), diaryProblemMessage(DiarySignInProblem.Offline)) + assertEquals( + Line(R.string.diary_problem_offline_first_run), + diaryProblemMessage(DiarySignInProblem.Offline, firstRun = true), + ) + assertEquals( + Line(R.string.diary_problem_server_missing_first_run), + diaryProblemMessage(DiarySignInProblem.ServerMissing, firstRun = true), + ) + for (lang in listOf("values", "values-en")) { + val strings = stringsOf(lang) + for (name in listOf("diary_problem_offline_first_run", "diary_problem_server_missing_first_run")) { + val text = strings.getValue(name) + assertFalse("$lang/$name names the settings: $text", "Синхронизац" in text || "Sync" in text) + } + } + } + + /** A family that joined a class by its code is not told to join one by its code. */ + @Test + fun `a phone in a class is not advised to join a class`() { + assertEquals( + Line(R.string.diary_problem_server_refused_session), + diaryProblemMessage(DiarySignInProblem.ServerRefusedSession), + ) + assertEquals( + Line(R.string.diary_problem_server_refused_session_in_class), + diaryProblemMessage(DiarySignInProblem.ServerRefusedSession, inClass = true), + ) + for (lang in listOf("values", "values-en")) { + val text = stringsOf(lang).getValue("diary_problem_server_refused_session_in_class") + assertFalse("$lang: $text", "по коду" in text || "by its code" in text) + } + } + + /** One `strings_diary.xml`, name to text, read from the source tree. */ + private fun stringsOf(folder: String): Map { + val file = listOf("src/main/res/$folder/strings_diary.xml", "app/src/main/res/$folder/strings_diary.xml") + .map(::File).first { it.isFile } + return Regex("(.*?)", RegexOption.DOT_MATCHES_ALL) + .findAll(file.readText()) + .associate { it.groupValues[1] to it.groupValues[2] } + } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinOneShotTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinOneShotTest.kt new file mode 100644 index 00000000..01849764 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinOneShotTest.kt @@ -0,0 +1,122 @@ +package com.lumenpearson.lessons.ui.join + +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onLast +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.ui.settings.AddClassSheet +import kotlinx.coroutines.CompletableDeferred +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A join's report belongs to the screen that sent the code. + * + * The join view model is the activity's, and the join writes the session — which + * swaps the shell — before its first sync, so the screen that pressed + * «Подключиться» is usually gone by the time the join reports. The report then + * waited for whoever came next: the «Добавить класс» sheet, which closed itself + * before a code could be typed, or a later first run's class-code step, which + * took it for its own join and finished a flow with no class in it. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp-h1200dp") +class JoinOneShotTest { + + @get:Rule val compose = createAndroidComposeRule() + + private val rig = JoinRig() + + /** A join started by a screen that is gone — the diary home's sheet, swapped away with its shell. */ + private fun orphanedJoin(model: JoinViewModel) { + model.onCodeChange("ABCD1234") + assertNotNull(model.submit()) + compose.waitForIdle() + } + + @Test + fun `a join another screen sent does not close the class sheet`() { + val model = rig.model() + orphanedJoin(model) + var dismissed = 0 + + compose.setContent { + LessonsTheme { AddClassSheet(onDismiss = { dismissed++ }, viewModel = model) } + } + compose.waitForIdle() + + assertEquals("the sheet closed on a join it never sent", 0, dismissed) + compose.onNode(hasSetTextAction()).performTextInput("EFGH5678") + compose.onAllNodesWithText("Подключиться").onLast().performClick() + compose.waitForIdle() + assertEquals("its own join closes it", 1, dismissed) + assertEquals(listOf("ABCD1234", "EFGH5678"), rig.codes) + } + + @Test + fun `a join another screen sent is not the first run's own`() { + val model = rig.model() + orphanedJoin(model) + val heard = mutableListOf() + + compose.setContent { + LessonsTheme { JoinScreen(onJoined = { heard += it }, viewModel = model) } + } + compose.waitForIdle() + + assertEquals("the class-code step heard somebody else's join", emptyList(), heard) + compose.onNode(hasSetTextAction()).performTextInput("EFGH5678") + compose.onAllNodesWithText("Подключиться").onLast().performClick() + compose.waitForIdle() + assertEquals(listOf(12L), heard) + } + + /** + * Leaving the class-code step while the code is out let the class land + * under the chooser, which then offered the family's own school as if + * nothing had been joined. + */ + @Test + fun `back is held while the code is out, and given back when it lands`() { + val gate = CompletableDeferred() + rig.syncGate = gate + val model = rig.model() + var backs = 0 + var flowBacks = 0 + + compose.setContent { + LessonsTheme { + // The first run's own handler, composed before the step as it is there. + BackHandler { flowBacks++ } + JoinScreen(onBack = { backs++ }, viewModel = model) + } + } + compose.onNode(hasSetTextAction()).performTextInput("ABCD1234") + compose.onAllNodesWithText("Подключиться").onLast().performClick() + compose.waitForIdle() + + compose.onNodeWithContentDescription("Назад").assertIsNotEnabled() + compose.runOnUiThread { compose.activity.onBackPressedDispatcher.onBackPressed() } + compose.waitForIdle() + assertEquals("the square left mid-join", 0, backs) + assertEquals("the gesture left mid-join", 0, flowBacks) + + gate.complete(Unit) + compose.waitForIdle() + compose.runOnUiThread { compose.activity.onBackPressedDispatcher.onBackPressed() } + compose.waitForIdle() + assertEquals("once the join has landed the gesture is the flow's again", 1, flowBacks) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinTestSupport.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinTestSupport.kt new file mode 100644 index 00000000..a3125431 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/join/JoinTestSupport.kt @@ -0,0 +1,66 @@ +package com.lumenpearson.lessons.ui.join + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import com.lumenpearson.lessons.core.data.repository.ServerStatus +import com.lumenpearson.lessons.core.data.repository.Session +import com.lumenpearson.lessons.core.data.repository.SessionRepository +import com.lumenpearson.lessons.core.data.repository.SyncResult +import com.lumenpearson.lessons.core.data.repository.TimetableRepository +import com.lumenpearson.lessons.core.model.Timetable +import com.lumenpearson.lessons.ui.onboarding.FakeSettings +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map + +/** + * The join's two halves as a test holds them: the session write, and the first + * sync after it — which [syncGate], when set, parks, as a slow network does + * while the shell has already swapped on the session. + */ +internal class JoinRig { + + val joined = MutableStateFlow>(emptyList()) + var syncGate: CompletableDeferred? = null + val codes = mutableListOf() + + private val sessionRepository = object : SessionRepository { + override val session: Flow = joined.map { it.lastOrNull() } + override val sessions: Flow> = joined + override suspend fun current(): Session? = joined.value.lastOrNull() + override suspend fun serverStatus(): ServerStatus = ServerStatus.NotConfigured + override suspend fun currentAll(): List = joined.value + override suspend fun join(code: String, deviceName: String?): Result { + codes += code + val session = Session(classId = 10L + codes.size, className = "9А", school = null, token = "t") + joined.value = joined.value + session + return Result.success(session) + } + override suspend fun select(classId: Long) = Unit + override suspend fun leave(classId: Long) = Unit + override suspend fun leaveActive() = Unit + override suspend fun signOut() = Unit + } + + private val timetables = object : TimetableRepository { + override val timetable: Flow = MutableStateFlow(null) + override val syncedYears: Flow> = MutableStateFlow(emptySet()) + override suspend fun snapshot(): Timetable? = null + override suspend fun snapshotAroundToday(): Timetable? = null + override suspend fun refresh(): SyncResult { + syncGate?.await() + return SyncResult.Success + } + override suspend fun refreshYear(openingYear: Int): SyncResult = refresh() + override suspend fun forgetClassesOtherThan(keep: Set) = Unit + } + + fun model() = JoinViewModel(sessionRepository, timetables, FakeSettings(), deviceName = null) + + /** Hands [model] to `viewModel(factory = …)`, the way the app's own factory would. */ + fun factory(model: JoinViewModel = model()) = object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = model as T + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt index bb75b0c4..e99b7b99 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingCatalogTest.kt @@ -162,14 +162,30 @@ class OnboardingCatalogTest { @Test fun `a region row says why it matched and what can be done there`() { - val byCity = realSearch.search("Togliatti").ifEmpty { realSearch.search("tolyatti") } val samaraMatch = realSearch.search("63").first { it.region.key == "samara" } val row = regionRowOf(realCatalog, samaraMatch) assertEquals(MatchVia.CODE, row.via) assertEquals("63", row.matched) assertEquals(OfferKind.SIGN_IN, row.offer.kind) - byCity.firstOrNull { it.via == MatchVia.CITY }?.let { match -> - assertTrue(regionRowOf(realCatalog, match).matched in match.region.cities) + + // A city and an alias, as the catalog spells them — never the search's + // folded words, which have lost the capitals and «область». + val samara = region("samara") + val togliatti = samara.cities[1] + assertEquals("the premise: Samara's second city is Togliatti", 3, samara.cities.size) + val byCity = realSearch.search(togliatti).first { it.region.key == "samara" } + assertEquals(MatchVia.CITY, byCity.via) + assertEquals(togliatti, regionRowOf(realCatalog, byCity).matched) + + for (key in listOf("zabaikalsky", "perm")) { + val entry = region(key) + // The alias that carries a region-type word, which the search drops. + val alias = entry.aliases.first { it.contains(' ') } + for (query in listOf(alias, alias.substringBefore(' '))) { + val match = realSearch.search(query).first { it.region.key == key } + assertEquals("$query finds $key by its alias", MatchVia.ALIAS, match.via) + assertEquals(query, alias, regionRowOf(realCatalog, match).matched) + } } assertEquals(OfferKind.GOSUSLUGI, regionOfferOf(realCatalog, region("tula")).kind) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFormTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFormTest.kt new file mode 100644 index 00000000..0a2e5319 --- /dev/null +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingFormTest.kt @@ -0,0 +1,128 @@ +package com.lumenpearson.lessons.ui.onboarding + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.semantics.getOrNull +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performImeAction +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.text.TextLayoutResult +import androidx.test.core.app.ApplicationProvider +import com.lumenpearson.lessons.R +import com.lumenpearson.lessons.core.data.repository.DiarySessionIdleDays +import com.lumenpearson.lessons.core.designsystem.theme.LessonsTheme +import com.lumenpearson.lessons.ui.diary.DiaryCredentialFields +import com.lumenpearson.lessons.ui.diary.LoginFieldTag +import com.lumenpearson.lessons.ui.diary.PasswordFieldTag +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * The sign-in form and the summary, drawn: what a keystroke leaves in the + * field, what a link does on a phone with no browser, and whether a warning + * can be read without watching it crawl. + */ +@RunWith(RobolectricTestRunner::class) +@Config(qualifiers = "ru-rRU-w411dp-h1200dp") +// Real text measurement: whether a sentence wraps is the question one of these +// tests asks, and the legacy shadows lay every string out on one line. +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class OnboardingFormTest { + + @get:Rule + val compose = createComposeRule() + + private val context get() = ApplicationProvider.getApplicationContext() + + /** + * The form trimmed the login on every keystroke. A field hands back the + * value it is given, so a space typed at the end vanished and the next + * letter joined the word: «par ent», which the shared vectors hold to be a + * valid «Сетевой город» login, could only ever be typed as «parent». + */ + @Test + fun `a login with a space inside can be typed, and the ends are trimmed on the way out`() { + var login by mutableStateOf("") + var sent: String? = null + compose.setContent { + LessonsTheme { + DiaryCredentialFields( + login = login, + onLoginChange = { login = it }, + onSubmit = { typed, _ -> sent = typed }, + loginKeyboard = androidx.compose.ui.text.input.KeyboardType.Text, + ) + } + } + + val field = compose.onNodeWithTag(LoginFieldTag) + field.performTextInput("par") + field.performTextInput(" ") + field.performTextInput("ent") + field.performTextInput(" ") + assertEquals("par ent ", login) + + val password = compose.onNodeWithTag(PasswordFieldTag) + password.performTextInput("secret") + password.performImeAction() + assertEquals("par ent", sent) + } + + /** + * The keep-alive warning is two sentences. As a row's title it was one + * line scrolling for ever; as its subtitle it wraps. The clock is held + * because a marquee — which is what the defect drew — never lets it idle. + */ + @Test + fun `the keep-alive warning wraps rather than crawling along one line`() { + compose.mainClock.autoAdvance = false + compose.setContent { + LessonsTheme { KeepAliveItem(inClass = false, petersburg = true) } + } + repeat(4) { + Snapshot.sendApplyNotifications() + compose.mainClock.advanceTimeByFrame() + } + + val days = DiarySessionIdleDays.toInt() + val sentence = context.resources.getQuantityString(R.plurals.onboarding_summary_keepalive, days, days) + val node = compose.onNodeWithText(sentence, substring = true, useUnmergedTree = true).fetchSemanticsNode() + val layouts = mutableListOf() + node.config.getOrNull(SemanticsActions.GetTextLayoutResult)?.action?.invoke(layouts) + val lines = layouts.single().lineCount + assertTrue("the warning is drawn on $lines line(s)", lines > 1) + compose.onNodeWithText(context.getString(R.string.onboarding_summary_keepalive_title)).fetchSemanticsNode() + } + + /** + * «Забыли пароль?» and the Госуслуги «Открыть» dropped what + * `openInBrowser` answered, so on a phone with nothing to open a link the + * tap did nothing and said nothing. The handoff sheet says why; so does + * the sign-in now. + */ + @Test + fun `a link nothing on the phone can open is remembered, so the page can say so`() { + shadowOf(RuntimeEnvironment.getApplication()).checkActivities(true) + val links = BrowserLinks(context) + assertFalse(links.failed) + + links.open("https://dnevnik2.petersburgedu.ru") + + assertTrue("the tap that opened nothing is not dropped", links.failed) + } +} diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt index 57e92682..403688fb 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingPromisesTest.kt @@ -71,6 +71,24 @@ class OnboardingPromisesTest { } } + /** + * The note under a school name too common to place promised «школу найдём + * на следующем шаге», and most regions have no school step: the next step + * there is the diary list, and nothing ever looks for the school. + */ + @Test + fun `the generic-name note promises no school step most regions do not have`() { + val without = realCatalog.regions.count { !regionPlanOf(it).showsSchool } + assertTrue("the premise: most regions skip the school step", without > realCatalog.regions.size / 2) + + val notes = shipped.filter { (name, _) -> name.endsWith("/onboarding_region_school_generic") } + assertEquals("both languages", 2, notes.size) + val promises = listOf("следующем шаге", "найдём", "next step", "finds the school") + for ((name, text) in notes) { + assertTrue("$name: $text", promises.none { it in text }) + } + } + /** * #157. The first run is not four screens or five any more and the class * code is not six characters; the comments that counted either were a diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt index 3e6b2fe2..d2d7bcbe 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingStepsTest.kt @@ -8,6 +8,7 @@ import com.lumenpearson.lessons.core.data.diary.DiaryImportPhase import com.lumenpearson.lessons.core.data.diary.DiaryImportProgress import com.lumenpearson.lessons.core.data.repository.DiarySignInProblem import com.lumenpearson.lessons.core.data.repository.DiaryTarget +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle @@ -99,8 +100,135 @@ class OnboardingStepsTest { assertNull(step.state.value.problem) } + /** + * The password has gone and the diary is answering when the step is left: + * the session it opens is ended, not dropped with the cancelled call. + */ + @Test + fun `a session the diary opens after the step was left is ended there`() = runTest { + val gate = CompletableDeferred() + val signIn = FakeSignIn().apply { openGate = gate } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + step.submit(target, password) {} + runCurrent() + assertEquals(SignInStage.UPSTREAM, step.state.value.stage) + + step.abandon() + gate.complete(Unit) + advanceUntilIdle() + + assertEquals("the session opened after the leave", 1, signIn.discarded.size) + assertTrue("and it was never sent to our server", signIn.registered.isEmpty()) + } + + /** + * Leaving while our server adopts the session must neither end it + * upstream under the server nor drop the answer: the registration runs to + * its end, and the real one stores the bearer, so the row has a key. + */ + @Test + fun `leaving during the registration lets it finish and ends nothing under the server`() = runTest { + val gate = CompletableDeferred() + val stored = mutableListOf() + val signIn = FakeSignIn().apply { + registerGate = gate + this.stored = { stored += it.token } + } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + var registered = false + step.submit(target, password) { registered = true } + runCurrent() + assertEquals(SignInStage.REGISTER, step.state.value.stage) + + step.abandon() + advanceUntilIdle() + assertTrue("nothing said goodbye while the server held the request", signIn.discarded.isEmpty()) + + gate.complete(Unit) + advanceUntilIdle() + assertEquals("the bearer was stored", listOf("bearer"), stored) + assertTrue(signIn.discarded.isEmpty()) + assertFalse("a step that was left is not carried on", registered) + } + + @Test + fun `a registration that failed after the step was left ends the session it kept`() = runTest { + val gate = CompletableDeferred() + val signIn = FakeSignIn().apply { + registerGate = gate + registerResults += Result.failure(DiarySignInProblem.RegisterUnreachable) + } + val step = SignInStep(this, signIn) + step.setLogin("ivan") + step.submit(target, password) {} + runCurrent() + + step.abandon() + gate.complete(Unit) + advanceUntilIdle() + + assertEquals(signIn.registered, signIn.discarded) + assertFalse(step.state.value.sessionHeld) + } + + @Test + fun `the sign-in's way out is back, not now, or start over`() { + assertEquals(SignInExit.SKIP, signInExitOf(classBound = true, canGoBack = false)) + assertEquals(SignInExit.BACK, signInExitOf(classBound = false, canGoBack = true)) + assertEquals( + "a sign-in on the floor still has a way out", + SignInExit.START_OVER, + signInExitOf(classBound = false, canGoBack = false), + ) + } + + // --- School search --------------------------------------------------------------------- + + @Test + fun `a new school name for the same region is a new search, the same one keeps the typing`() = runTest { + val asked = mutableListOf() + val finder = SchoolFinder(scope = this, schools = { _, query -> asked += query; Result.success(emptyList()) }) + + finder.open("samara", "239") + advanceUntilIdle() + finder.type("2391") + advanceUntilIdle() + + // Back from the provider step: what was typed here stays. + finder.open("samara", "239") + advanceUntilIdle() + assertEquals("2391", finder.state.value.query) + + // Back to the region step, and another school name typed there. + finder.open("samara", "116") + advanceUntilIdle() + assertEquals("116", finder.state.value.query) + assertEquals("116", asked.last()) + } + // --- Import ---------------------------------------------------------------------------- + /** + * «Повторить» only where a second try can get past the failure (#153's + * rule): an account with no pupil, or a diary that refuses our server's + * address, answers the same way every time. + */ + @Test + fun `the import offers a retry only where one can help`() { + fun actionFor(problem: DiarySignInProblem) = + importActionOf(ImportUi(failed = ImportFailure(DiaryImportPhase.SCHEDULE, problem, resumable = true))) + assertEquals(ImportAction.RETRY, actionFor(DiarySignInProblem.Offline)) + assertEquals(ImportAction.RETRY, actionFor(DiarySignInProblem.ProviderUnavailable(null))) + assertEquals(ImportAction.SIGN_IN_AGAIN, actionFor(DiarySignInProblem.ReauthRequired)) + assertEquals(ImportAction.START_OVER, actionFor(DiarySignInProblem.NoStudent)) + assertEquals(ImportAction.START_OVER, actionFor(DiarySignInProblem.ServerAddressRefused)) + assertEquals(ImportAction.START_OVER, actionFor(DiarySignInProblem.ServerDisabled)) + assertEquals(ImportAction.RUNNING, importActionOf(ImportUi())) + assertEquals(ImportAction.CONTINUE, importActionOf(ImportUi(done = ImportDone(1, 1, 1, emptySet())))) + } + @Test fun `stage rows follow the phase under way`() { val running = ImportUi(phase = DiaryImportPhase.SCHEDULE) @@ -151,6 +279,7 @@ class OnboardingStepsTest { advanceUntilIdle() assertNull(runner.state.value.choosing) assertEquals(1f, runner.state.value.completed) + assertEquals("the import goes on with the pupil picked", 8L, import.picked?.id) } // --- Region search --------------------------------------------------------------------- @@ -199,5 +328,22 @@ class OnboardingStepsTest { assertEquals(DirectoryFailure.OFFLINE, failed(DirectoryProblem.Offline).reason) assertEquals(DirectoryFailure.OFF, failed(DirectoryProblem.Disabled).reason) assertEquals(DirectoryFailure.OFF, failed(DirectoryProblem.ServerTooOld).reason) + // The directory failing this once is not the server lacking it. + assertEquals(DirectoryFailure.DOWN, failed(DirectoryProblem.Upstream).reason) + assertEquals(DirectoryFailure.DOWN, failed(DirectoryProblem.Unexpected("500")).reason) + } + + @Test + fun `a lookup that threw is the directory down, not switched off`() = runTest { + val finder = RegionFinder( + scope = this, + catalog = { realCatalog }, + byName = { realSearch.search(it) }, + find = { error("timed out") }, + ) + finder.type("Lyceum 239") + finder.submit() + advanceUntilIdle() + assertEquals(SchoolAnswer.Failed(DirectoryFailure.DOWN), finder.state.value.school) } } diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt index cda95a06..2e77be60 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTestSupport.kt @@ -24,6 +24,7 @@ import com.lumenpearson.lessons.core.data.upstream.DiarySchool import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.ui.diary.FakeDiaryCache import java.io.File +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emptyFlow @@ -73,6 +74,11 @@ internal class TestHeld(override val target: DiaryTarget) : HeldUpstream /** * The sign-in, scripted: what each step answers, and every call it was asked. * The password is recorded only to prove, elsewhere, that nothing else kept it. + * + * [openGate] and [registerGate], when set, hold that step until completed — + * the diary or our server still answering — so a test can leave the step + * while the answer is out. [stored] is what the real registration does on + * success: it writes the bearer to the phone's store. */ internal class FakeSignIn : OnboardingSignIn { var preflightResult: Result = Result.success(Unit) @@ -82,6 +88,9 @@ internal class FakeSignIn : OnboardingSignIn { val opened = mutableListOf>() val registered = mutableListOf() val discarded = mutableListOf() + var openGate: CompletableDeferred? = null + var registerGate: CompletableDeferred? = null + var stored: (DiarySession) -> Unit = {} override suspend fun preflight(target: DiaryTarget): Result { calls += "preflight" @@ -91,13 +100,17 @@ internal class FakeSignIn : OnboardingSignIn { override suspend fun open(target: DiaryTarget, password: String): Result { calls += "open" opened += target to password + openGate?.await() return openResult(target) } override suspend fun register(held: HeldUpstream): Result { calls += "register" registered += held - return registerResults.removeFirstOrNull() ?: Result.success(registration(held.target)) + registerGate?.await() + val result = registerResults.removeFirstOrNull() ?: Result.success(registration(held.target)) + result.onSuccess { stored(it.session) } + return result } override suspend fun discard(held: HeldUpstream) { @@ -119,7 +132,11 @@ internal val pupil = DiaryStudent( className = "9A", ) -/** An import that answers with [steps], or waits for the chooser when [choosing] is set. */ +/** + * An import that answers with [steps], or waits for the chooser when [choosing] + * is set. [picked] is whom the chooser answered with, and [selected] is told as + * `DiaryImportImpl` tells the store. + */ internal class FakeImport( var steps: List = listOf( DiaryImportProgress.Running(DiaryImportPhase.STUDENTS, 0f, 0.1f), @@ -128,6 +145,8 @@ internal class FakeImport( var choosing: List? = null, ) : DiaryImport { val runs = mutableListOf() + var picked: DiaryStudent? = null + var selected: suspend (Long) -> Unit = {} override fun run( resumeFrom: DiaryImportPhase?, @@ -136,8 +155,10 @@ internal class FakeImport( runs += resumeFrom choosing?.let { students -> emit(DiaryImportProgress.ChoosingStudent(students, 0.1f)) - val picked = choose(students) - emit(DiaryImportProgress.Done(picked, emptySet(), 1, 1, 1)) + val chosen = choose(students) + picked = chosen + selected(chosen.id) + emit(DiaryImportProgress.Done(chosen, emptySet(), 1, 1, 1)) return@flow } steps.forEach { emit(it) } @@ -162,6 +183,13 @@ internal class OnboardingRig( val directoryAsked = mutableListOf() var schools: List = listOf(DiarySchool(id = 239, name = "Lyceum 239", address = null)) + init { + // What the real registration and import write, where the view model + // reads it back: the bearer in the store, the pupil picked in the cache. + signIn.stored = { diarySession = it } + import.selected = { cache.selectStudent(it) } + } + fun deps() = OnboardingDeps( settings = settings, shellMode = shell, diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt index 7b03dd92..21c7c8bc 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingTextTest.kt @@ -80,6 +80,43 @@ class OnboardingTextTest { } } + /** + * The one region the catalog calls unreachable is recommended its own + * diary — the generator has nothing else to name there — so a sentence + * ending «Поэтому рекомендуем «%2$s»» recommended the very diary it had + * just said cannot be reached. Read against the real row, in both languages. + */ + @Test + fun `the unreachable reason does not recommend the diary it calls unreachable`() { + val volgograd = realCatalog.regions.single { it.recommended?.reason == WhyReason.UNREACHABLE.code } + val why = checkNotNull(providerPageOf(realCatalog, volgograd, school = null).why) + for ((language, system) in listOf(context to why.systemRu, inEnglish() to why.systemEn)) { + val line = whyLines(why, volgograd.nameRu, system, null, null).first() + val text = language.getString(line.id, *line.args.toTypedArray()) + assertFalse("\"$text\" names $system as the answer", system in text) + assertTrue(text, volgograd.nameRu in text) + } + } + + /** + * What keeps the diary's sign-in, by mode: only a diary read moves the + * server's idle clock, and in a class nothing reads the diary on start — + * the class's timetable is the home. The class sentence sends the family + * to the diary itself. + */ + @Test + fun `the keep-alive sentence says what keeps the sign-in in each mode`() { + for (language in listOf(context, inEnglish())) { + val resources = language.resources + val home = resources.getQuantityString(keepAliveText(inClass = false), 30, 30) + val inClass = resources.getQuantityString(keepAliveText(inClass = true), 30, 30) + assertFalse("a class's sentence is its own", home == inClass) + val settings = language.getString(com.lumenpearson.lessons.R.string.settings_title) + assertTrue(inClass, settings in inClass) + assertTrue(inClass, "30" in inClass) + } + } + @Test fun `a sign-in reason names the system and the school year`() { val text = whyLines(why(WhyReason.PRIMARY), "Region", "System", null, null) diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt index 853a642c..c05365cb 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/onboarding/OnboardingViewModelTest.kt @@ -183,13 +183,271 @@ class OnboardingViewModelTest { model.importShown() advanceUntilIdle() assertEquals(OnboardingStep.SUMMARY, model.state.current) - assertNotNull(model.summary.value) + val summary = checkNotNull(model.summary.value) + assertEquals(login, summary.login) + assertEquals("asurso.ru", summary.place?.host) + assertFalse("a diary-only phone draws no class and no notifications row", summary.inClass) + assertNull(summary.className) model.finish() advanceUntilIdle() assertFalse(rig.shell.stored.value.held) } + /** + * The pupil the owner asked the summary to name is the one picked on the + * chooser, not whoever the diary lists first — and the class, when there + * is one, is what turns on the class card and the notifications row. + */ + @Test + fun `the summary names the pupil picked and the class joined`() = runTest(dispatcher) { + val sister = pupil.copy(id = 8, firstName = "Anna", fullName = "Petrova Anna", className = "5B") + val rig = OnboardingRig(import = FakeImport(choosing = listOf(pupil, sister))) + rig.cache.saveStudents(listOf(pupil, sister), java.time.Instant.EPOCH) + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + assertEquals(listOf(7L, 8L), model.importing.state.value.choosing?.map { it.id }) + + model.pickStudent(8) + advanceUntilIdle() + assertEquals("the import goes on with the pupil picked", 8L, rig.import.picked?.id) + model.importShown() + advanceUntilIdle() + val summary = checkNotNull(model.summary.value) + assertEquals("Petrova Anna", summary.studentName) + assertEquals("5B", summary.studentClass) + assertFalse(summary.inClass) + + // The same page for a phone that also holds a class. + val joined = OnboardingRig() + joined.joinedClass(DiaryBinding(DiaryProviderKey.NETSCHOOL, "samara", 239L, "Lyceum 239")) + val classModel = joined.model() + classModel.start(introduced = true) + advanceUntilIdle() + classModel.chooseWay(WayIn.CLASS_CODE) + classModel.proceedFromWayIn() + advanceUntilIdle() + classModel.onJoined() + advanceUntilIdle() + classModel.signIn.setLogin(login) + classModel.submitSignIn(password) + advanceUntilIdle() + classModel.importShown() + advanceUntilIdle() + val inClass = checkNotNull(classModel.summary.value) + assertTrue(inClass.inClass) + assertEquals("9A", inClass.className) + } + + /** + * Back during «Передаём сессию серверу…» used to cancel + * the request our server finishes anyway: a sealed diary credential tied + * to no device, which no sign-out could reach, and a second with the next + * try. The step now stays until the answer is in. + */ + @Test + fun `back is refused while the server is adopting the session`() = runTest(dispatcher) { + val rig = OnboardingRig() + val gate = kotlinx.coroutines.CompletableDeferred() + rig.signIn.registerGate = gate + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + assertEquals(SignInStage.REGISTER, model.signIn.state.value.stage) + + model.back() + advanceUntilIdle() + assertEquals("the sign-in is not left mid-registration", OnboardingStep.SIGN_IN, model.state.current) + assertTrue("nothing said goodbye under the server", rig.signIn.discarded.isEmpty()) + + gate.complete(Unit) + advanceUntilIdle() + assertEquals(OnboardingStep.IMPORT, model.state.current) + assertNotNull("the phone holds the bearer to the row the server kept", rig.diarySession) + assertTrue(rig.signIn.discarded.isEmpty()) + } + + @Test + fun `not now is refused while a class's sign-in is under way`() = runTest(dispatcher) { + val rig = OnboardingRig() + val gate = kotlinx.coroutines.CompletableDeferred() + rig.signIn.registerGate = gate + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.chooseWay(WayIn.CLASS_CODE) + model.proceedFromWayIn() + advanceUntilIdle() + rig.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + model.onJoined() + advanceUntilIdle() + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + + model.skipSignIn() + advanceUntilIdle() + assertTrue("the flow did not end under the registration", rig.shell.stored.value.held) + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + + gate.complete(Unit) + advanceUntilIdle() + assertEquals(OnboardingStep.IMPORT, model.state.current) + } + + /** + * The bundle is written when the activity stops; a + * registration that lands after that reaches the in-memory handle only, + * and a process death then restored the form over a diary already + * registered — a second sign-in there orphans the first server row. + */ + @Test + fun `a saved sign-in over a diary registered since goes on to its import`() = runTest(dispatcher) { + val rig = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.DIARY, held = true))) + OnboardingState( + path = listOf( + OnboardingStep.WAY_IN, + OnboardingStep.REGION, + OnboardingStep.SCHOOL, + OnboardingStep.PROVIDER, + OnboardingStep.SIGN_IN, + ), + choices = OnboardingChoices( + wayIn = WayIn.FIND_SCHOOL, + region = "samara", + school = PickedSchool(239, "Lyceum 239"), + system = 0, + ), + ).toSaved().forEach { (key, value) -> rig.saved[key] = value } + rig.diarySession = DiarySession(login, "bearer", DiaryTarget.netschool("samara", 239L, "Lyceum 239", login, "Europe/Samara")) + + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + + assertEquals(OnboardingStep.IMPORT, model.state.current) + assertFalse("the form cannot be walked back into", model.state.canGoBack) + assertEquals("the import runs from the start", listOf(null), rig.import.runs) + } + + @Test + fun `a saved join screen over a class joined since goes on as the join would`() = runTest(dispatcher) { + val finished = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.CLASS, held = true))) + val atCode = OnboardingState( + path = listOf(OnboardingStep.WAY_IN, OnboardingStep.CLASS_CODE), + choices = OnboardingChoices(wayIn = WayIn.CLASS_CODE), + ) + atCode.toSaved().forEach { (key, value) -> finished.saved[key] = value } + finished.joinedClass(binding = null) + finished.model().start(introduced = true) + advanceUntilIdle() + assertFalse("a class with no diary: the flow is done", finished.shell.stored.value.held) + + val bound = OnboardingRig(shell = FakeShellMode(ShellState(ShellMode.CLASS, held = true))) + atCode.toSaved().forEach { (key, value) -> bound.saved[key] = value } + bound.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + val model = bound.model() + model.start(introduced = true) + advanceUntilIdle() + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + assertTrue(model.state.choices.classBound) + assertFalse("the join screen cannot be walked back into", model.state.canGoBack) + } + + /** + * «Забыли пароль?» took the site of a system + * picked on the provider step and walked back from, over the class's own + * diary the form now signs in to. + */ + @Test + fun `a class's sign-in after a family attempt links the class's diary site`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.signIn.registerResults += Result.failure(DiarySignInProblem.ServerRefusedSession) + val model = rig.model() + toSamaraSignIn(model) + assertEquals("https://asurso.ru", model.signInHeader.value?.forgotUrl) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + assertEquals(DiarySignInProblem.ServerRefusedSession, model.signIn.state.value.problem) + + model.toClassCode() + advanceUntilIdle() + rig.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + model.onJoined() + advanceUntilIdle() + + val header = checkNotNull(model.signInHeader.value) + assertEquals(DiaryProviderKey.PETERSBURG, header.provider) + assertEquals("https://dnevnik2.petersburgedu.ru", header.forgotUrl) + } + + /** The same, reached by walking back from the family's sign-in rather than through a 409. */ + @Test + fun `a class's sign-in after walking back from the family's links the class's diary site`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + toSamaraSignIn(model) + model.back() + advanceUntilIdle() + assertEquals(OnboardingStep.PROVIDER, model.state.current) + + model.toClassCode() + advanceUntilIdle() + rig.joinedClass(DiaryBinding(DiaryProviderKey.PETERSBURG, null, null, null)) + model.onJoined() + advanceUntilIdle() + + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + assertEquals("https://dnevnik2.petersburgedu.ru", model.signInHeader.value?.forgotUrl) + } + + /** + * «Войти ещё раз» put the sign-in on the floor with no + * back and no «Не сейчас»; a sign-in that kept failing there had no way + * out short of killing the app. It has the import page's own now. + */ + @Test + fun `a sign-in reopened after the import can still start over`() = runTest(dispatcher) { + val rig = OnboardingRig() + rig.import.steps = listOf( + DiaryImportProgress.Failed(DiaryImportPhase.SCHEDULE, DiarySignInProblem.ReauthRequired, true, 0.2f), + ) + val model = rig.model() + toSamaraSignIn(model) + model.signIn.setLogin(login) + model.submitSignIn(password) + advanceUntilIdle() + model.signInAgain() + advanceUntilIdle() + val reopened = model.state + assertEquals(OnboardingStep.SIGN_IN, reopened.current) + assertEquals(SignInExit.START_OVER, signInExitOf(reopened.choices.classBound, reopened.canGoBack)) + + // Not while a sign-in is out: the registration would land on a flow + // that has moved on. + val gate = kotlinx.coroutines.CompletableDeferred() + rig.signIn.registerGate = gate + rig.signIn.registerResults += Result.failure(DiarySignInProblem.WrongPassword(upstreamMessage = null)) + model.submitSignIn(password) + advanceUntilIdle() + model.startOver() + advanceUntilIdle() + assertEquals(OnboardingStep.SIGN_IN, model.state.current) + gate.complete(Unit) + advanceUntilIdle() + + model.startOver() + advanceUntilIdle() + assertEquals(listOf(OnboardingStep.WAY_IN), model.state.path) + assertEquals(1, rig.signedOut) + } + @Test fun `a failed registration keeps the session for a retry without the password`() = runTest(dispatcher) { val rig = OnboardingRig() @@ -290,6 +548,52 @@ class OnboardingViewModelTest { assertEquals(listOf(OnboardingStep.WAY_IN), model.state.path) } + /** + * The step holders live as long as the view model, which is the + * activity's. After «Выйти из дневника» sends a diary-only phone back to + * the first run, the next one opened on the old region's search and on a + * sign-in form holding the login that sign-out had just forgotten. + */ + @Test + fun `a finished flow's login and searches do not reach the next one`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.region.type("Самара") + model.school.open("samara", "Лицей") + model.signIn.setLogin(login) + advanceUntilIdle() + + model.finish() + advanceUntilIdle() + model.start(introduced = true) + advanceUntilIdle() + + assertEquals("", model.signIn.state.value.login) + assertEquals("", model.region.state.value.query) + assertTrue(model.region.state.value.rows.isEmpty()) + assertEquals("", model.school.state.value.query) + assertNull(model.school.state.value.regionKey) + assertNull(model.signInHeader.value) + assertNull(model.summary.value) + } + + /** A first start is not a restart: a recreation keeps the login in memory. */ + @Test + fun `a flow that has not finished keeps its login across a second start`() = runTest(dispatcher) { + val rig = OnboardingRig() + val model = rig.model() + model.start(introduced = true) + advanceUntilIdle() + model.signIn.setLogin(login) + + model.start(introduced = true) + advanceUntilIdle() + + assertEquals(login, model.signIn.state.value.login) + } + @Test fun `an import the diary ended goes back to the sign-in and resumes its phase`() = runTest(dispatcher) { val rig = OnboardingRig() diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt index 570b19df..78331c41 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblem.kt @@ -119,10 +119,16 @@ sealed class DiarySignInProblem(message: String, cause: Throwable? = null) : * An answer nobody could read: the diary's to the phone (a captcha, a * changed sign-in page), or its answer to our server (`502`), in which case * [host] is `null`. An app update fixes this, not another password. + * + * Nor another attempt: [Action.NONE], because both sentences for it say + * the fix is on the server or in an update, and a «Повторить» under them + * asks the same question for the same answer. The diary's card excluded + * the `502` from retrying for exactly that reason until the card started + * asking this type instead. */ data class ProviderUnreadable(val host: String?) : DiarySignInProblem("The diary answered in an unreadable way") { - override val action get() = Action.RETRY + override val action get() = Action.NONE } /** The phone could not resolve or reach the diary's server at all. */ diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt index 2294e60a..aa3cc9b4 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/UpstreamJson.kt @@ -39,8 +39,15 @@ internal object UpstreamJson { * object. Each of those is a refusal to the server, which calls it * «unexpected»; the phone used to carry on with a word, and then called a * firewall page a dead diary and a garbled login answer a wrong password. + * + * And it reads a raw control character inside a string — a tab or a line + * break the diary did not escape — which `json.loads` refuses («Invalid + * control character»). Outside a string tab, line feed and carriage + * return are whitespace to both, and anything else below a space is an + * unquoted token, which [strict] already refuses. */ fun parse(text: String): JsonElement? { + if (hasRawControlInString(text)) return null val element = try { json.parseToJsonElement(text) } catch (_: Exception) { @@ -49,6 +56,26 @@ internal object UpstreamJson { return element.takeIf(::strict) } + /** + * Whether a character below U+0020 stands unescaped between quotes. A + * backslash escapes the one character after it, so `\"` does not end the + * string and `\\` does not escape the quote after it. + */ + private fun hasRawControlInString(text: String): Boolean { + var inString = false + var escaped = false + for (c in text) { + when { + !inString -> if (c == '"') inString = true + escaped -> escaped = false + c == '\\' -> escaped = true + c == '"' -> inString = false + c < ' ' -> return true + } + } + return false + } + /** * Walked with a stack of its own rather than by recursion: kotlinx parses a * two-megabyte «[[[[…» without overflowing, and a recursive walk over what diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt index 4b5fcc63..e840151b 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInProblemTest.kt @@ -50,7 +50,7 @@ class DiarySignInProblemTest { row("certificate", UpstreamFailure.Untrusted(SSLHandshakeException("PKIX")), DiarySignInProblem.ProviderUntrusted(host), Action.NONE), row("captcha", UpstreamFailure.Unexpected("html"), - DiarySignInProblem.ProviderUnreadable(host), Action.RETRY), + DiarySignInProblem.ProviderUnreadable(host), Action.NONE), // Our server. row("no address", ServerAddressMissingException(), DiarySignInProblem.ServerMissing, Action.SET_SERVER), row("no network", IOException("unreachable"), DiarySignInProblem.Offline, Action.RETRY), @@ -61,7 +61,7 @@ class DiarySignInProblemTest { DiarySignInProblem.ReauthRequired, Action.RETYPE), row("409", http(409), DiarySignInProblem.ServerRefusedSession, Action.NONE), row("429 (#153)", http(429, "Retry-After" to "90"), DiarySignInProblem.TooManyAttempts(90), Action.WAIT), - row("502", http(502), DiarySignInProblem.ProviderUnreadable(null), Action.RETRY), + row("502", http(502), DiarySignInProblem.ProviderUnreadable(null), Action.NONE), row("503 disabled (#153)", http(503, DiaryFailure.UNAVAILABLE_HEADER to "disabled"), DiarySignInProblem.ServerDisabled, Action.NONE), row("503 address-refused (#153)", http(503, DiaryFailure.UNAVAILABLE_HEADER to "address-refused"), @@ -77,7 +77,7 @@ class DiarySignInProblemTest { row("read re-auth", DiaryFailure.ReauthRequired, DiarySignInProblem.ReauthRequired, Action.RETYPE), row("read signed out", DiaryFailure.SignInRequired, DiarySignInProblem.SignInRequired, Action.RETYPE), row("read down", DiaryFailure.Unavailable, DiarySignInProblem.ProviderUnavailable(null), Action.RETRY), - row("read unreadable", DiaryFailure.Unreadable, DiarySignInProblem.ProviderUnreadable(null), Action.RETRY), + row("read unreadable", DiaryFailure.Unreadable, DiarySignInProblem.ProviderUnreadable(null), Action.NONE), row("read offline", DiaryFailure.Offline(IOException("x")), DiarySignInProblem.Offline, Action.RETRY), row("read offline, no address", DiaryFailure.Offline(ServerAddressMissingException()), DiarySignInProblem.ServerMissing, Action.SET_SERVER), diff --git a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt index e5ca47e9..f7f2ab59 100644 --- a/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt +++ b/android/widget/src/main/kotlin/com/lumenpearson/lessons/widget/LessonsWidget.kt @@ -17,6 +17,7 @@ import androidx.glance.appwidget.provideContent import com.lumenpearson.lessons.core.data.di.Graph import com.lumenpearson.lessons.core.data.locale.AppLocale import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource import com.lumenpearson.lessons.core.model.AppLanguage import com.lumenpearson.lessons.core.model.DayState import com.lumenpearson.lessons.core.model.DeepLink @@ -206,9 +207,9 @@ class LessonsWidget : GlanceAppWidget() { // count as the family's activity and keep a session alive with nobody // behind it. Outside a class there is no class timetable to read, so // Room is not asked at all. - val mode = container.shellMode.current().mode - val timetable: Timetable? = - if (mode == ShellMode.CLASS) container.timetableRepository.snapshotAroundToday() else null + val (mode, timetable) = readModeAndTimetable(container.shellMode) { + container.timetableRepository.snapshotAroundToday() + } val settings = container.settingsRepository.settings.first() // The school's wall clock, not the phone's. These differ whenever the @@ -234,3 +235,19 @@ class LessonsWidget : GlanceAppWidget() { ) } } + +/** + * The mode the widget draws for, and the class timetable only in a class. + * + * Out of [LessonsWidget.loadSnapshot], which reads `Graph` and cannot be handed + * anything by a test, because this is the line the diary-only phone depends + * on: read from the class session instead, as it once was, a phone signed in + * to a diary and in no class drew the sentence sending it to join one. + */ +internal suspend fun readModeAndTimetable( + shell: ShellModeSource, + timetable: suspend () -> Timetable?, +): Pair { + val mode = shell.current().mode + return mode to if (mode == ShellMode.CLASS) timetable() else null +} diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetModeReadTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetModeReadTest.kt new file mode 100644 index 00000000..7f503345 --- /dev/null +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/WidgetModeReadTest.kt @@ -0,0 +1,73 @@ +package com.lumenpearson.lessons.widget + +import com.lumenpearson.lessons.core.data.repository.ShellMode +import com.lumenpearson.lessons.core.data.repository.ShellModeSource +import com.lumenpearson.lessons.core.data.repository.ShellState +import com.lumenpearson.lessons.core.data.repository.SyncArming +import com.lumenpearson.lessons.core.model.SchoolClassInfo +import com.lumenpearson.lessons.core.model.Timetable +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test + +/** + * Which mode the widget draws for, read the way the render reads it. + * + * The sentence a widget shows with nothing to draw is chosen by the mode, and + * a diary-only phone got the one sending it to join a class while the mode + * was read off the class session. `EmptyTextTest` holds the sentences for + * each mode it is handed; this holds that the render hands it the shell's. + */ +class WidgetModeReadTest { + + private val timetable = Timetable( + schoolClass = SchoolClassInfo(id = 1, name = "9А", timeZoneId = "Europe/Moscow"), + days = emptyList(), + ) + + private class Shell(private val mode: ShellMode) : ShellModeSource { + override val state: Flow = flowOf(ShellState(mode, held = false)) + override suspend fun current() = ShellState(mode, held = false) + override val syncArming: Flow = emptyFlow() + override suspend fun hold() = Unit + override suspend fun release() = Unit + override suspend fun settleColdStart() = current() + } + + @Test + fun `a diary-only phone is drawn as one, and its class cache is never read`() = runBlocking { + var reads = 0 + val (mode, read) = readModeAndTimetable(Shell(ShellMode.DIARY)) { + reads += 1 + timetable + } + + assertEquals(ShellMode.DIARY, mode) + assertNull(read) + assertEquals("outside a class Room is not asked at all", 0, reads) + } + + @Test + fun `every mode is the shell's, and only a class reads its timetable`() = runBlocking { + for (shell in ShellMode.entries) { + var reads = 0 + val (mode, read) = readModeAndTimetable(Shell(shell)) { + reads += 1 + timetable + } + assertEquals(shell, mode) + if (shell == ShellMode.CLASS) { + assertSame(timetable, read) + assertEquals(1, reads) + } else { + assertNull("$shell", read) + assertEquals("$shell", 0, reads) + } + } + } +} diff --git a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt index 6a2b26f4..b2ed2496 100644 --- a/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt +++ b/android/widget/src/test/kotlin/com/lumenpearson/lessons/widget/ui/EmptyTextTest.kt @@ -183,8 +183,12 @@ class EmptyTextTest { language = AppLanguage.SYSTEM, ) + /** + * That `snapshotOf` keeps the mode it is handed, and no more: which mode + * the render hands it is `WidgetModeReadTest`'s. + */ @Test - fun `the snapshot carries the mode it was read in`() { + fun `the snapshot keeps the mode it is handed`() { for (mode in ShellMode.entries) { assertEquals(mode, snapshot(mode, timetable = null).mode) } diff --git a/docs/app/guide.en.md b/docs/app/guide.en.md index 2d63ce9e..d5d26bf7 100644 --- a/docs/app/guide.en.md +++ b/docs/app/guide.en.md @@ -35,7 +35,7 @@ A fresh install does not open with the code field. It opens with five introducto - **School** — Only for Setevoy Gorod: the phone takes the list of schools straight from your region's diary server. - **The electronic diary** — The systems the region's schools use; one is marked “Recommended”, and “Why?” explains the choice. If a diary opens only through Gosuslugi, or the app cannot read it yet, its site opens instead — or you can use a class code. - **Sign-in** — The diary's login and password. The “Where the password goes” card names the diary's address: the password goes there and nowhere else, over HTTPS, and the server gets the session the diary hands out. -- **Loading** — The student, the terms, two weeks of timetable, homework and marks. If the account has several students, the app asks whose diary to show; if the load stops, “Try again” carries on from where it stopped. +- **Loading** — The student, the terms, two weeks of timetable, homework and marks. If the account has several students, the app asks whose diary to show; if the load stops, “Try again” carries on from where it stopped — and where trying again would change nothing (the account has no student, the diary does not let the server in, the diary answered in a way nobody could read), “Sign out of the diary and start over” is what remains. - **All set** — The student, the diary, the class if there is one, and the main settings. “Open the app” goes to the home screen. The app has no server of its own: the address comes from the class admin, or from whoever set a server up for your school. It goes into the “Server address” row — on the “How do you want to start?” screen, under the code field, or in Settings → Sync; on the way through your school you are asked for it when it is needed. It has to be the address the server is reachable at from the phone itself: “localhost” on a phone means the phone. @@ -150,9 +150,9 @@ Signing in takes the same login and password as the diary's own site. The form n Inside are two tabs — Timetable and Marks — and a child picker if the account sees more than one. Diary homework appears under the lessons of the day it is due on. An absence, a late arrival and a remark all arrive in the same list as the marks, but the app tells them apart and shows them differently. -What was loaded is kept on the phone and opens offline — the app then says it is showing what was saved, and when it was last updated. The app reads the diary again only while it is open: neither the background nor the widget ever reads it. That is also why the sign-in lasts while the app is being opened: after 30 days without that you sign in again, and the Petersburg diary may end the sign-in sooner. +What was loaded is kept on the phone and opens offline — the app then says it is showing what was saved, and when it was last updated. The app reads the diary again only while the diary is on screen: neither the background nor the widget ever reads it. That is also why the sign-in lasts while the diary is being opened — on a phone without a class that is the app itself, on one with a class it is Settings → Diary: after 30 days without that you sign in again, and the Petersburg diary may end the sign-in sooner. -“Sign out of the diary” is in the same place, Settings → Diary. The lessons and marks saved on the phone are deleted and the server forgets its copy of the sign-in; a phone with no class then goes back to “How do you want to start?”. +“Sign out of the diary” is in the same place, Settings → Diary. The lessons and marks saved on the phone are deleted and the server deletes its copy of the sign-in; a phone with no class then goes back to “How do you want to start?”. If the phone is offline at that moment, the server deletes the copy by itself 30 days after the diary was last used, and keeps a Setevoy Gorod session open until then. > The service belongs to somebody else and is undocumented. If it answers in a way the app cannot read, the app says so: that is fixed on the server, not in the app. diff --git a/docs/app/guide.ru.md b/docs/app/guide.ru.md index d8452f9c..15e0b127 100644 --- a/docs/app/guide.ru.md +++ b/docs/app/guide.ru.md @@ -35,7 +35,7 @@ - **Школа** — Только для «Сетевого города»: список школ телефон берёт прямо у сервера дневника вашего региона. - **Электронный дневник** — Системы, которыми пользуются школы региона; одна отмечена «Рекомендуем», и «Почему?» объясняет выбор. Если дневник открывается только через Госуслуги или приложение его пока не читает, откроется его сайт — или можно войти по коду класса. - **Вход** — Логин и пароль от дневника. Карточка «Куда уйдёт пароль» называет адрес дневника: пароль уходит только туда, по HTTPS, а сервер получает сессию, которую выдал дневник. -- **Загрузка** — Ученик, учебные периоды, расписание на две недели, задания и оценки. Если в аккаунте несколько учеников, приложение спросит, чей дневник показывать; если загрузка остановилась, «Повторить» продолжит с того же места. +- **Загрузка** — Ученик, учебные периоды, расписание на две недели, задания и оценки. Если в аккаунте несколько учеников, приложение спросит, чей дневник показывать; если загрузка остановилась, «Повторить» продолжит с того же места — а там, где повтор ничего не изменит (в аккаунте нет ученика, дневник не пускает сервер, дневник ответил непонятно), останется «Выйти из дневника и начать заново». - **Всё готово** — Ученик, дневник, класс, если он есть, и основные настройки. «Открыть приложение» ведёт на главный экран. Своего сервера у приложения нет: адрес даёт администратор класса или тот, кто поднял сервер для вашей школы. Его вводят в строке «Адрес сервера» — на экране «Как подключиться?», под полем кода или в «Настройки → Синхронизация»; на пути через свою школу его спросят, когда он понадобится. Адрес нужен тот, по которому сервер видит телефон: «localhost» для телефона означает его самого. @@ -150,9 +150,9 @@ Внутри две вкладки — «Расписание» и «Оценки» — и выбор ребёнка, если аккаунт видит нескольких. Задания дневника показываются под уроками того дня, к которому заданы. Пропуск, опоздание и замечание сервис кладёт в один список с оценками, но приложение их различает и показывает по-разному. -Загруженное хранится на телефоне и открывается без сети — тогда приложение пишет, что показано сохранённое, и когда оно обновлялось. Перечитывает дневник приложение, только пока оно открыто: ни в фоне, ни из виджета дневник не читается. Поэтому и вход держится, пока приложение открывают: после 30 дней без этого войти придётся заново, а дневник Петербурга может закончить вход и раньше. +Загруженное хранится на телефоне и открывается без сети — тогда приложение пишет, что показано сохранённое, и когда оно обновлялось. Перечитывает дневник приложение, только пока дневник открыт на экране: ни в фоне, ни из виджета дневник не читается. Поэтому и вход держится, пока открывают дневник — на телефоне без класса это само приложение, с классом — «Настройки → Дневник»: после 30 дней без этого войти придётся заново, а дневник Петербурга может закончить вход и раньше. -«Выйти из дневника» — там же, в «Настройки → Дневник». Уроки и оценки, сохранённые на телефоне, удаляются, а сервер забывает свою копию входа; телефон без класса после этого возвращается к выбору «Как подключиться?». +«Выйти из дневника» — там же, в «Настройки → Дневник». Уроки и оценки, сохранённые на телефоне, удаляются, а сервер удаляет свою копию входа; телефон без класса после этого возвращается к выбору «Как подключиться?». Если телефон в этот момент не в сети, сервер удалит копию сам — через 30 дней после того, как дневником пользовались в последний раз, а сессию «Сетевого города» до тех пор будет держать открытой. > Сервис чужой и недокументированный. Если он ответит непонятно, приложение так и скажет: это чинится на сервере, а не в приложении. diff --git a/server/tests/vectors/diary_protocol.json b/server/tests/vectors/diary_protocol.json index 744b9ca2..f71326db 100644 --- a/server/tests/vectors/diary_protocol.json +++ b/server/tests/vectors/diary_protocol.json @@ -91,7 +91,7 @@ {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": false, "expect": {"failure": "unexpected"}}, {"status": 200, "body": {"entryPoint": "/choose-session-role"}, "tried_role": true, "expect": {"failure": "bad_credentials", "message": null}} ], - "raw_answer_cases_about": "Answers given as the bytes the diary sent, for bodies no JSON value can stand for. The step's answer is replaced and the flow's own answers stand in for the rest. Whatever Python's json.loads refuses is unexpected on both sides, however lenient a parser could be about it: a single unquoted word, a leading zero, a bare word inside an object. NaN and Infinity are JSON to Python, so they are to the phone too.", + "raw_answer_cases_about": "Answers given as the bytes the diary sent, for bodies no JSON value can stand for. The step's answer is replaced and the flow's own answers stand in for the rest. Whatever Python's json.loads refuses is unexpected on both sides, however lenient a parser could be about it: a single unquoted word, a leading zero, a bare word inside an object. NaN and Infinity are JSON to Python, so they are to the phone too. A control character below a space inside a string is refused unless it is escaped; outside one, tab, line feed and carriage return are whitespace.", "raw_answer_cases": [ {"step": "logindata", "status": 200, "content_type": "text/html", "body": "", "expect": "unexpected"}, {"step": "logindata", "status": 200, "content_type": "application/json", "body": "{\"schoolLogin\": False}", "expect": "unexpected"}, @@ -103,7 +103,11 @@ {"step": "login", "status": 200, "content_type": "text/plain", "body": "OK", "expect": "unexpected"}, {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": abc}", "expect": "unexpected"}, {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"timeOut\": NaN}", "expect": "ok"}, - {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"timeOut\": -Infinity}", "expect": "ok"} + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"timeOut\": -Infinity}", "expect": "ok"}, + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"message\": \"a\tb\"}", "expect": "unexpected"}, + {"step": "login", "status": 200, "content_type": "application/json", "body": "{\"at\": \"x\", \"message\": \"a\\tb\"}", "expect": "ok"}, + {"step": "getdata", "status": 200, "content_type": "application/json", "body": "{\"salt\": \"3\u000133\", \"lt\": \"1\", \"ver\": \"2\"}", "expect": "unexpected"}, + {"step": "getdata", "status": 200, "content_type": "application/json", "body": "{\n\t\"salt\": \"333\",\r\n\t\"lt\": \"1\", \"ver\": \"2\"}", "expect": "ok"} ], "role_pick": [ {"body": {"accountInfo": {"userRoles": [{"role": {"id": 7, "name": "Учитель"}}, {"role": {"id": 12, "name": "Родитель"}}]}}, "expect": "12"}, From 6b0878f919ce42d0536f797e59ca97230d14c3d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 08:09:19 +0000 Subject: [PATCH 25/30] Close what an audit of the server half found before its migrations go on, each with a test that fails without its fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial audit of the server half of #140 and of revisions 0015/0016 had 22 findings survive two independent refuters each; 21 are fixed here. One of them already existed on main and has its own issue (#163); the rest are in code this pull request adds. The migrations themselves were compared op by op with the DDL the models produce and do not change on PostgreSQL. The ones that mattered most: - A «Сетевой город» 5xx or 429 error page was read as a dead session, so an outage upstream would have signed every family out, through the keep-alive and through any read. A status of 500 and above, or 429, is now «the diary is down» (503, session kept) whatever the body says; a non-JSON 2xx still means the session is gone. - The keep-alive checked its deadline before waiting for a slot, so pings went on starting past it and a hanging region could push the cron tick over Vercel's 30 seconds; the deadline is checked after the slot and every ping runs under a hard stop, so the results are always written. - A «Сетевой город» session kept the school year it was opened in and read an empty diary after it ended; a read past the sealed year asks for the current one again, at most once a diary-day. - Registrations were never counted, so one real session could mint unlimited kept-alive rows; a limiter now counts every session opened through /login or /session, and the keep-alive claims the stalest rows first so fresh ones cannot starve a family's. - The throttles counted before they recorded, so a burst of parallel requests went past them — 24 wrong passwords reached the diary against a limit of 10 (#163). Every door now records first and counts after. And: a weekly answer that is not an object, a body that will not decode, and a years/current without a usable year were 500s or a 200-then-401 loop; they are 502/503 now, refused at registration where they would loop. The bot's page no longer tells a family whose account has no pupil that the diary «ответил непонятно», nor a Госуслуги-only region to «попробуйте ещё раз». 0015 now works on an existing SQLite database and on an empty PostgreSQL that 0001 already built, and its downgrade no longer leaves a class looking bound to Petersburg; its PostgreSQL upgrade is unchanged, and a new test pins it to the model as test_quota does for 0016. Seven tests that could not fail now can: the cron tick calling the keep-alive, the protocol vectors' credential fields, the directory's own bucket, the invisible-to-the-bot check, and the Postgres statements of the quota and the throttle, which are now compiled in tests. Left open, on purpose, for the owner: a session registered from a phone names its own login and nothing upstream vouches for it, while corrections are filed under that login — so a second account that can see the same child could claim the first account's login and reach its corrections. Every fix is a product choice (whose corrections a phone sees), and it is put to the owner rather than decided here. Gates: ruff clean, mypy clean (100 files), pytest -n auto 1998 passed (1944 before). Not run: alembic against a real empty PostgreSQL (the permission system refused a local server), and the throttle's atomicity on PostgreSQL, which rests on READ COMMITTED. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- docs/api.md | 36 ++- docs/architecture.md | 10 + docs/bot.md | 17 +- docs/deploy.md | 11 +- server/app/api/diary.py | 139 ++++++--- server/app/api/diary_web.py | 34 ++- server/app/api/directory.py | 13 +- server/app/api/public.py | 19 +- server/app/bot/handlers/manage.py | 13 +- server/app/providers/netschool/client.py | 27 +- server/app/providers/netschool/provider.py | 92 +++++- server/app/security.py | 98 +++++- server/app/services/diary_keepalive.py | 46 ++- server/app/services/diary_link.py | 19 ++ .../0013_one_homework_per_subject_per_day.py | 13 + .../versions/0015_diary_provider_columns.py | 96 ++++-- server/tests/test_api_extended.py | 89 ++++++ server/tests/test_bot_manage.py | 105 ++++++- server/tests/test_diary_keepalive.py | 222 ++++++++++++++ server/tests/test_diary_protocol_vectors.py | 20 ++ server/tests/test_diary_provider_revision.py | 278 ++++++++++++++++++ server/tests/test_diary_session.py | 264 ++++++++++++++++- server/tests/test_diary_web.py | 114 +++++++ server/tests/test_directory.py | 85 +++++- server/tests/test_netschool_client.py | 36 +++ server/tests/test_quota.py | 55 ++++ 26 files changed, 1814 insertions(+), 137 deletions(-) create mode 100644 server/tests/test_diary_provider_revision.py diff --git a/docs/api.md b/docs/api.md index f277fe97..d8a616a0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -963,11 +963,15 @@ any read. The same tick also **keeps «Сетевой город» sessions alive**. That diary idles a session out in 15–60 minutes and this project stores no password to sign back in with, so the tick pings -each live one with `GET /webapi/context`, within a batch cap and a time budget, and never +each live one with `GET /webapi/context`, within a batch cap of 200 taken stalest first +(by the last ping, or for a row never pinged the moment the diary last took it), and a time +budget — no ping starts after 18 seconds of the tick and none is waited for past 24, so the +results are always written before the platform's 30-second ceiling. It never touches `last_used_at` — a ping must not look like the family using the session, or the 30-day purge above would never fire. `diary_sessions_kept_alive` is how many were pinged alive, `diary_sessions_lost` how many the upstream had already dropped (they are expired, and -the app is told to sign in again), and `diary_keepalive_failed` is `true` when the keep-alive +the app is told to sign in again — a `401` or a login page only: a regional server answering +a `5xx` or `429`, an HTML error page included, is down, and its sessions are left as they are), and `diary_keepalive_failed` is `true` when the keep-alive itself raised — isolated so a diary fault never fails the whole tick and reddens the fallback clock. Petersburg sessions are not pinged; they refresh from their own answers. This depends on the external cron, not GitHub's fallback clock, which is too sparse to keep a session @@ -1135,8 +1139,8 @@ and `null` for Petersburg. | `403` | the diary took the session, and there is no pupil behind the account — a staff account, or a pupil's own account that does not list itself | yes | | `409` | the diary refused, **from this server's address**, the session it had just handed the client. It is not the password | yes | | `422` | not one of the two shapes, a value that cannot be sent upstream whole, or a region this server does not sign in to. `detail` names what was wrong and **never repeats the value**: FastAPI's validation answer normally echoes each refused value as `input`, and here that value is a session or a password | no | -| `429` | ten counted failures from this address within fifteen minutes, on `/login` and `/session` together; `Retry-After` says how long | — | -| `502` | the diary answered something nobody can read | yes | +| `429` | ten counted failures, or twenty sessions opened, from this address within fifteen minutes, on `/login` and `/session` together; `Retry-After` says how long | — | +| `502` | the diary answered something nobody can read — for «Сетевой город», that includes a current school year without an id or its dates, since no read can be made without them | yes | | `503` | the diary is off on this server, refuses this server's address, or is not answering; `X-Diary-Unavailable` says which (see [Error codes](#error-codes)) | no | **`409` rather than `/login`'s `401` + `X-Diary-Reauth`.** The session worked on the client @@ -1152,6 +1156,11 @@ It shares `/login`'s limiter **and its bucket**, so ten wrong passwords on one d ten more tries on the other. What is counted follows the same line as `/login`'s: whatever the upstream judged, which includes the `409` a replay of a session that was never real produces; what is forgiven is what never reached it, or reached a diary that did not answer. +A `200` is counted too, on a limit of its own: **twenty sessions opened per address in +fifteen minutes**, through either door. A session is not free once it is open — the cron +pings every «Сетевой город» one from this server's address for as long as it lives — and +counting failures alone let one real session be replayed into `/session` without end, each +replay a new row in the keep-alive's queue. **A registered session belongs to no class and no Telegram account.** The row carries neither, so the bot's «📒 Мой дневник» does not see it; a phone and the bot hold separate @@ -1201,11 +1210,16 @@ be re-minted whenever either half changed. Failed sign-ins are rate-limited per client address, ten per fifteen minutes, in a bucket of their own shared by `/login` and `/session`: ten wrong diary passwords must not spend a -phone's thirty `/join` attempts, nor buy ten more tries by session. Past that both answer -`429` with `Retry-After`, and it is counted in the database, like the join limiter, because -nothing in this deployment survives between requests. What the limit is for is that this -server's address must not become a way of guessing passwords against somebody else's school -diary. +phone's thirty `/join` attempts, nor buy ten more tries by session. Sessions opened are held +to twenty per address in the same fifteen minutes, in a bucket of their own. Past either +limit both answer `429` with `Retry-After`, and it is counted in the database, like the join +limiter, because nothing in this deployment survives between requests. What the limit is for +is that this server's address must not become a way of guessing passwords against somebody +else's school diary. **An attempt is counted before the diary is asked, and handed back once +it turns out not to be one** (a success for the failure count, a failure for the session +count, a `503` for both): counted after the answer, as it used to be, forty guesses sent at +once all read a count from before any of them had been written, and two dozen reached the +diary inside a window whose limit is ten. The same holds for `/join` and the directory. ### What can be asked @@ -1319,11 +1333,11 @@ where they are visible as corrections and are reversible. | `404` | this account has no such child | — | | `409` | on `/diary/session` only: the diary will not take this session from this server | say it is not the password; do not retry by itself | | `422` | on reads, the date range is inverted or wider than 62 days; on `PUT .../overrides`, the correction was refused: an unknown `target`, an uncorrectable field, or an empty value where empty is not allowed; on `/login` and `/session`, a body or a region this server will not sign in with | on a read, fix the range; on a correction, show `detail` | -| `429` | on `/diary/login` and `/diary/session` together, ten counted failures from this address inside fifteen minutes | wait out `Retry-After`, and do not blame the password | +| `429` | on `/diary/login` and `/diary/session` together, ten counted failures or twenty sessions opened from this address inside fifteen minutes | wait out `Retry-After`, and do not blame the password | | `502` | the diary answered incomprehensibly | say that the service has changed | | `503` + `X-Diary-Unavailable: disabled` | this deployment has no `DIARY_SECRET`; the diary is off here | say it is off on this server; nothing typed will help | | `503` + `X-Diary-Unavailable: address-refused` | the region's server drops this server's address | say it is not the password, and not worth retrying | -| `503` + `X-Diary-Unavailable: upstream` | the diary is not answering, or at sign-in answered that it takes only Госуслуги | offer to retry later | +| `503` + `X-Diary-Unavailable: upstream` | the diary is not answering — a timeout, a `5xx` or a `429`, whatever the body, an HTML error page included — or at sign-in answered that it takes only Госуслуги | offer to retry later; the session is kept | **Every `503` under `/api/v1/diary` carries `X-Diary-Unavailable`**, `/login`'s included, because the three cases want three different sentences and `detail` is Russian prose a diff --git a/docs/architecture.md b/docs/architecture.md index 585d8fcb..7364f4d6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -696,6 +696,16 @@ reaching for the last unit cannot both have it — there is no read-then-write t request it pays for, and the empty-answer retry asks for its own unit first, because DaData counts a request whatever comes of it. +The per-caller throttle had a read-then-write of its own, and so did every door on it — `/join`, +the diary's `/login` and `/session`, and the directory: two SELECTs to check, an INSERT to +record, later, with nothing between. A burst of concurrent requests from one address all read +the count from before any of them was written; forty wrong diary passwords sent at once put +two dozen through a limit of ten. `JoinThrottle.admit` now writes the attempt first and counts +after the commit, so the n-th attempt to commit sees at least n rows and no more than the limit +are let through however they overlap; a door that counts only failures hands the row back +(`forgive`) once it knows it was not one. On SQLite that is a test with a burst in it; on +Postgres it rests on READ COMMITTED showing each statement every commit before it. + The day is Moscow's (`services/quota.py:QUOTA_ZONE`), not UTC and not the server's. DaData is a Moscow company and its allowance is assumed to turn at Moscow midnight — assumed, because nothing in its documentation says which clock it counts by. If the assumption is wrong and it diff --git a/docs/bot.md b/docs/bot.md index bea91b7a..e79b6dc0 100644 --- a/docs/bot.md +++ b/docs/bot.md @@ -513,8 +513,13 @@ bot never saw it, which was never true; a test now fails on the old wording. The claim about the app either way: an app built before registration still posts the password to this server, and the page cannot tell which one the reader holds. -The form re-reads the class's binding at both the GET and the submit, so a class unbound or -rebound since the link was made refuses before the password is sent, rather than sending it to a diary the family is no longer looking at. A ticket is +A class unbound since the link was made refuses at the GET and at the submit, before the +password is sent and without spending the ticket. Rebinding is the harder half, because the +submit finds a binding and it is the wrong one: re-reading it would send a password typed +under «Санкт-Петербург» to «Сетевой город», or the other way round. So every change to the +binding — «📒 Дневник: отвязать», a pick of Petersburg, a pick of a school — drops the class's +outstanding tickets in the same commit, and a form opened before it answers `410` with no +upstream call. The family asks the bot for a new link, which names the diary bound now. A ticket is worth **one** sign-in for fifteen minutes for one Telegram account in one class; a GET checks it without spending it (Telegram fetches link previews by itself), a POST spends it before @@ -528,7 +533,13 @@ page says so in words rather than blaming the password, which is what it used to do for every failure that was not a plain 401, and names the bound diary's own address to open in a browser — taken from the allow-list, never from anything typed. It used to name dnevnik2 whatever the class was bound to, which sent a «Сетевой город» family -to Петербург's diary to see whether theirs was down (#158). +to Петербург's diary to see whether theirs was down (#158). Two refusals get sentences of +their own rather than that one. A region that answers it takes only Госуслуги is a `503` +that keeps the ticket — no password was sent — and points at Госуслуги on the region's own +server instead of saying «попробуйте ещё раз» under «логин и пароль тут не подойдут». An +account the diary accepted but that lists no pupil is a `403` that spends it — the password +was judged — and says «В этой учётной записи нет ученика», with a new link for a parent's or +a pupil's account, instead of «ответил непонятно» and a link that fails the same way. The session is stored encrypted (`DIARY_SECRET`, `app/crypto.py`). Without that key the whole feature refuses at the door rather than falling back to diff --git a/docs/deploy.md b/docs/deploy.md index 1b137ea2..c7e7050d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -328,7 +328,9 @@ columns a second diary provider needs: `diary_sessions.provider` and `region` an keep-alive clocks, and `classes.diary_region`, `diary_school_id` and `diary_school_name` — eight nullable columns, additive, to go on before the merge. Its downgrade expires every non-Petersburg session first, so code rolled back past this revision cannot read a «Сетевой -город» credential as Petersburg's and replay it at the wrong upstream. `0016` creates +город» credential as Petersburg's and replay it at the wrong upstream, and unbinds every +class bound to «Сетевой город», which the old code would call «Санкт-Петербург» on the +admin's card and «не привязан» behind the diary button. `0016` creates `usage_counters` — one row per external allowance per Moscow day, the anonymous school directory's share of DaData's — and nothing else: one new table, no existing row read or rewritten, additive, and it goes on **together with `0015`, before #140 merges**. Its @@ -336,7 +338,12 @@ downgrade drops the table, which loses nothing but the counts. Everything up to `0012` checks with an inspector what is not in the database yet and does not rewrite existing tables, so those can be applied to a live class in the middle of a -school day. The head is `0016`. +school day. `0013`, `0015` and `0016` ask the inspector too — per constraint, per column, +per table — because on an empty database `0001` has already built today's schema, and a +second `ADD COLUMN` or `ADD CONSTRAINT` there is a hard error that stops the `migrate` +service below; and because a SQLite file `scripts.init_db` built before a model change is +stamped at the old head without the new columns, and only the revision adds them. The head +is `0016`. ### A migration goes BEFORE the deploy, not after diff --git a/server/app/api/diary.py b/server/app/api/diary.py index 1be523b3..1bb27393 100644 --- a/server/app/api/diary.py +++ b/server/app/api/diary.py @@ -72,7 +72,7 @@ NetSchoolCapabilitiesOut, NetSchoolSessionIn, ) -from app.security import JoinThrottle +from app.security import Admission, JoinThrottle from app.services import diary as service from app.services import diary_overrides as overrides @@ -262,17 +262,77 @@ async def _guard(awaitable): #: mistakes, and only failures are counted. diary_login_limiter = JoinThrottle(limit=10, window=900.0) +#: Sessions one caller may open in a quarter of an hour, through either door. +#: +#: The limit above counts failures only, so a caller whose every attempt +#: *succeeds* was never limited at all — and a success is not free. Each one +#: is a new row the cron keeps alive with a ping from this server's address, +#: for up to thirty days, and nothing ties a row to anything but itself: one +#: real «Сетевой город» session replayed into `/session` a few thousand times +#: was a few thousand rows, four bootstrap calls each, and a keep-alive queue +#: that pinged one account over and over from an address the region can block +#: for everybody. Twenty is a household's phones signing in again with room to +#: spare; the window is the other limiters', as `JoinThrottle` requires. +diary_open_limiter = JoinThrottle(limit=20, window=900.0) + +_THROTTLED_DETAIL = "Слишком много попыток входа. Попробуйте позже." + + +class _Attempt: + """One attempt on either door, counted by both diary limiters until the + outcome says which of the two it was. + + Counted *before* the upstream is asked, not after (see + `JoinThrottle.admit`): recorded after, a burst of concurrent wrong + passwords all read the count from before any of them and all reached the + diary. The same limiter **and bucket** for `/login` and `/session`, so a + caller who spent ten wrong passwords does not get ten more tries by + session. + """ -async def _refuse_if_throttled(session: AsyncSession, client: str) -> None: - """429 while ``client`` has spent its failures. One check for both doors - onto the upstream, so they cannot drift into two limits.""" - retry_after = await diary_login_limiter.blocked_for(session, client) - if retry_after is not None: - raise HTTPException( - status_code=status.HTTP_429_TOO_MANY_REQUESTS, - detail="Слишком много попыток входа. Попробуйте позже.", - headers={"Retry-After": str(int(retry_after) + 1)}, + __slots__ = ("failures", "opened") + + def __init__(self, failures: Admission, opened: Admission) -> None: + self.failures = failures + self.opened = opened + + @classmethod + async def admit(cls, session: AsyncSession, request: Request) -> _Attempt: + """Count the attempt, or 429 while the caller has spent either limit.""" + failures = await diary_login_limiter.admit( + session, caller_bucket(request, scope="diary:") + ) + if failures.retry_after is not None: + raise _throttled(failures.retry_after) + opened = await diary_open_limiter.admit( + session, caller_bucket(request, scope="diary-open:") ) + if opened.retry_after is not None: + await diary_login_limiter.forgive(session, failures) + raise _throttled(opened.retry_after) + return cls(failures, opened) + + async def succeeded(self, session: AsyncSession) -> None: + """A session was opened: not a failure, and one of the twenty.""" + await diary_login_limiter.forgive(session, self.failures) + + async def failed(self, session: AsyncSession) -> None: + """The upstream judged it and said no: a failure, and no session.""" + await diary_open_limiter.forgive(session, self.opened) + + async def not_judged(self, session: AsyncSession) -> None: + """Nothing looked at what was sent — the feature off, the diary down, + the address refused: neither.""" + await diary_login_limiter.forgive(session, self.failures) + await diary_open_limiter.forgive(session, self.opened) + + +def _throttled(retry_after: float) -> HTTPException: + return HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=_THROTTLED_DETAIL, + headers={"Retry-After": str(int(retry_after) + 1)}, + ) def _served_region(key: str | None) -> str: @@ -329,17 +389,19 @@ async def login( upstream session eventually expires, requests answer 401 with ``X-Diary-Reauth: required`` and the app asks for it again. """ - # A bucket of its own, asked for through `caller_bucket` rather than built - # by putting «diary:» in front of what it returns. The counter's column is - # `VARCHAR(64)` and the digest already fills it, so the prefix made every - # recorded failure six characters too long for Postgres: the insert raised - # out of the `except` that was recording it, so a wrong password answered - # 500 instead of 401 and nothing was ever counted — the limit below existed - # only in the tests, where SQLite does not enforce a width. - client = caller_bucket(request, scope="diary:") - await _refuse_if_throttled(session, client) - + # The buckets are `_Attempt.admit`'s, asked for through `caller_bucket` + # rather than built by putting «diary:» in front of what it returns. The + # counter's column is `VARCHAR(64)` and the digest already fills it, so the + # prefix made every recorded failure six characters too long for Postgres: + # the insert raised out of the `except` that was recording it, so a wrong + # password answered 500 instead of 401 and nothing was ever counted — the + # limit existed only in the tests, where SQLite does not enforce a width. + # + # The target is checked before the attempt is counted: a region we do not serve is a 422 + # that nothing upstream saw, and counting it would charge the caller for + # our refusal. provider, region, school_id = _resolve_login_target(payload) + attempt = await _Attempt.admit(session, request) try: token, row = await _guard( @@ -360,6 +422,7 @@ async def login( # per attempt, and nothing for the app to put on the screen. The other # door onto the same service, ``POST /diary/signin``, has always # answered 503 and said so in words; this is that answer. + await attempt.not_judged(session) raise _disabled() from failure except HTTPException as refusal: # Everything but a 503 counts, and the line is drawn where the other @@ -380,9 +443,12 @@ async def login( # 503 is the one that is safe to forgive, and it is safe for the reason # `diary_web` names: it means the feature is off, or the transport # failed, or the upstream answered 5xx — nothing read what was typed. - if refusal.status_code != status.HTTP_503_SERVICE_UNAVAILABLE: - await diary_login_limiter.record_failure(session, client) + if refusal.status_code == status.HTTP_503_SERVICE_UNAVAILABLE: + await attempt.not_judged(session) + else: + await attempt.failed(session) raise + await attempt.succeeded(session) return DiaryLoginOut(token=token, login=row.login) @@ -466,22 +532,22 @@ async def register_session( phone forgets its copy. Nothing here stores or accepts a password: a ``password`` key anywhere in the body is a 422. - Shares ``/login``'s limiter **and bucket**, so a caller who spent ten - wrong passwords does not get ten more tries by session. Counted: a session - the upstream refused (409), an account with no pupil (403), an answer - nobody can read (502). Not counted: anything that never reached the - upstream (422), the feature being off, or the upstream not answering (503). + Shares ``/login``'s limiters **and buckets**, so a caller who spent ten + wrong passwords does not get ten more tries by session. Counted as a + failure: a session the upstream refused (409), an account with no pupil + (403), an answer nobody can read (502). Counted as a session opened: a 200, + twenty to a caller in fifteen minutes across both doors. Not counted: + anything that never reached the upstream (422), the feature being off, or + the upstream not answering (503). 409 rather than ``/login``'s 401 + ``X-Diary-Reauth``, because asking for the password again would loop: the session was good on the phone seconds ago, and it is *this server* the diary will not take it from. """ - # The same limiter and the same bucket as /login: a separate one would - # double what one caller may try against the upstream from our address. - client = caller_bucket(request, scope="diary:") - await _refuse_if_throttled(session, client) - provider, region, school_id = _resolve_session_target(payload) + # The same limiters and buckets as /login: separate ones would double what + # one caller may try against the upstream from our address. + attempt = await _Attempt.admit(session, request) # The provider's own serialisation: Petersburg's bare token, or the JSON of # what «Сетевой город» handed the phone, with the fields it did not hand # left out rather than stored as nulls. @@ -501,13 +567,15 @@ async def register_session( school_id=school_id, ) except service.DiaryDisabled as failure: + await attempt.not_judged(session) raise _disabled() from failure except UpstreamUnavailable as failure: # Nothing judged the session: the diary did not answer, or will not # talk to this address at all. Forgiven, like /login's 503. + await attempt.not_judged(session) raise _unavailable(failure) from failure except NoStudents as failure: - await diary_login_limiter.record_failure(session, client) + await attempt.failed(session) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=failure.message ) from failure @@ -515,16 +583,17 @@ async def register_session( # Before the broader DiaryError below, and after NoStudents, which is # a SessionExpired too. Counted: this is also what a replay of a # session that was never real looks like. - await diary_login_limiter.record_failure(session, client) + await attempt.failed(session) raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=REFUSED_FROM_HERE_DETAIL ) from failure except DiaryError as failure: - await diary_login_limiter.record_failure(session, client) + await attempt.failed(session) raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail=failure.message ) from failure + await attempt.succeeded(session) return DiarySessionOut( token=registered.token, login=registered.row.login, diff --git a/server/app/api/diary_web.py b/server/app/api/diary_web.py index 9fa27aa4..c055dd78 100644 --- a/server/app/api/diary_web.py +++ b/server/app/api/diary_web.py @@ -57,6 +57,7 @@ from app.providers.diary.errors import ( BadCredentials, DiaryError, + NoStudents, SignInUnsupported, UpstreamUnavailable, ) @@ -356,7 +357,7 @@ async def sign_in_submit( return _closed( verdict.message, status=verdict.status, - note=_TRY_AGAIN if verdict.keep_ticket else _ASK_AGAIN, + note=verdict.note or (_TRY_AGAIN if verdict.keep_ticket else _ASK_AGAIN), ) except Exception: # noqa: BLE001 - never let an upstream shape reach the page log.exception("diary sign-in failed") @@ -386,6 +387,10 @@ class _Verdict(NamedTuple): #: True when the failure was the diary's rather than the person's, so the #: ticket goes back and the same link still opens the form. keep_ticket: bool + #: What to do next, when neither «попробуйте ещё раз» nor «запросите + #: ссылку заново» is true. Chosen by `keep_ticket` alone, the Госуслуги + #: refusal told the family to retry what it had just said cannot work. + note: str | None = None def _site_of(binding: Binding) -> str: @@ -424,8 +429,28 @@ def _why(error: DiaryError, binding: Binding) -> _Verdict: if isinstance(error, SignInUnsupported): # Decided before any password was sent, so the ticket goes back — but # retrying will not help, so the note points at Госуслуги rather than - # «попробуйте снова». - return _Verdict(error.message, 502, keep_ticket=True) + # «попробуйте снова». A 503, as `/api/v1/diary/login` answers it: the + # region's own answer about who it lets in, not a reply nobody can read. + return _Verdict( + error.message, + 503, + keep_ticket=True, + note=f"Дневник региона открывается через Госуслуги на {_site_of(binding)}.", + ) + if isinstance(error, NoStudents): + # The password was accepted and there is no pupil behind the account — + # staff-only, or a pupil's account that does not list itself. Before + # the generic branch below, which it is a subclass of the family of: + # there it was «ответил непонятно … откройте сайт», sending the family + # to check a diary that is up and to ask for a link that fails the + # same way. The ticket is spent: the password was judged. + return _Verdict( + error.message, + 403, + keep_ticket=False, + note="Войдите под учётной записью родителя или ученика — " + "попросите у бота новую ссылку.", + ) if isinstance(error, BadCredentials): # PasswordExpired and any other BadCredentials with its own words keep # them; the bare base message becomes the fixed «неверный пароль». @@ -435,7 +460,8 @@ def _why(error: DiaryError, binding: Binding) -> _Verdict: if isinstance(error, UpstreamUnavailable): # AddressRefused lands here too, with its own «дело не в пароле» words. return _Verdict(error.message, 503, keep_ticket=True) - # UnexpectedResponse, SessionExpired and any future member of the family. + # UnexpectedResponse, SessionExpired bar NoStudents, and any future member + # of the family. # The address is named on purpose: opening the diary in a browser is the # one check that tells the person which of the two is broken, and it is # also where a captcha would be waiting for them. diff --git a/server/app/api/directory.py b/server/app/api/directory.py index fd1aa2e2..ec97e700 100644 --- a/server/app/api/directory.py +++ b/server/app/api/directory.py @@ -93,23 +93,26 @@ async def school_regions( # and hashed with the scope inside it — see `caller_bucket` for why a # prefix on the digest is a 500 on Postgres. client = caller_bucket(request, scope="directory:") - retry_after = await directory_limiter.blocked_for(session, client) - if retry_after is not None: + # Counted first and handed back on a 422, rather than checked here and + # recorded after the validation: between a check and a later record, every + # request of a parallel burst from one address read the count from before + # any of them, and each went on to spend the anonymous share. + attempt = await directory_limiter.admit(session, client) + if attempt.retry_after is not None: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail=THROTTLED_DETAIL, - headers={"Retry-After": str(int(retry_after) + 1)}, + headers={"Retry-After": str(int(attempt.retry_after) + 1)}, ) try: query = schools_service.normalise_query(q) except schools_service.SearchError as error: + await directory_limiter.forgive(session, attempt) raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(error) ) from error - await directory_limiter.record(session, client) - if not schools_service.available(): raise _unavailable(DISABLED_DETAIL, "disabled") diff --git a/server/app/api/public.py b/server/app/api/public.py index b6d841b7..ba0778df 100644 --- a/server/app/api/public.py +++ b/server/app/api/public.py @@ -347,12 +347,15 @@ async def join( not been true of every token since invites existed. """ client = caller_bucket(request) - retry_after = await join_limiter.blocked_for(session, client) - if retry_after is not None: + # Counted before the code is looked at, and handed back below on every + # answer that is not a wrong code: see `JoinThrottle.admit` for why a check + # followed by a later record let a concurrent burst through. + attempt = await join_limiter.admit(session, client) + if attempt.retry_after is not None: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many join attempts", - headers={"Retry-After": str(int(retry_after) + 1)}, + headers={"Retry-After": str(int(attempt.retry_after) + 1)}, ) code = payload.code.strip().upper() @@ -373,6 +376,7 @@ async def join( # stop somebody walking the code space, and this caller has already # found a code — counting it would let a class that switched to invites # lock out everybody who still had the old one. + await join_limiter.forgive(session, attempt) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Этот класс принимает только по личному приглашению из бота", @@ -384,7 +388,7 @@ async def join( school_class = await session.get(SchoolClass, invite.class_id) if school_class is None: - await join_limiter.record_failure(session, client) + # The one answer that stays counted: the attempt `admit` wrote is it. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown join code") # Spent before the token is minted, not after: the update is what makes @@ -396,8 +400,10 @@ async def join( # spent by the time it was written. Not counted against the limiter, # for the same reason the 403 above is not — this caller had a real # code, and the limiter is there for somebody who does not. + await join_limiter.forgive(session, attempt) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown join code") + token = new_token() session.add( DeviceToken( @@ -426,6 +432,11 @@ async def join( f"телефон подключён по личному коду: {payload.device_name or 'без названия'}", ) await session.commit() + # A real code: only failures are counted, so a classroom joining from one + # school NAT is never blocked by each other's successes. After the commit + # above, which is the join, so the invite's burn and the token land in one + # transaction as they always did. + await join_limiter.forgive(session, attempt) return JoinResponse( token=token, class_id=school_class.id, diff --git a/server/app/bot/handlers/manage.py b/server/app/bot/handlers/manage.py index b5bad8d5..cb4d118b 100644 --- a/server/app/bot/handlers/manage.py +++ b/server/app/bot/handlers/manage.py @@ -120,7 +120,7 @@ from app.providers.netschool import regions as ns_regions from app.providers.netschool.client import NetSchoolClient from app.services import access as access_service -from app.services import audit, linking, structure, timetable_io +from app.services import audit, diary_link, linking, structure, timetable_io from app.services import calendar as calendar_service from app.services import diary as diary_service from app.services import stats as stats_service @@ -2398,6 +2398,10 @@ async def class_diary_bind( school_class.diary_region = None school_class.diary_school_id = None school_class.diary_school_name = None + # An outstanding sign-in link would still open a form; the submit + # refuses an unbound class, but only a dropped ticket survives a + # rebind that follows at once (#137). + await diary_link.drop_for_class(session, school_class.id) await audit.record( session, school_class.id, callback.from_user.id, "class.diary", "дневник отвязан" ) @@ -2434,7 +2438,10 @@ async def class_diary_provider( school_class.diary_school_name = None # The members' «Сетевой город» sessions read a diary the class has # left; expired in the same commit as the binding they no longer fit. + # And the sign-in links minted under the old binding go with it, or a + # form drawn for one diary sends its password to the other (#137). await diary_service.expire_off_binding(session, school_class) + await diary_link.drop_for_class(session, school_class.id) await audit.record( session, school_class.id, callback.from_user.id, "class.diary", "привязан дневник Санкт-Петербурга", @@ -2593,8 +2600,10 @@ async def class_diary_school( school_class.diary_school_name = str(school["name"])[:300] # Sessions on another region's server, or Petersburg's, read a diary the # class has left: expired with the binding, so the keep-alive stops - # pinging a server nobody here uses. The same region keeps them. + # pinging a server nobody here uses. The same region keeps them. The + # sign-in links go whatever the region: each names one school (#137). await diary_service.expire_off_binding(session, school_class) + await diary_link.drop_for_class(session, school_class.id) await audit.record( session, school_class.id, callback.from_user.id, "class.diary", f"привязан «Сетевой город»: {region.title}, {str(school['name'])[:200]}", diff --git a/server/app/providers/netschool/client.py b/server/app/providers/netschool/client.py index 9ca97c89..f4e83b89 100644 --- a/server/app/providers/netschool/client.py +++ b/server/app/providers/netschool/client.py @@ -259,6 +259,12 @@ async def _send( if "reset" in text or "refused" in text or "denied" in text: raise AddressRefused from error raise UpstreamUnavailable from error + except httpx.HTTPError as error: + # A body whose Content-Encoding does not decode is not a + # TransportError, and walked out of here as a bare 500 — on + # `/session`, `/login` and the sign-in page alike. Petersburg's + # client and DaData's already read it as the upstream failing. + raise UpstreamUnavailable from error if self._looks_refused(response): raise AddressRefused return response @@ -287,9 +293,22 @@ async def _authed_json(self, method: str, path: str, **kwargs: Any) -> Any: raise SessionExpired if response.status_code == 401 or response.is_redirect: raise SessionExpired + status = response.status_code + if status >= 500 or status == 429: + # Before the content-type rule below, and whatever the body is: an + # outage arrives as nginx's or IIS's HTML error page, and read as a + # login page it expired every session on the region in one + # keep-alive tick, and each family's own read expired theirs — with + # no password stored to sign back in with. + raise UpstreamUnavailable + if status >= 400: + # 401 is above and 403 never gets past `_send`. Any other 4xx is + # not an answer to read as data: a 404 `{"message": …}` from + # `years/current` used to be sealed as a year with no id. + raise UnexpectedResponse ctype = response.headers.get("content-type", "") if "json" not in ctype: - # A non-JSON 200 on an authenticated call is a login page: the + # A non-JSON 2xx on an authenticated call is a login page: the # session is gone, which is «войдите снова», not «непонятно». raise SessionExpired self._absorb_cookies(response) @@ -583,12 +602,16 @@ async def terms_search(self, group_id: int | None) -> Any: headers=headers, timeout=_TIMEOUT, ) - except httpx.TransportError as error: + except httpx.HTTPError as error: + # TransportError and a body that will not decode alike: see `_send`. raise UpstreamUnavailable from error if self._looks_refused(response): raise AddressRefused if response.status_code == 401 or response.is_redirect: raise SessionExpired + if response.status_code >= 500 or response.status_code == 429: + # An outage, not a list of terms: see `_authed_json`. + raise UpstreamUnavailable if response.status_code in (404, 405): return [] # this server has no such endpoint try: diff --git a/server/app/providers/netschool/provider.py b/server/app/providers/netschool/provider.py index b7debf1f..551b5f97 100644 --- a/server/app/providers/netschool/provider.py +++ b/server/app/providers/netschool/provider.py @@ -11,7 +11,9 @@ `NetSchoolConnection` walks the diary a week at a time, because the route is a week at a time in every client, and clips each walk to the school year's bounds so a session kept alive across 1 September does not ask for a year that has -ended. A credential that will not parse makes every call +ended — and asks ``years/current`` again, at most once a day, when a read runs +past the sealed year's end, so that same session moves on to the new year +rather than reading an empty one. A credential that will not parse makes every call :class:`SessionExpired`, so a key rotation expires the row rather than 500ing. """ @@ -37,7 +39,12 @@ Teacher, ) from app.providers.netschool import mapper as m -from app.providers.netschool.client import CREDENTIAL_VERSION, SESSION_COOKIES, NetSchoolClient +from app.providers.netschool.client import ( + CREDENTIAL_VERSION, + SESSION_COOKIES, + NetSchoolClient, + _json_int, +) from app.providers.netschool.regions import Region from app.providers.netschool.regions import get as region_for from app.timezones import resolve @@ -127,14 +134,46 @@ async def teachers(self, education_id: int) -> list[Teacher]: # noqa: ARG002 async def attendance(self, education_id: int) -> list[AttendanceEvent]: # noqa: ARG002 return m.to_attendance() - async def _walk(self, education_id: int, date_from: Date, date_to: Date): + async def _year_for(self, date_to: Date) -> tuple[int, Date | None, Date | None]: + """The sealed school year, asked again when a read runs past its end. + + The year used to be fetched once, at the bootstrap, and never again — + so a session opened in August under the old year, or one the cron has + kept open across 1 September, clipped every walk to a year that had + ended and answered 200 with an empty diary until the family signed out + and back in, with nothing telling anybody to. At most once a day per + session: all summer a fortnight's read runs past 31 May, and the + upstream's answer then is the same old year until the new one opens. + The day it was asked is sealed with the rest, and only after an answer + that could be read, so a failed ask is asked again next read. + """ year_id, year_start, year_end = self._year() + session = self._client.session + stale = year_id is None or (year_end is not None and date_to > year_end) + today = self.today().isoformat() + if stale and session.get("year_checked") != today: + fresh = _usable_year(await self._client.years_current()) + if fresh is not None: + session.update(fresh) + session["year_checked"] = today + year_id, year_start, year_end = self._year() if year_id is None: raise SessionExpired # no year handle sealed → the session is unusable + return year_id, year_start, year_end + + async def _walk(self, education_id: int, date_from: Date, date_to: Date): + year_id, year_start, year_end = await self._year_for(date_to) for week_start, week_end in _weeks(date_from, date_to, year_start, year_end): - yield week_start, week_end, await self._client.diary_week( + diary = await self._client.diary_week( education_id, year_id, _iso(week_start), _iso(week_end) ) + if not isinstance(diary, dict): + # `null`, a list or a string where the week's object belongs. + # The mappers read it with `.get`, and the AttributeError was + # outside the diary's error family: a bare 500 with no reason + # for the phone, where every other odd answer is a 502. + raise UnexpectedResponse + yield week_start, week_end, diary async def schedule( self, education_id: int, date_from: Date, date_to: Date @@ -252,12 +291,22 @@ async def bootstrap(client: NetSchoolClient) -> dict[str, Any]: init = await client.diary_init() if not _students_of(init, None): raise NoStudents - year = await client.years_current() - if isinstance(year, dict): - client.session["year_id"] = year.get("id") - client.session["year_start"] = _year_date(year.get("startDate")) - client.session["year_end"] = _year_date(year.get("endDate")) - ctx = await client.context() + year = _usable_year(await client.years_current()) + if year is None: + # Required, not best effort: every schedule, homework and grades + # read needs the year's id, and a session sealed without one was + # handed out with a 200 and expired by its first read — a 401 the + # phone answered by registering again, into the same loop. + raise UnexpectedResponse + client.session.update(year) + # The school's name and the type map are nice to have: a server that + # answers either with a 4xx (`_authed_json` reads that as + # UnexpectedResponse) still opens the diary, as a shape it does not + # know always did. + try: + ctx = await client.context() + except UnexpectedResponse: + ctx = None if isinstance(ctx, dict): org = ctx.get("organization") name = ctx.get("organizationName") or ( @@ -265,7 +314,10 @@ async def bootstrap(client: NetSchoolClient) -> dict[str, Any]: ) if name: client.session["school"] = str(name)[:300] - types = await client.assignment_types() + try: + types = await client.assignment_types() + except UnexpectedResponse: + types = None if isinstance(types, list): client.session["types"] = { str(t.get("id")): str(t.get("name")) @@ -299,6 +351,24 @@ def _year_date(raw) -> str | None: # noqa: ANN001 return parsed.isoformat() if parsed else None +def _usable_year(year: Any) -> dict[str, Any] | None: + """``years/current`` as the three sealed keys, or ``None`` when the answer + lacks any of them — a JSON integer id and both bounds. + + The bounds are required with the id: a year with no end can never be seen + to have ended, and `NetSchoolConnection._year_for` would go on clipping to + it for as long as the cron keeps the session open. + """ + if not isinstance(year, dict): + return None + year_id = _json_int(year.get("id")) + start = _year_date(year.get("startDate")) + end = _year_date(year.get("endDate")) + if year_id is None or start is None or end is None: + return None + return {"year_id": year_id, "year_start": start, "year_end": end} + + class _DeadConnection: """A connection for an unreadable credential: everything is SessionExpired.""" diff --git a/server/app/security.py b/server/app/security.py index 43462c4b..6fcd88a5 100644 --- a/server/app/security.py +++ b/server/app/security.py @@ -9,6 +9,7 @@ import hashlib import secrets import string +from dataclasses import dataclass from datetime import UTC, datetime, timedelta from sqlalchemy import delete, func, select @@ -79,6 +80,19 @@ def normalise_phone(raw: str) -> str: return digits +@dataclass(frozen=True) +class Admission: + """What :meth:`JoinThrottle.admit` decided. + + ``retry_after`` is ``None`` when the attempt may go ahead, and then + ``attempt_id`` is the row counting it; refused, it is the seconds until the + caller may try again and there is no row. + """ + + attempt_id: int | None + retry_after: float | None + + class JoinThrottle: """Sliding-window limit on attempts per caller, counted in the database. @@ -105,6 +119,17 @@ class JoinThrottle: Every method takes the caller's session and is awaited inside the request, which makes this a couple of indexed queries on a table holding one window's worth of attempts. That is the price of a limit that is real. + + **A door counts through** :meth:`admit`, which writes the attempt first and + counts after, never through :meth:`blocked_for` followed by :meth:`record`. + Check-then-record let every request of a concurrent burst read a count from + before any of them was written: two hundred wrong passwords sent at once + from one address all reached the diary inside one window whose limit is + ten, and the directory's twenty searches were as many as a burst could fit. + Written first, the n-th attempt to commit sees at least n rows, so no more + than ``limit`` of them are let through, however they overlap. A door that + counts only failures hands the row back (:meth:`forgive`) once it knows the + attempt was not one. """ __slots__ = ("limit", "window") @@ -113,6 +138,69 @@ def __init__(self, limit: int, window: float) -> None: self.limit = limit self.window = window + async def admit(self, session: AsyncSession, key: str) -> Admission: + """Count one attempt by [key] and say whether it may go ahead. Commits. + + Let through, the attempt stays counted until :meth:`forgive` takes it + back. Refused, it is taken back at once: a refusal asked nothing of + anybody, and counting it would keep a caller who keeps asking locked out + for as long as they ask rather than for the window. + """ + from app.models import JoinAttempt + + now = _utcnow() + attempt = JoinAttempt(client_key=key, created_at=now) + session.add(attempt) + await session.flush() + attempt_id = attempt.id + await self._prune(session, now) + await session.commit() + + # After the commit, in a statement of its own: under READ COMMITTED it + # sees every attempt committed before it, this one included. + counted = await session.scalar( + select(func.count()) + .select_from(JoinAttempt) + .where( + JoinAttempt.client_key == key, + JoinAttempt.created_at > now - timedelta(seconds=self.window), + ) + ) + if (counted or 0) <= self.limit: + return Admission(attempt_id=attempt_id, retry_after=None) + + await self._drop(session, attempt_id) + # Never 0: the attempts that filled the window may all be in flight and + # about to be forgiven, and a client told to wait no time asks at once. + return Admission( + attempt_id=None, retry_after=max(await self.blocked_for(session, key) or 0.0, 1.0) + ) + + async def forgive(self, session: AsyncSession, admission: Admission) -> None: + """Take back an attempt :meth:`admit` counted, because it turned out not + to be one this door counts — a success, or nothing having judged it. + Commits.""" + if admission.attempt_id is not None: + await self._drop(session, admission.attempt_id) + + async def _drop(self, session: AsyncSession, attempt_id: int) -> None: + from app.models import JoinAttempt + + await session.execute(delete(JoinAttempt).where(JoinAttempt.id == attempt_id)) + await session.commit() + + async def _prune(self, session: AsyncSession, now: datetime) -> None: + from app.models import JoinAttempt + + # Pruned here rather than on a schedule: there is no scheduler in a + # serverless deployment, and the only moment this table is known to be + # growing is the moment something is being added to it. + await session.execute( + delete(JoinAttempt).where( + JoinAttempt.created_at <= now - timedelta(seconds=self.window) + ) + ) + async def blocked_for(self, session: AsyncSession, key: str) -> float | None: """Seconds until [key] may try again, or ``None`` if it may try now.""" from app.models import JoinAttempt @@ -162,15 +250,7 @@ async def record(self, session: AsyncSession, key: str) -> None: now = _utcnow() session.add(JoinAttempt(client_key=key, created_at=now)) - - # Pruned here rather than on a schedule: there is no scheduler in a - # serverless deployment, and the only moment this table is known to be - # growing is the moment something is being added to it. - await session.execute( - delete(JoinAttempt).where( - JoinAttempt.created_at <= now - timedelta(seconds=self.window) - ) - ) + await self._prune(session, now) await session.commit() diff --git a/server/app/services/diary_keepalive.py b/server/app/services/diary_keepalive.py index b31bd541..01d75141 100644 --- a/server/app/services/diary_keepalive.py +++ b/server/app/services/diary_keepalive.py @@ -37,7 +37,7 @@ from dataclasses import dataclass from datetime import UTC, datetime, timedelta -from sqlalchemy import select +from sqlalchemy import func, select from sqlalchemy import update as sa_update from sqlalchemy.ext.asyncio import AsyncSession @@ -50,14 +50,24 @@ log = logging.getLogger(__name__) #: At most this many sessions a tick, so one tick's work is bounded whatever the -#: number of families. The rest are first next tick (ordered oldest-attempt). +#: number of families. The rest are first next tick: the queue is ordered by +#: how long since a row was last known good (see `_claim`). KEEPALIVE_BATCH = 200 #: A floor between two pings of one session, so extra or overlapping ticks are #: free and one address is not hammered. Well under the shortest idle window. KEEPALIVE_MIN_INTERVAL = timedelta(minutes=4) #: Stop starting new pings this many seconds into the tick, so the whole -#: request stays inside the platform's function ceiling. +#: request stays inside the platform's function ceiling (``maxDuration: 30`` +#: in ``vercel.json``). Asked when a ping gets its slot, not when its task is +#: created: `asyncio.gather` creates all two hundred at once, so a check made +#: there passed every one of them at t≈0 and stopped nothing. KEEPALIVE_DEADLINE_SECONDS = 18.0 +#: And give up on whatever is still in flight at this point, filed as "skip". +#: A ping has no total timeout of its own — httpx's are per phase, and the +#: SecurityWarning acknowledgement takes the long read one — so without this +#: a ping started at 17.9 s could run the function past its ceiling, and a +#: function killed there never reaches `_apply`: nothing it learnt is written. +KEEPALIVE_HARD_STOP_SECONDS = 24.0 #: At most this many pings in flight at once. KEEPALIVE_CONCURRENCY = 8 @@ -124,9 +134,20 @@ async def _claim(session: AsyncSession) -> list[_Claim]: (DiarySession.keepalive_attempted_at.is_(None)) | (DiarySession.keepalive_attempted_at < cutoff), ) - .order_by(DiarySession.keepalive_attempted_at.is_(None).desc(), - DiarySession.keepalive_attempted_at, - DiarySession.id) + # Stalest first: the last attempt, or — for a row never pinged — the + # moment the upstream last took it, which for a new row is its + # registration. It used to be never-pinged rows first, whatever their + # age, so more than a batch of fresh registrations a tick (one real + # session replayed into `/session` is enough) meant no family already + # in the queue was pinged again, and each idled out upstream. + .order_by( + func.coalesce( + DiarySession.keepalive_attempted_at, + DiarySession.upstream_ok_at, + DiarySession.created_at, + ), + DiarySession.id, + ) .limit(KEEPALIVE_BATCH) ) # FOR UPDATE SKIP LOCKED on Postgres so two overlapping ticks never take the @@ -162,12 +183,19 @@ async def _ping_all(claims: list[_Claim], *, loop, started: float) -> list[_Resu refused: set[str] = set() async def one(claim: _Claim) -> _Result: - if loop.time() - started > KEEPALIVE_DEADLINE_SECONDS: - return _Result(claim.id, "skip", claim.credential) # out of budget; first next tick async with semaphore: + elapsed = loop.time() - started + if elapsed > KEEPALIVE_DEADLINE_SECONDS: + return _Result(claim.id, "skip", claim.credential) # out of budget; first next tick if claim.region is not None and claim.region in refused: return _Result(claim.id, "skip", claim.credential) - result = await _ping(claim) + try: + result = await asyncio.wait_for( + _ping(claim), KEEPALIVE_HARD_STOP_SECONDS - elapsed + ) + except TimeoutError: + log.info("diary keep-alive ping for session %s ran out of the tick", claim.id) + result = _Result(claim.id, "skip", claim.credential) if result.outcome == "refused" and claim.region is not None: if claim.region not in refused: log.warning( diff --git a/server/app/services/diary_link.py b/server/app/services/diary_link.py index db78a29d..579171b4 100644 --- a/server/app/services/diary_link.py +++ b/server/app/services/diary_link.py @@ -131,6 +131,25 @@ class they have just been taken out of. Committed by the caller. return rows_affected(result) +async def drop_for_class(session: AsyncSession, class_id: int) -> int: + """Drop every outstanding sign-in ticket in this class, whoever holds it. + + Called wherever the class's diary binding is written — bound, rebound or + unbound. A ticket's form names the diary it will send the password to, and + the submit reads the binding again, so a link opened before an admin + rebinds and submitted after it would hand a Petersburg password to + «Сетевой город», or the other way round (#137). With the tickets gone in + the same commit as the binding, the submit finds no ticket and refuses + before anything leaves this server: ``claim`` runs after the binding is + read, so it cannot win against a rebind that committed first. Committed by + the caller. + """ + result = await session.execute( + sa_delete(DiaryLinkCode).where(DiaryLinkCode.class_id == class_id) + ) + return rows_affected(result) + + async def purge(session: AsyncSession) -> int: """Drop tickets nobody can use any more. Returns how many went. diff --git a/server/migrations/versions/0013_one_homework_per_subject_per_day.py b/server/migrations/versions/0013_one_homework_per_subject_per_day.py index 01a69b77..3f35138e 100644 --- a/server/migrations/versions/0013_one_homework_per_subject_per_day.py +++ b/server/migrations/versions/0013_one_homework_per_subject_per_day.py @@ -68,6 +68,17 @@ def _has_table(table: str) -> bool: return sa.inspect(op.get_bind()).has_table(table) +def _has_constraint() -> bool: + # An empty Postgres has it before this revision runs: 0001's `create_all` + # builds today's `homework`, constraint included, and creating it again is + # «relation already exists» — which stopped `docker compose up`'s migrate + # service here, with every later revision unapplied. + if context.is_offline_mode(): + return False + unique = sa.inspect(op.get_bind()).get_unique_constraints("homework") + return any(constraint["name"] == _NAME for constraint in unique) + + def upgrade() -> None: # SQLite has no ALTER for constraints at all, and a database that got here # through `create_all` already carries this one — which is the only way a @@ -81,6 +92,8 @@ def upgrade() -> None: return if not context.is_offline_mode() and not _has_table("homework"): return + if _has_constraint(): + return op.execute(_DEDUPE) op.create_unique_constraint(_NAME, "homework", list(_COLUMNS)) diff --git a/server/migrations/versions/0015_diary_provider_columns.py b/server/migrations/versions/0015_diary_provider_columns.py index 0474a221..19d9ebe5 100644 --- a/server/migrations/versions/0015_diary_provider_columns.py +++ b/server/migrations/versions/0015_diary_provider_columns.py @@ -45,13 +45,23 @@ UPDATE diary_sessions SET expired_at = now() WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL; + UPDATE classes SET diary_provider = NULL + WHERE diary_provider IS NOT NULL AND diary_provider <> 'petersburg'; -``downgrade`` does exactly that before dropping the columns. +The second statement unbinds every class bound to «Сетевой город». Without it +the old code, which knows one diary, reads ``'netschool'`` two ways at once: +the admin's card and the main menu test the column for truth and say +«Санкт-Петербург», while the diary button compares it with ``'petersburg'`` +and answers that the class is not bound. With the region and school gone the +binding means nothing to that code; the admin binds again after the roll +forward. ``downgrade`` does both before dropping the columns. The DDL is taken from the model, as ``CLAUDE.md`` requires: ``CreateTable(...).compile(dialect=postgresql.dialect())`` prints these column -types. Applied through the Neon connector, ``alembic_version`` stamped in the -same transaction; on local SQLite the columns arrive through ``create_all``. +types, and ``tests/test_diary_provider_revision.py`` holds the revision to them. +Applied through the Neon connector, ``alembic_version`` stamped in the same +transaction. On a database at ``0014`` that is exactly the eight +``ADD COLUMN`` statements below, because each guard finds its column missing. """ from __future__ import annotations @@ -67,41 +77,65 @@ depends_on: str | Sequence[str] | None = None -def upgrade() -> None: - # Local SQLite only ever exists here through `create_all`, which builds - # every column the model declares; there is nothing to add. Postgres's - # alone, exactly as the additive revisions before this one. - if op.get_bind().dialect.name == "sqlite": - return - op.add_column("diary_sessions", sa.Column("provider", sa.String(length=32), nullable=True)) - op.add_column("diary_sessions", sa.Column("region", sa.String(length=32), nullable=True)) - op.add_column("diary_sessions", sa.Column("kept_alive_at", sa.DateTime(), nullable=True)) - op.add_column( - "diary_sessions", sa.Column("keepalive_attempted_at", sa.DateTime(), nullable=True) +def _has_column(table: str, column: str) -> bool: + # The guard the additive revisions before this one carry (0005, 0006, + # 0008, 0010), asked per column rather than per dialect. An empty + # database already has every column here, because 0001's `create_all` + # builds today's schema before 0015 runs, and adding one twice is a hard + # error on Postgres. A SQLite file built by `scripts.init_db` before the + # model changed, stamped 0014, has none of them — and skipping SQLite + # wholesale stamped it 0015 anyway, `/warmup` said «ok», and the first + # read of a class raised «no such column: classes.diary_region». + # Offline (`--sql`) there is nobody to ask, and the database the script is + # written for is one at 0014, which has none of them. Asked of the + # migration context rather than `alembic.context`, so the test that renders + # this revision in-process runs this very guard instead of patching it. + if op.get_context().as_sql: + return False + inspector = sa.inspect(op.get_bind()) + if not inspector.has_table(table): + return False + return any(existing["name"] == column for existing in inspector.get_columns(table)) + + +def _columns() -> tuple[tuple[str, sa.Column], ...]: + # Built afresh per call: `add_column` attaches the Column to a table, and + # one Column cannot belong to two. + return ( + ("diary_sessions", sa.Column("provider", sa.String(length=32), nullable=True)), + ("diary_sessions", sa.Column("region", sa.String(length=32), nullable=True)), + ("diary_sessions", sa.Column("kept_alive_at", sa.DateTime(), nullable=True)), + ("diary_sessions", sa.Column("keepalive_attempted_at", sa.DateTime(), nullable=True)), + ("diary_sessions", sa.Column("upstream_ok_at", sa.DateTime(), nullable=True)), + ("classes", sa.Column("diary_region", sa.String(length=32), nullable=True)), + ("classes", sa.Column("diary_school_id", sa.BigInteger(), nullable=True)), + ("classes", sa.Column("diary_school_name", sa.String(length=300), nullable=True)), ) - op.add_column("diary_sessions", sa.Column("upstream_ok_at", sa.DateTime(), nullable=True)) - op.add_column("classes", sa.Column("diary_region", sa.String(length=32), nullable=True)) - op.add_column("classes", sa.Column("diary_school_id", sa.BigInteger(), nullable=True)) - op.add_column("classes", sa.Column("diary_school_name", sa.String(length=300), nullable=True)) + + +def upgrade() -> None: + # Nullable with no default, so SQLite's own ALTER TABLE ADD COLUMN takes + # each of them as it is; no table copy is needed on either dialect. + for table, column in _columns(): + if not _has_column(table, column.name): + op.add_column(table, column) def downgrade() -> None: - if op.get_bind().dialect.name == "sqlite": - return # Expire any non-Petersburg session before the columns that tell it apart # are gone, so the reverted code cannot replay its credential at the wrong # upstream. The rows stay; expired ones are swept within a day. + # CURRENT_TIMESTAMP rather than `now()`, which SQLite does not have; on + # Postgres the two are the same function. Literal SQL rather than a Core + # UPDATE, whose bound parameters `--sql` would print as placeholders. op.execute( - "UPDATE diary_sessions SET expired_at = now() " + "UPDATE diary_sessions SET expired_at = CURRENT_TIMESTAMP " "WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL" ) - for column in ( - "upstream_ok_at", - "keepalive_attempted_at", - "kept_alive_at", - "region", - "provider", - ): - op.drop_column("diary_sessions", column) - for column in ("diary_school_name", "diary_school_id", "diary_region"): - op.drop_column("classes", column) + # And unbind every class the old code cannot read: see the docstring. + op.execute( + "UPDATE classes SET diary_provider = NULL " + "WHERE diary_provider IS NOT NULL AND diary_provider <> 'petersburg'" + ) + for table, column in reversed(_columns()): + op.drop_column(table, column.name) diff --git a/server/tests/test_api_extended.py b/server/tests/test_api_extended.py index d92ff533..aa6f7ae9 100644 --- a/server/tests/test_api_extended.py +++ b/server/tests/test_api_extended.py @@ -8,6 +8,7 @@ from __future__ import annotations +import json from dataclasses import dataclass, field from datetime import date, datetime, time, timedelta from typing import Any @@ -1696,6 +1697,94 @@ async def test_cron_tick_sweeps_dead_and_forgotten_diary_sessions( assert sorted(left) == ["b@e", "e@e"] +def _live_netschool_session() -> DiarySession: + from app.crypto import seal + + credential = {"v": 1, "region": "zabaikalsky", "school_id": 1, "at": "at", + "cookies": {}, "year_id": 2026} + return DiarySession( + token_hash=hash_token("netschool-session"), + upstream_token=seal(json.dumps(credential)), + login="parent@example.com", + provider="netschool", + region="zabaikalsky", + ) + + +async def test_cron_tick_keeps_the_netschool_sessions_alive( + client, session, school_class, monkeypatch, tick_bot +): + """The tick is the keep-alive's only clock. The digest test above has no + «Сетевой город» row, so it reads 0 and False — exactly what a tick that + never called the keep-alive returns; without a ping every such session + idles out upstream within the hour and the family signs in again.""" + _configure_cron(monkeypatch) + row = _live_netschool_session() + session.add(row) + await session.commit() + pinged: list[int] = [] + + async def keep_alive(self): + pinged.append(1) + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", keep_alive + ) + + response = await client.get("/api/v1/cron/tick", headers={"X-Cron-Secret": CRON_SECRET}) + + assert response.status_code == 200 + assert response.json()["diary_sessions_kept_alive"] == 1 + assert response.json()["diary_keepalive_failed"] is False + assert pinged == [1] + await session.refresh(row) + assert row.kept_alive_at is not None + + +async def test_cron_tick_hands_the_keep_alive_the_start_of_the_request( + client, session, school_class, monkeypatch, tick_bot +): + """The keep-alive's deadline counts from the start of the request, so a + morning heavy with digests shortens it rather than pushing the function + past its ceiling. The clock it is handed is the tick's, not its own.""" + import asyncio + + _configure_cron(monkeypatch) + seen: list[float | None] = [] + + async def keep_alive(session, *, started=None): + seen.append(started) + assert started is not None and started <= asyncio.get_running_loop().time() + return 0, 0 + + monkeypatch.setattr(cron.diary_keepalive, "keep_alive", keep_alive) + before = asyncio.get_running_loop().time() + response = await client.get("/api/v1/cron/tick", headers={"X-Cron-Secret": CRON_SECRET}) + + assert response.status_code == 200 + assert len(seen) == 1 and seen[0] >= before + + +async def test_a_keep_alive_that_raises_does_not_fail_the_tick( + client, session, school_class, monkeypatch, tick_bot +): + """A diary fault must not turn the fallback clock red every five minutes, + nor cost the digests and sweeps that ran before it.""" + _configure_cron(monkeypatch) + + async def broken(session, *, started=None): + raise RuntimeError("the keep-alive fell over") + + monkeypatch.setattr(cron.diary_keepalive, "keep_alive", broken) + response = await client.get("/api/v1/cron/tick", headers={"X-Cron-Secret": CRON_SECRET}) + + assert response.status_code == 200 + body = response.json() + assert body["diary_keepalive_failed"] is True + assert body["diary_sessions_kept_alive"] == 0 + assert "fsm_purged" in body + + async def test_cron_tick_sweeps_the_phones_that_stopped_asking( client, session, school_class, monkeypatch, tick_bot ): diff --git a/server/tests/test_bot_manage.py b/server/tests/test_bot_manage.py index 873821e6..d7dbfe84 100644 --- a/server/tests/test_bot_manage.py +++ b/server/tests/test_bot_manage.py @@ -21,6 +21,8 @@ from types import SimpleNamespace from typing import Any +import httpx +import pytest from sqlalchemy import select from app.bot.handlers.manage import ( @@ -137,6 +139,7 @@ DayKind, DayOverride, DeviceToken, + DiaryLinkCode, DiarySession, Homework, JoinMode, @@ -151,7 +154,7 @@ WeekParity, ) from app.security import hash_token, new_token -from app.services import audit +from app.services import audit, diary_link # -------------------------------------------------------------------------- # Stubs @@ -2361,6 +2364,106 @@ async def test_an_editor_cannot_bind_the_diary(session, school_class): assert callback.alerted +async def _rebind_to_netschool(session, school_class) -> None: + await class_diary_school( + FakeCallback(message=FakeEditable()), + SimpleNamespace(value=0), + session, + Role.ADMIN, + FakeState( + data={ + "diary_region": "samara", + "diary_class_id": school_class.id, + "diary_schools": [{"id": 1234, "name": "Школа № 1"}], + } + ), + ) + + +async def _rebind_to_petersburg(session, school_class) -> None: + await class_diary_provider( + FakeCallback(message=FakeEditable()), + SimpleNamespace(value="petersburg"), + session, + school_class, + Role.ADMIN, + ) + + +async def _unbind_then_netschool(session, school_class) -> None: + await class_diary_bind(FakeCallback(message=FakeEditable()), session, school_class, Role.ADMIN) + await _rebind_to_netschool(session, school_class) + + +@pytest.mark.parametrize( + ("before", "rebind", "site"), + [ + ("petersburg", _rebind_to_netschool, "dnevnik2.petersburgedu.ru"), + ("petersburg", _unbind_then_netschool, "dnevnik2.petersburgedu.ru"), + ("netschool", _rebind_to_petersburg, "Самарская область"), + ], + ids=["petersburg-to-netschool", "unbind-then-netschool", "netschool-to-petersburg"], +) +async def test_a_rebind_between_the_form_and_the_submit_sends_the_password_nowhere( + session, school_class, monkeypatch, before, rebind, site +): + """The form named one diary; an admin rebinds the class while the family + types; the submit must not hand that password to the diary bound now — + a Petersburg password's MD5 to a regional server, or a «Сетевой город» + password in plain JSON to dnevnik2 (#137). The rebind drops the class's + tickets in its own commit, so the submit finds none and asks nobody.""" + from app.main import app + + school_class.diary_provider = before + if before == "netschool": + school_class.diary_region = "samara" + school_class.diary_school_id = 1234 + school_class.diary_school_name = "Школа № 1" + await session.commit() + code = await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + + sent: list[dict] = [] + + async def sign_in(session, login, password, **kwargs): + sent.append(kwargs) + raise AssertionError("the password was sent to a diary") + + monkeypatch.setattr("app.api.diary_web.diary_service.sign_in", sign_in) + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as web: + form = await web.get(f"/diary/signin/{code}") + assert form.status_code == 200 + assert site in form.text + + await rebind(session, school_class) + assert school_class.diary_provider != before + + submitted = await web.post( + f"/diary/signin/{code}", data={"login": "parent", "password": "secret"} + ) + + assert submitted.status_code == 410 + assert sent == [] + assert await session.scalar(select(DiaryLinkCode)) is None + + +async def test_unbinding_drops_the_class_links_and_nobody_elses(session, school_class): + other = SchoolClass(name="9Б", school="Школа № 1", join_code="OTHER42") + session.add(other) + school_class.diary_provider = "petersburg" + other.diary_provider = "petersburg" + await session.commit() + await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + await diary_link.mint(session, telegram_id=43, class_id=school_class.id) + kept = await diary_link.mint(session, telegram_id=42, class_id=other.id) + + await class_diary_bind(FakeCallback(message=FakeEditable()), session, school_class, Role.ADMIN) + + left = (await session.scalars(select(DiaryLinkCode))).all() + assert [row.class_id for row in left] == [other.id] + assert await diary_link.claim(session, kept) is not None + + # -------------------------------------------------------------------------- # Binding a class to «Сетевой город»: provider → region → school # -------------------------------------------------------------------------- diff --git a/server/tests/test_diary_keepalive.py b/server/tests/test_diary_keepalive.py index 1d6c6fce..0ca8f117 100644 --- a/server/tests/test_diary_keepalive.py +++ b/server/tests/test_diary_keepalive.py @@ -246,3 +246,225 @@ async def ping(self): assert (await check.get(DiarySession, quiet.id)).upstream_token == quiet_blob stored = (await check.get(DiarySession, rotating.id)).upstream_token assert json.loads(unseal(stored))["at"] == "rotated" + + +# --------------------------------------------------------------------------- +# Through the real client, not a patched `keep_alive` +# --------------------------------------------------------------------------- + + +def _upstream(monkeypatch, answer): + """«Сетевой город»'s shared client over a transport answering every call + with ``answer(request)``.""" + import httpx + + from app.providers.diary import http as diary_http + from app.providers.netschool import client as nsclient + + async def shared(): + return httpx.AsyncClient( + transport=httpx.MockTransport(answer), cookies=diary_http.NoCookieJar() + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + + +async def test_an_outage_page_does_not_sign_the_region_out(session, monkeypatch): + """A regional server mid-deploy answers nginx's 502 page. Read as a login + page, every session the tick claimed on that region was expired at once — + and none can be signed back in without its family, because no password is + kept. Every keep-alive test before this one patched `keep_alive` itself, + so the client's own reading of the answer was never asked.""" + import httpx + + rows = [_netschool_row() for _ in range(5)] + session.add_all(rows) + await session.commit() + _upstream(monkeypatch, lambda request: httpx.Response( + 502, text="

502 Bad Gateway

nginx", + headers={"content-type": "text/html"}, + )) + + assert await diary_keepalive.keep_alive(session) == (0, 0) + for row in rows: + await session.refresh(row) + assert row.expired_at is None + + +async def test_a_login_page_still_expires_the_session(session, monkeypatch): + import httpx + + row = _netschool_row() + session.add(row) + await session.commit() + _upstream(monkeypatch, lambda request: httpx.Response( + 200, text="
", headers={"content-type": "text/html"} + )) + + assert await diary_keepalive.keep_alive(session) == (0, 1) + + +# --------------------------------------------------------------------------- +# The tick's budget, and the queue +# --------------------------------------------------------------------------- + + +def _claims(count: int) -> list: + return [ + diary_keepalive._Claim(id=i, provider="netschool", region="zabaikalsky", credential="x") + for i in range(count) + ] + + +async def test_the_deadline_stops_the_pings_still_waiting_for_a_slot(monkeypatch): + """`gather` starts every claim's task at once, so the deadline — checked + before the semaphore — was passed by all of them at t≈0: forty claims, a + deadline at 1.5 s and one-second pings pinged all forty in five seconds. + Checked when the slot comes, the third wave of eight never starts.""" + import asyncio + + async def slow(claim): + await asyncio.sleep(0.2) + return diary_keepalive._Result(claim.id, "ok", claim.credential) + + monkeypatch.setattr(diary_keepalive, "_ping", slow) + monkeypatch.setattr(diary_keepalive, "KEEPALIVE_DEADLINE_SECONDS", 0.3) + loop = asyncio.get_running_loop() + + results = await diary_keepalive._ping_all(_claims(40), loop=loop, started=loop.time()) + + pinged = [r for r in results if r.outcome == "ok"] + skipped = [r for r in results if r.outcome == "skip"] + assert diary_keepalive.KEEPALIVE_CONCURRENCY <= len(pinged) <= 16 + assert len(pinged) + len(skipped) == 40 + + +async def test_a_ping_still_in_flight_at_the_hard_stop_is_given_up(monkeypatch): + """A hung origin, or a SecurityWarning round trip on the long read timeout, + held the tick until the platform killed it — before `_apply`, so nothing + the tick learnt was written. It is now abandoned as a skip.""" + import asyncio + + async def hung(claim): + await asyncio.sleep(30) + return diary_keepalive._Result(claim.id, "ok", claim.credential) + + monkeypatch.setattr(diary_keepalive, "_ping", hung) + monkeypatch.setattr(diary_keepalive, "KEEPALIVE_HARD_STOP_SECONDS", 0.3) + loop = asyncio.get_running_loop() + began = loop.time() + + results = await diary_keepalive._ping_all(_claims(8), loop=loop, started=began) + + assert loop.time() - began < 5 + assert [r.outcome for r in results] == ["skip"] * 8 + + +async def test_fresh_registrations_do_not_starve_a_family_already_in_the_queue( + session, monkeypatch +): + """Never-pinged rows used to go first whatever their age, so more than a + batch of new ones a tick — one real session replayed into `/session` over + and over is enough — meant a family's row, due for its ping, never got + one. The queue is now the stalest first, and a fresh row was just seen + working by the registration itself.""" + from datetime import datetime, timedelta + + monkeypatch.setattr(diary_keepalive, "KEEPALIVE_BATCH", 5) + now = datetime.utcnow() + family = _netschool_row( + keepalive_attempted_at=now - timedelta(minutes=10), upstream_ok_at=now - timedelta(hours=1) + ) + session.add(family) + await session.commit() + session.add_all([_netschool_row(upstream_ok_at=now) for _ in range(5)]) + await session.commit() + + claimed = await diary_keepalive._claim(session) + + assert family.id in {claim.id for claim in claimed} + + +async def test_a_second_tick_within_the_floor_pings_nothing(session, monkeypatch): + """An extra or overlapping tick is free: a row attempted less than + `KEEPALIVE_MIN_INTERVAL` ago is not taken again. Without the floor every + tick — the external cron and `reminders.yml` both — pings every session, + and a caller who can fire the tick can make us hammer a regional server.""" + from datetime import datetime, timedelta + + pinged: list[int] = [] + + async def fake_keep_alive(self): + pinged.append(1) + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", fake_keep_alive + ) + row = _netschool_row() + stale = _netschool_row( + keepalive_attempted_at=datetime.utcnow() + - diary_keepalive.KEEPALIVE_MIN_INTERVAL + - timedelta(minutes=1) + ) + session.add_all([row, stale]) + await session.commit() + + assert await diary_keepalive.keep_alive(session) == (2, 0) + assert await diary_keepalive.keep_alive(session) == (0, 0) + assert pinged == [1, 1] + + +async def test_a_tick_that_arrives_out_of_budget_pings_nothing(session, monkeypatch): + """The deadline counts from the start of the request the tick handed in, + so a morning whose digests used the budget up leaves the keep-alive for + the next tick rather than running the function past its ceiling.""" + import asyncio + + pinged: list[int] = [] + + async def fake_keep_alive(self): + pinged.append(1) + + monkeypatch.setattr( + "app.providers.netschool.provider.NetSchoolConnection.keep_alive", fake_keep_alive + ) + row = _netschool_row() + session.add(row) + await session.commit() + + late = asyncio.get_running_loop().time() - diary_keepalive.KEEPALIVE_DEADLINE_SECONDS - 1 + assert await diary_keepalive.keep_alive(session, started=late) == (0, 0) + assert pinged == [] + await session.refresh(row) + assert row.kept_alive_at is None + + +async def test_on_postgres_two_overlapping_ticks_never_take_the_same_rows(): + """`FOR UPDATE SKIP LOCKED` is the only thing keeping two ticks — the + external cron and `reminders.yml` — off each other's rows, and it is + asked for on Postgres alone, which CI does not run. So the claim is built + against a session that says it is Postgres and the statement read back.""" + from types import SimpleNamespace + + from sqlalchemy.dialects import postgresql + + class Captured: + bind = SimpleNamespace(dialect=postgresql.dialect()) + + def __init__(self) -> None: + self.statements: list = [] + + async def scalars(self, statement): + self.statements.append(statement) + return [] + + async def commit(self) -> None: + pass + + captured = Captured() + assert await diary_keepalive._claim(captured) == [] + + (statement,) = captured.statements + sql = " ".join(str(statement.compile(dialect=postgresql.dialect())).split()) + assert sql.endswith("FOR UPDATE SKIP LOCKED") + assert "diary_sessions.keepalive_attempted_at <" in sql diff --git a/server/tests/test_diary_protocol_vectors.py b/server/tests/test_diary_protocol_vectors.py index 0743eeb9..fa00adb9 100644 --- a/server/tests/test_diary_protocol_vectors.py +++ b/server/tests/test_diary_protocol_vectors.py @@ -202,6 +202,22 @@ async def test_netschool_getdata_answers_match_the_vectors(monkeypatch, case): assert list(form) == NETSCHOOL["login_form_fields"] for field, value in case["form"].items(): assert form[field] == value + # And the fields that carry the credential, which the case's `form` leaves + # out: a form posting another school, another login, or `pw2` in both + # hash fields passed every case here while every «Сетевой город» password + # sign-in would have been refused. The hash is the vectors' own answer for + # this salt and this password, not a second call to the function under test. + (hashed,) = [ + row + for row in NETSCHOOL["hash"] + if row["salt"] == str(case["body"]["salt"]) and row["password"] == FLOW["password"] + ] + assert form["un"] == FLOW["login"] + assert form["scid"] == str(FLOW["school_id"]) + assert (form["pw"], form["pw2"]) == (hashed["pw"], hashed["pw2"]) + # «1» is the sign-in by login and password; «2» and the rest are other + # doors (Госуслуги among them) that this form must never ask for. + assert form["loginType"] == "1" @pytest.mark.parametrize( @@ -391,6 +407,10 @@ async def test_petersburg_login_answers_match_the_vectors(monkeypatch, case): assert set(sent) == {*PETERSBURG["login_fields"], "login", "password"} for field, value in PETERSBURG["login_fields"].items(): assert sent[field] == value + # What was typed, as it was typed: an upper-cased or trimmed login is a + # refused sign-in for every lower-case e-mail, and nothing else here says so. + assert sent["login"] == "parent@example.com" + assert sent["password"] == "secret" expect = case["expect"] if "failure" in expect: diff --git a/server/tests/test_diary_provider_revision.py b/server/tests/test_diary_provider_revision.py new file mode 100644 index 00000000..d3703b60 --- /dev/null +++ b/server/tests/test_diary_provider_revision.py @@ -0,0 +1,278 @@ +"""``0015``, the revision that gives a second diary its columns. + +Three things are pinned here, each of which was once wrong: + +- on Postgres it builds exactly the columns the model declares — the rule + ``CLAUDE.md`` sets for every revision, held by a test rather than by whoever + applies it through the Neon connector (``test_quota.py`` does the same for + ``0016``); +- it asks per column whether there is anything to add, rather than skipping + SQLite wholesale. The wholesale skip stamped a ``lessons.db`` built before + the model changed as ``0015`` with none of the columns, ``/warmup`` said + «ok», and the first read of a class raised «no such column»; and on an empty + Postgres, where ``0001``'s ``create_all`` has already built them, adding a + column twice is a hard error; +- going down it unbinds the classes the old code cannot read, as well as + expiring the sessions it would replay at the wrong upstream. + +Nothing here connects to Postgres. The Postgres half renders the revision +offline, the way ``alembic upgrade --sql`` would, in this process. +""" + +from __future__ import annotations + +import importlib.util +import io +import os +import sqlite3 +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy.dialects import postgresql + +from app.models import DiarySession, SchoolClass + +SERVER_ROOT = Path(__file__).resolve().parent.parent +VERSIONS = SERVER_ROOT / "migrations" / "versions" + +#: What 0015 adds, in its order. Named here once so a column the revision +#: loses, or gains without the model, fails the comparison below. +ADDED = { + "diary_sessions": ( + "provider", + "region", + "kept_alive_at", + "keepalive_attempted_at", + "upstream_ok_at", + ), + "classes": ("diary_region", "diary_school_id", "diary_school_name"), +} +MODEL_TABLES = {"diary_sessions": DiarySession.__table__, "classes": SchoolClass.__table__} + + +def _load(filename: str, name: str): + spec = importlib.util.spec_from_file_location(name, VERSIONS / filename) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _revision(): + return _load("0015_diary_provider_columns.py", "revision_0015") + + +def _render(function) -> list[str]: + rendered = io.StringIO() + context = MigrationContext.configure( + dialect_name="postgresql", opts={"as_sql": True, "output_buffer": rendered} + ) + with Operations.context(context): + function() + return [" ".join(part.split()) for part in rendered.getvalue().split(";") if part.strip()] + + +def test_the_revision_builds_on_postgres_exactly_what_the_model_declares(): + """Each ``ADD COLUMN`` is the model's column compiled for Postgres, and + each is the additive shape: nullable, no default, no index, no key — the + shape that lets it go on before the merge. The revision's own guard runs + here unpatched: offline it has nobody to ask and adds all eight, which is + what a database at ``0014`` needs.""" + revision = _revision() + assert (revision.revision, revision.down_revision) == ("0015", "0014") + dialect = postgresql.dialect() + + expected = [] + for table_name, columns in ADDED.items(): + table = MODEL_TABLES[table_name] + for name in columns: + column = table.c[name] + assert column.nullable, name + assert column.server_default is None, name + assert not column.foreign_keys, name + assert not any(name in index.columns for index in table.indexes), name + expected.append( + f"ALTER TABLE {table_name} ADD COLUMN {name} {column.type.compile(dialect=dialect)}" + ) + + assert _render(revision.upgrade) == expected + + +def test_the_way_down_unbinds_what_the_old_code_cannot_read_then_drops_the_columns(): + """The two updates come before the drops, because after them nothing says + which session or class was «Сетевой город»'s.""" + statements = _render(_revision().downgrade) + + assert statements[:2] == [ + "UPDATE diary_sessions SET expired_at = CURRENT_TIMESTAMP " + "WHERE provider IS NOT NULL AND provider <> 'petersburg' AND expired_at IS NULL", + "UPDATE classes SET diary_provider = NULL " + "WHERE diary_provider IS NOT NULL AND diary_provider <> 'petersburg'", + ] + dropped = [ + f"ALTER TABLE {table} DROP COLUMN {name}" + for table, columns in ADDED.items() + for name in columns + ] + assert sorted(statements[2:]) == sorted(dropped) + + +# ---- run for real, on SQLite --------------------------------------------------- + + +def _alembic(database: Path, *args: str) -> subprocess.CompletedProcess: + env = dict(os.environ, DATABASE_URL=f"sqlite+aiosqlite:///{database}") + return subprocess.run( + [sys.executable, "-m", "alembic", *args], + env=env, + cwd=str(SERVER_ROOT), + capture_output=True, + text=True, + ) + + +def _columns(db: sqlite3.Connection, table: str) -> set[str]: + return {row[1] for row in db.execute(f"PRAGMA table_info({table})")} + + +def _at_0014(database: Path) -> None: + """A file shaped the way ``scripts.init_db`` left it before this batch. + + ``0001`` builds today's whole schema, so a chain from nothing never makes a + ``0014`` database; taking this revision's columns and ``0016``'s table + back out and putting the stamp back does. + """ + database.touch() + built = _alembic(database, "upgrade", "head") + assert built.returncode == 0, built.stderr + with sqlite3.connect(database) as db: + for table, columns in ADDED.items(): + for name in columns: + db.execute(f"ALTER TABLE {table} DROP COLUMN {name}") + db.execute("DROP TABLE usage_counters") + db.execute("UPDATE alembic_version SET version_num = '0014'") + + +def test_a_file_built_before_the_model_changed_gets_every_column(tmp_path): + """The wholesale SQLite skip left this file stamped ``0016`` with none of + the eight: «no such column: classes.diary_region» on the first read of a + class, which for the bot is every update.""" + database = tmp_path / "at14.db" + _at_0014(database) + + upgraded = _alembic(database, "upgrade", "head") + assert upgraded.returncode == 0, upgraded.stderr + with sqlite3.connect(database) as db: + for table, columns in ADDED.items(): + assert set(columns) <= _columns(db, table), table + assert db.execute("select version_num from alembic_version").fetchall() == [("0016",)] + + # What the app itself reads: every mapped column of both tables. + engine = sa.create_engine(f"sqlite:///{database}") + try: + with engine.connect() as connection: + connection.execute(sa.select(SchoolClass.__table__)).all() + connection.execute(sa.select(DiarySession.__table__)).all() + finally: + engine.dispose() + + +def test_the_way_down_on_sqlite_expires_and_unbinds_then_the_way_up_again(tmp_path): + database = tmp_path / "down.db" + _at_0014(database) + assert _alembic(database, "upgrade", "head").returncode == 0 + + with sqlite3.connect(database) as db: + for class_id, provider in ((1, "petersburg"), (2, "netschool")): + db.execute( + "INSERT INTO classes (id, name, join_code, join_mode, created_at, " + "diary_provider) VALUES (?, ?, ?, 'OPEN', '2026-09-01 00:00:00', ?)", + (class_id, f"9{class_id}", f"CODE000{class_id}", provider), + ) + for session_id, provider in ((1, None), (2, "petersburg"), (3, "netschool")): + db.execute( + "INSERT INTO diary_sessions (id, token_hash, upstream_token, login, " + "created_at, provider) VALUES (?, ?, 'sealed', 'parent', " + "'2026-09-01 00:00:00', ?)", + (session_id, f"hash{session_id}", provider), + ) + + down = _alembic(database, "downgrade", "0014") + assert down.returncode == 0, down.stderr + with sqlite3.connect(database) as db: + for table, columns in ADDED.items(): + assert not set(columns) & _columns(db, table), table + assert db.execute("SELECT id, diary_provider FROM classes ORDER BY id").fetchall() == [ + (1, "petersburg"), + (2, None), + ] + expired = db.execute( + "SELECT id FROM diary_sessions WHERE expired_at IS NOT NULL ORDER BY id" + ).fetchall() + assert expired == [(3,)] + + again = _alembic(database, "upgrade", "head") + assert again.returncode == 0, again.stderr + + +def _pretending_to_be_postgres(database: Path, filename: str, name: str) -> None: + """Run one revision's ``upgrade`` against a schema ``create_all`` built, + with the connection's dialect answering «postgresql». + + That is the empty-Postgres path of ``docker compose up``: ``0001``'s + ``create_all`` has already built today's schema when the later revisions + run. CI has no Postgres, and the guards ask the inspector rather than the + dialect's name, so a SQLite file that says it is Postgres reaches exactly + the branch Postgres would — and a statement the guard should have held back + reaches SQLite, which refuses it as Postgres would. + """ + revision = _load(filename, name) + engine = sa.create_engine(f"sqlite:///{database}") + try: + with engine.begin() as connection: + connection.dialect.name = "postgresql" + context = MigrationContext.configure(connection) + with Operations.context(context): + if hasattr(revision, "context"): + # alembic.context is a proxy only a running `env.py` fills. + revision.context = SimpleNamespace(is_offline_mode=lambda: False) + revision.upgrade() + finally: + engine.dispose() + + +def test_on_a_schema_create_all_already_built_the_revision_adds_nothing(tmp_path): + """Before the per-column guard this was ``duplicate column name: provider`` + — on Postgres «column "provider" of relation "diary_sessions" already + exists», and the migrate service never finished.""" + database = tmp_path / "empty.db" + database.touch() + assert _alembic(database, "upgrade", "head").returncode == 0 + + _pretending_to_be_postgres(database, "0015_diary_provider_columns.py", "revision_0015_pg") + + with sqlite3.connect(database) as db: + for table, columns in ADDED.items(): + assert set(columns) <= _columns(db, table) + + +def test_0013_on_a_schema_create_all_already_built_adds_no_second_constraint(tmp_path): + """The chain's other stop on an empty Postgres, one revision earlier: + ``create_all`` already made ``uq_homework_per_subject_per_day``, and making + it again is «relation already exists». Fixing 0015 alone only moved the + failure here.""" + database = tmp_path / "empty13.db" + database.touch() + assert _alembic(database, "upgrade", "head").returncode == 0 + + _pretending_to_be_postgres( + database, "0013_one_homework_per_subject_per_day.py", "revision_0013_pg" + ) + + with sqlite3.connect(database) as db: + schema = db.execute("SELECT sql FROM sqlite_master WHERE name = 'homework'").fetchone()[0] + assert schema.count("uq_homework_per_subject_per_day") == 1 diff --git a/server/tests/test_diary_session.py b/server/tests/test_diary_session.py index 79516110..eb2f213b 100644 --- a/server/tests/test_diary_session.py +++ b/server/tests/test_diary_session.py @@ -98,6 +98,8 @@ def handler(self, request: httpx.Request) -> httpx.Response: route = self.routes.get(request.url.path) if isinstance(route, httpx.Response): return route + if callable(route): + return route(request) if route is None: return httpx.Response(404, json={}) return httpx.Response(200, json=route) @@ -528,9 +530,13 @@ async def test_the_login_finds_the_corrections_a_password_sign_in_left( async def test_a_registered_session_is_invisible_to_the_bot(client, session, petersburg): """Showing a phone's session in the bot is deliberately left for later: the row belongs to no Telegram account and no class, so no bot screen finds - it — even with a device token of a class bound to the same diary sent.""" - from app.bot.handlers import diary as bot_diary + it — even with a device token of a class bound to the same diary sent. + Sent the way the app sends it, as `Authorization: Bearer`. This test sent + it as `X-Device-Token`, which nothing reads, so a registration that began + tying itself to the caller's class would have passed; and it asked the bot + for Telegram id 42, which a row with no Telegram id can never match + whatever its class is.""" klass = SchoolClass(name="9А", join_code="PHONE42", diary_provider="petersburg") session.add(klass) await session.commit() @@ -538,13 +544,18 @@ async def test_a_registered_session_is_invisible_to_the_bot(client, session, pet device = joined.json()["token"] response = await client.post( - "/api/v1/diary/session", json=_petersburg_body(), headers={"X-Device-Token": device} + "/api/v1/diary/session", + json=_petersburg_body(), + headers={"Authorization": f"Bearer {device}"}, ) assert response.status_code == 200, response.text row = await session.scalar(select(DiarySession)) assert row.telegram_id is None and row.class_id is None - assert await bot_diary._session_for(session, 42, klass) is None + in_the_class = await session.scalar( + select(DiarySession).where(DiarySession.class_id == klass.id) + ) + assert in_the_class is None async def test_a_device_token_never_authorises_a_diary_read(client, session, school_class): @@ -675,3 +686,248 @@ def now(cls, tz=None): # Every region the allow-list serves has a zone this Python knows. for region in regions.listed(password_only=False): assert service.zone_for("netschool", region.key) == region.zone + + +# -------------------------------------------------------------------------- +# «Сетевой город» answering the way a real server fails +# -------------------------------------------------------------------------- + +#: nginx's own page for a regional server in the middle of a deploy. +NGINX_502 = "502 Bad Gateway

502 Bad Gateway


nginx
" # noqa: E501 + + +def _outage(status: int = 502, text: str = NGINX_502, ctype: str = "text/html"): + return lambda request: httpx.Response(status, text=text, headers={"content-type": ctype}) + + +async def _ns_token(client) -> dict[str, str]: + registered = await _register(client, _netschool_body()) + assert registered.status_code == 200, registered.text + return {"Authorization": f"Bearer {registered.json()['token']}"} + + +@pytest.mark.parametrize( + ("status", "text", "ctype"), + [ + (502, NGINX_502, "text/html"), + (503, "

Service Unavailable

", "text/html; charset=us-ascii"), + (500, "Runtime Error", "text/plain"), + (429, "

Too Many Requests

", "text/html"), + ], + ids=["502-nginx", "503-iis", "500-plain", "429-html"], +) +async def test_an_outage_page_on_a_read_is_503_and_keeps_the_session( + client, session, netschool, status, text, ctype +): + """An error page is the region being down, not the session being over. + + Read as a login page — the rule for a non-JSON *2xx* — it expired the row + and sent the phone to sign in again, and no password is stored to do that + for the family: one outage signed a whole region out. + """ + headers = await _ns_token(client) + netschool.routes["/webapi/student/diary/init"] = _outage(status, text, ctype) + + response = await client.get("/api/v1/diary/students", headers=headers) + + assert response.status_code == 503, response.text + assert response.headers["X-Diary-Unavailable"] == "upstream" + assert "X-Diary-Reauth" not in response.headers + row = await session.scalar(select(DiarySession)) + await session.refresh(row) + assert row.expired_at is None + + +async def test_a_login_page_on_a_read_still_expires_the_session(client, session, netschool): + """The other half of the rule above, which must survive it: a 200 of HTML + on an authenticated call is the session gone.""" + headers = await _ns_token(client) + netschool.routes["/webapi/student/diary/init"] = _outage(200, "Вход
") + + response = await client.get("/api/v1/diary/students", headers=headers) + + assert response.status_code == 401 + assert response.headers["X-Diary-Reauth"] == "required" + + +async def test_an_outage_page_during_registration_is_503_and_not_counted( + client, session, netschool +): + netschool.routes["/webapi/student/diary/init"] = _outage() + + response = await _register(client, _netschool_body()) + + assert response.status_code == 503, response.text + assert response.headers["X-Diary-Unavailable"] == "upstream" + assert await _attempts(session) == 0 + assert await session.scalar(select(DiarySession)) is None + + +async def test_a_body_that_will_not_decode_is_503_and_not_counted(client, session, netschool): + """``Content-Encoding: gzip`` over a body that is not: httpx raises a + DecodingError, which is not a TransportError, and it left the client as a + bare 500 — uncounted, unexplained, and with no header to switch on.""" + netschool.routes["/webapi/student/diary/init"] = lambda request: httpx.Response( + 200, + headers={"content-type": "application/json", "content-encoding": "gzip"}, + stream=httpx.ByteStream(b"this is not gzip"), + ) + + response = await _register(client, _netschool_body()) + + assert response.status_code == 503, response.text + assert response.headers["X-Diary-Unavailable"] == "upstream" + assert await _attempts(session) == 0 + + +@pytest.mark.parametrize( + "answer", + [ + httpx.Response(404, json={"message": "not found"}), + httpx.Response(200, json={}), + httpx.Response(200, json={"id": None, "startDate": "2026-09-01", "endDate": "2027-05-31"}), + httpx.Response(200, json=[]), + httpx.Response(200, json={"id": 2026}), + ], + ids=["404", "empty", "null-id", "list", "no-bounds"], +) +async def test_a_registration_whose_year_cannot_be_read_is_refused( + client, session, netschool, answer +): + """Before, it answered 200 with a token, and the first schedule read found + no year sealed and expired it: 401, register again, 200, 401 — for ever.""" + netschool.routes["/webapi/years/current"] = answer + + response = await _register(client, _netschool_body()) + + assert response.status_code == 502, response.text + assert await session.scalar(select(DiarySession)) is None + assert await _attempts(session) == 1 + + +@pytest.mark.parametrize("answer", [None, [], "week", 42], ids=["null", "list", "str", "int"]) +async def test_a_weekly_diary_that_is_not_an_object_is_502(client, netschool, answer): + headers = await _ns_token(client) + netschool.routes["/webapi/student/diary"] = lambda request: httpx.Response( + 200, content=json.dumps(answer).encode(), headers={"content-type": "application/json"} + ) + + for kind in ("schedule", "homework", "grades"): + response = await client.get( + f"/api/v1/diary/students/11/{kind}?from=2026-09-14&to=2026-09-20", headers=headers + ) + assert response.status_code == 502, (kind, response.text) + assert response.json()["detail"] == "Электронный дневник ответил непонятно" + + +async def test_a_session_opened_under_the_old_year_reads_the_new_one( + client, session, netschool +): + """Registered while ``years/current`` still named the year that ended in + May, then read in September. The walk was clipped to the sealed year and + answered 200 with nothing, making no call at all, until the family signed + out and back in. Now the year is asked again — once that day.""" + netschool.routes["/webapi/years/current"] = { + "id": 2025, "startDate": "2025-09-01", "endDate": "2026-05-31"} + headers = await _ns_token(client) + netschool.routes["/webapi/years/current"] = { + "id": 2026, "startDate": "2026-09-01", "endDate": "2027-05-31"} + netschool.routes["/webapi/student/diary"] = {"weekDays": [{ + "date": "2026-09-15T00:00:00", + "lessons": [{"number": 1, "subjectName": "Алгебра", "startTime": "08:30", + "endTime": "09:15", "room": "12"}], + }]} + netschool.seen.clear() + + schedule = "/api/v1/diary/students/11/schedule?from=2026-09-14&to=2026-09-20" + first = await client.get(schedule, headers=headers) + second = await client.get(schedule, headers=headers) + + for response in (first, second): + assert response.status_code == 200, response.text + assert [lesson["subject"] for lesson in response.json()] == ["Алгебра"] + weeks = [r for r in netschool.seen if r.url.path == "/webapi/student/diary"] + assert weeks and all(r.url.params["yearId"] == "2026" for r in weeks) + # Once, not on every read: the new year is sealed with the session. + assert [r.url.path for r in netschool.seen].count("/webapi/years/current") == 1 + row = await session.scalar(select(DiarySession)) + await session.refresh(row) + assert json.loads(service.upstream_of(row))["year_id"] == 2026 + + +# -------------------------------------------------------------------------- +# What one caller may do to the upstream, all at once or one at a time +# -------------------------------------------------------------------------- + + +@pytest.fixture +async def own_pool(): + """A connection pool of this test's own. A burst waits on the pool, which + binds the pool's queue to this test's event loop — and the next test runs + on another loop and cannot wait on it. Disposed before and after.""" + from app.db import engine + + await engine.dispose() + yield + await engine.dispose() + + +async def test_a_burst_of_wrong_passwords_reaches_the_diary_at_most_ten_times( + client, petersburg, LOGIN_PATH, own_pool +): + """Checked first and recorded only after the upstream had answered, a + burst of forty concurrent guesses all read a count from before any of them + and twenty-odd reached the diary, from our address, inside a window whose + limit is ten — the oracle the limiter exists to close.""" + import asyncio + + async def slow_refusal(request: httpx.Request) -> httpx.Response: + await asyncio.sleep(0.2) + return httpx.Response(401, json={"message": "Неверный логин или пароль"}) + + petersburg.routes[LOGIN_PATH] = slow_refusal + responses = await asyncio.gather(*( + client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": f"guess{i}"} + ) + for i in range(40) + )) + + guesses = [r for r in petersburg.seen if r.url.path == LOGIN_PATH] + assert len(guesses) <= diary_login_limiter.limit + assert {r.status_code for r in responses} <= {401, 429} + + +async def test_one_caller_cannot_open_sessions_without_end(client, session, netschool): + """Only failures were counted, so a caller whose every registration + succeeded was never limited: one real session replayed into `/session` + was a new row per call — four bootstrap calls each, kept alive by the cron + from our address for a month.""" + from app.api.diary import diary_open_limiter + + for _ in range(diary_open_limiter.limit): + assert (await _register(client, _netschool_body())).status_code == 200 + + refused = await _register(client, _netschool_body()) + + assert refused.status_code == 429 + assert "Retry-After" in refused.headers + rows = list(await session.scalars(select(DiarySession))) + assert len(rows) == diary_open_limiter.limit + + +async def test_a_failure_does_not_spend_a_session_and_a_session_does_not_spend_a_failure( + client, session, netschool +): + """The two counts are apart: a session opened is not a wrong guess, and a + wrong guess opened nothing.""" + from app.api.diary import diary_open_limiter + + ok = await _register(client, _netschool_body()) + netschool.routes["/webapi/student/diary/init"] = httpx.Response(401, json={}) + refused = await _register(client, _netschool_body()) + + assert (ok.status_code, refused.status_code) == (200, 409) + # One row for each: the session opened, the failure counted. + assert await _attempts(session) == 2 + assert diary_open_limiter.limit > 1 diff --git a/server/tests/test_diary_web.py b/server/tests/test_diary_web.py index 33dd4d47..7f4222e6 100644 --- a/server/tests/test_diary_web.py +++ b/server/tests/test_diary_web.py @@ -227,6 +227,46 @@ async def test_an_unknown_ticket_is_gone_rather_than_a_form(web): assert "type=password" not in response.text +# ---- a class whose binding is not the one the link was minted under (#137) -- + + +@pytest.fixture +def password_sent(monkeypatch) -> list[dict]: + """Every sign-in the page attempts. A refusal here must leave it empty: + the point of refusing is that the password never leaves this server.""" + calls: list[dict] = [] + + async def spy(session, login, password, **kwargs): + calls.append({"login": login, **kwargs}) + raise AssertionError("the password was sent to a diary") + + monkeypatch.setattr(from_app.diary_service, "sign_in", spy) + return calls + + +async def test_a_link_into_a_class_with_no_diary_opens_no_form_and_sends_nothing( + web, session, school_class, password_sent +): + """Refused at the GET and at the POST, without spending the ticket: the + family did nothing wrong, and a class bound again can use the same link.""" + assert school_class.diary_provider is None + code = await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + + shown = await web.get(f"/diary/signin/{code}") + assert shown.status_code == 410 + assert "type=password" not in shown.text + + sent = await web.post( + f"/diary/signin/{code}", data={"login": "parent@example.com", "password": "secret"} + ) + assert sent.status_code == 410 + assert "не привязан" in sent.text + assert password_sent == [] + row = await session.scalar(select(DiaryLinkCode)) + await session.refresh(row) + assert row.used_at is None + + async def test_a_second_link_retires_the_first(session, school_class): """Two live links is two chances for the older one — further up the chat, likelier to be scrolled past by somebody else — to still work.""" @@ -441,3 +481,77 @@ async def test_a_refused_sign_in_never_draws_the_form_again(web, upstream, ticke # Not a style left behind by the branch that went either, which is how a # renderer keeps a shape nothing builds. assert "class=bad" not in response.text + + +async def _netschool_ticket(session, school_class, monkeypatch, routes: dict) -> str: + """A ticket for a class bound to «Сетевой город» in samara, with the + regional server answering ``routes`` (path → JSON) and 404 elsewhere.""" + from app.providers.diary import http as diary_http + from app.providers.netschool import client as nsclient + + def handler(request: httpx.Request) -> httpx.Response: + body = routes.get(request.url.path) + if body is None: + return httpx.Response(404, json={}) + return httpx.Response(200, json=body) + + async def shared(): + return httpx.AsyncClient( + transport=httpx.MockTransport(handler), cookies=diary_http.NoCookieJar() + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + school_class.diary_provider = "netschool" + school_class.diary_region = "samara" + school_class.diary_school_id = 1234 + school_class.diary_school_name = "Школа № 1" + await session.commit() + return await diary_link.mint(session, telegram_id=42, class_id=school_class.id) + + +async def test_an_account_with_no_pupil_is_told_so_rather_than_sent_to_the_site( + web, session, school_class, monkeypatch +): + """The password was right and the account lists no pupil. `NoStudents` fell + through to «ответил непонятно … откройте asurso.ru, попросите новую + ссылку» — a diary that is up, and a link that fails the same way.""" + code = await _netschool_ticket(session, school_class, monkeypatch, { + "/webapi/logindata": {"schoolLogin": True, "cacheVer": "1"}, + "/webapi/auth/getdata": {"lt": "1", "ver": "2", "salt": "3"}, + "/webapi/login": {"at": "at-staff"}, + "/webapi/student/diary/init": {"students": []}, + }) + + response = await web.post( + f"/diary/signin/{code}", data={"login": "teacher", "password": "correct"} + ) + + assert response.status_code == 403 + assert "В этой учётной записи нет ученика" in response.text + assert "ответил непонятно" not in response.text + assert "родителя или ученика" in response.text + row = await session.scalar(select(DiaryLinkCode)) + await session.refresh(row) + assert row.used_at is not None, "the password was judged" + + +async def test_a_region_that_takes_only_gosuslugi_does_not_say_try_again( + web, session, school_class, monkeypatch +): + """The page said «логин и пароль тут не подойдут» over «откройте её снова и + попробуйте ещё раз», because the note was picked by the ticket alone.""" + code = await _netschool_ticket(session, school_class, monkeypatch, { + "/webapi/logindata": {"schoolLogin": False}, + }) + + response = await web.post( + f"/diary/signin/{code}", data={"login": "parent", "password": "correct"} + ) + + assert response.status_code == 503 + assert "Госуслуги" in response.text + assert "попробуйте ещё раз" not in response.text + assert "asurso.ru" in response.text + row = await session.scalar(select(DiaryLinkCode)) + await session.refresh(row) + assert row.used_at is None, "nothing looked at the password" diff --git a/server/tests/test_directory.py b/server/tests/test_directory.py index a1afdde6..b860bc97 100644 --- a/server/tests/test_directory.py +++ b/server/tests/test_directory.py @@ -343,9 +343,46 @@ async def test_every_call_counts_against_the_caller(client, upstream, session, m assert await _attempts(session) == 20 assert len(upstream.requests) == 10 - # Its own bucket: twenty searches have not spent a phone's join attempts. - joined = await client.post("/api/v1/join", json={"code": "NOSUCH12"}) - assert joined.status_code == 404 + # One key, and one that fits its column: SQLite ignores a VARCHAR's width + # and Postgres refuses the insert, so a key built as «directory:» + the + # digest passed here and was a 500 on every search in production — the + # shape of the `/diary/login` outage `caller_bucket` was written after. + keys = set(await session.scalars(select(JoinAttempt.client_key))) + assert len(keys) == 1 + assert len(next(iter(keys))) <= JoinAttempt.__table__.c.client_key.type.length + + +async def test_twenty_searches_spend_nothing_of_the_join_or_the_diary_sign_in( + client, upstream, session, monkeypatch +): + """Its own bucket, asked of the two doors that share the table. + + One `/join` after twenty searches cannot tell: `/join` allows thirty, so + it answers 404 whether the searches landed in its bucket or not. Enough + mistyped codes to cross thirty only if the twenty were counted there can; + and a diary sign-in allows ten, so a single wrong password is a 401 in its + own bucket and a 429 in the directory's. + """ + from app.api import diary as diary_api + from app.providers.diary.errors import BadCredentials + + for _ in range(directory.directory_limiter.limit): + assert (await client.get(PATH, params={"q": "школа 5"})).status_code == 200 + assert (await client.get(PATH, params={"q": "школа 5"})).status_code == 429 + + shared_would_refuse = public.join_limiter.limit - directory.directory_limiter.limit + 1 + for _ in range(shared_would_refuse): + joined = await client.post("/api/v1/join", json={"code": "NOSUCH12"}) + assert joined.status_code == 404 + + async def wrong_password(*args, **kwargs): + raise BadCredentials() + + monkeypatch.setattr(diary_api.service, "sign_in", wrong_password) + refused = await client.post( + "/api/v1/diary/login", json={"login": "parent@example.com", "password": "wrong"} + ) + assert refused.status_code == 401 async def test_the_daily_allowance_stops_the_search_and_says_until_when( @@ -485,6 +522,7 @@ def test_every_throttle_on_the_attempts_table_uses_one_window(): """ built = _throttles_built_in_app() assert sorted(path for path, _ in built) == [ + "api/diary.py", "api/diary.py", "api/directory.py", "api/public.py", @@ -497,7 +535,46 @@ def test_every_throttle_on_the_attempts_table_uses_one_window(): assert isinstance(window, ast.Constant), path assert float(window.value) == 900.0, path - live = [public.join_limiter, diary.diary_login_limiter, directory.directory_limiter] + live = [ + public.join_limiter, + diary.diary_login_limiter, + diary.diary_open_limiter, + directory.directory_limiter, + ] assert {limiter.window for limiter in live} == {900.0} assert cron.JOIN_ATTEMPT_TTL.total_seconds() >= 900.0 assert directory.directory_limiter.limit == 20 + + +@pytest.fixture +async def own_pool(): + """A connection pool of this test's own. A burst waits on the pool, which + binds the pool's queue to this test's event loop — and the next test runs + on another loop and cannot wait on it. Disposed before and after.""" + from app.db import engine + + await engine.dispose() + yield + await engine.dispose() + + +async def test_a_parallel_burst_from_one_address_cannot_pass_the_limit( + client, upstream, session, own_pool +): + """The check was two SELECTs and the record an INSERT after the query had + been validated, with nothing between them: every request of a burst read + the count from before any of them was written, and each spent from the + anonymous share. Sent one after another, as the test above does, the gap + never shows.""" + import asyncio + + upstream.answer([row('ГБОУ "ЛИЦЕЙ № 1535"', ogrn="1", kladr="7700000000000")]) + + responses = await asyncio.gather( + *(client.get(PATH, params={"q": "лицей 1535"}) for _ in range(100)) + ) + + let_through = [r for r in responses if r.status_code != 429] + assert len(let_through) <= directory.directory_limiter.limit + assert await _attempts(session) <= directory.directory_limiter.limit + assert len(upstream.requests) <= directory.directory_limiter.limit diff --git a/server/tests/test_netschool_client.py b/server/tests/test_netschool_client.py index ade34a66..d34807ca 100644 --- a/server/tests/test_netschool_client.py +++ b/server/tests/test_netschool_client.py @@ -427,3 +427,39 @@ def handler(request: httpx.Request) -> httpx.Response: ) assert response.status_code != 500, response.text assert response.status_code in (200, 401, 502, 503) + + +async def test_terms_during_an_outage_are_the_diary_down_not_a_list(monkeypatch): + """terms/search read a 502 page's JSON — or failed to parse its HTML — as + the terms; an outage is `UpstreamUnavailable` here as everywhere else.""" + from app.providers.diary.errors import UpstreamUnavailable + + _install(monkeypatch, lambda request: httpx.Response( + 502, text="

502 Bad Gateway

", headers={"content-type": "text/html"})) + await nsclient.close_client() + try: + client = nsclient.NetSchoolClient(region_for("samara"), {"at": "a", "cookies": {}}) + with pytest.raises(UpstreamUnavailable): + await client.terms_search(3) + finally: + await nsclient.close_client() + + +async def test_a_body_that_will_not_decode_before_the_password_hands_the_ticket_back( + monkeypatch, +): + """A DecodingError is not a TransportError. At `logindata`, before any + password is sent, it walked out as a 500 that spent the sign-in ticket.""" + from app.providers.diary.errors import UpstreamUnavailable + + _install(monkeypatch, lambda request: httpx.Response( + 200, + headers={"content-type": "application/json", "content-encoding": "gzip"}, + stream=httpx.ByteStream(b"not gzip at all"), + )) + await nsclient.close_client() + try: + with pytest.raises(UpstreamUnavailable): + await nsclient.NetSchoolClient(region_for("samara")).login_allowed() + finally: + await nsclient.close_client() diff --git a/server/tests/test_quota.py b/server/tests/test_quota.py index e3db75fd..4846b827 100644 --- a/server/tests/test_quota.py +++ b/server/tests/test_quota.py @@ -25,6 +25,7 @@ import sys from datetime import UTC, date, datetime, timedelta, timezone from pathlib import Path +from types import SimpleNamespace import pytest from alembic.migration import MigrationContext @@ -97,6 +98,60 @@ async def test_a_spend_of_nothing_is_a_mistake_not_a_free_pass(session): await quota.spend(session, "a", 0, cap=2, day=date(2026, 9, 25)) +def test_every_scope_fits_its_column(): + """SQLite ignores a VARCHAR's width, so a scope longer than the column + passes every test here and is a 500 on every search on Postgres. Every + upper-case string in the module is a scope today; one that is not can + still stand being measured.""" + width = UsageCounter.__table__.c.scope.type.length + scopes = { + name: value + for name, value in vars(quota).items() + if name.isupper() and isinstance(value, str) + } + assert "DADATA_ANONYMOUS" in scopes + assert {name: len(value) for name, value in scopes.items() if len(value) > width} == {} + + +class _Captured: + """A session that says it is Postgres and keeps the statement it is + handed. CI has no Postgres, so the dialect's own branch is otherwise + never built: swapping its insert for one with no ``on_conflict_do_update`` + would be green here and an AttributeError on every search in production.""" + + class _Result: + def scalar_one_or_none(self): + return 1 + + def __init__(self) -> None: + self.statements: list = [] + self.committed = False + + def get_bind(self): + return SimpleNamespace(dialect=postgresql.dialect()) + + async def execute(self, statement): + self.statements.append(statement) + return self._Result() + + async def commit(self) -> None: + self.committed = True + + +async def test_the_spend_on_postgres_is_one_guarded_upsert(): + captured = _Captured() + + assert await quota.spend(captured, "a", 2, cap=5, day=date(2026, 9, 25)) + + (statement,) = captured.statements + sql = _words(str(statement.compile(dialect=postgresql.dialect()))) + assert sql.startswith("INSERT INTO usage_counters (scope, day, used) VALUES") + assert "ON CONFLICT (scope, day) DO UPDATE SET used = (usage_counters.used +" in sql + assert "WHERE usage_counters.used + %(used_2)s <= %(param_1)s" in sql + assert sql.endswith("RETURNING usage_counters.used") + assert captured.committed + + # ---- the revision --------------------------------------------------------- From d20825148ca0f1bdc91faa139111e8a7d151d28a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 08:54:58 +0000 Subject: [PATCH 26/30] Hold the server's checks level on SQLAlchemy 2.1, which every fresh install now gets The pin is `>=2.0.54` with no ceiling, so CI and Vercel resolve 2.1.1 while a checkout made before 2.1 was published keeps 2.0.54. Two checks read the two versions differently (#164). The Postgres upsert test compared the compiled statement word for word, and 2.1 writes a cast after every bind parameter on that dialect (`%(used_2)s::INTEGER`). The statement is right on both; the casts are now taken out before the shape is compared, so the test asks what it meant to: one insert, one guarded update, one RETURNING. mypy stopped being clean on main: 2.1 types the rows of a two-entity select, so `remind_at` reaches the comparison as `datetime | None`. The query's WHERE already refuses a NULL; the guard says so where the checker can see it, and changes nothing at run time. Pinning `<2.1` would test something production no longer runs. The whole suite passes on 2.1.1: ruff clean, mypy clean over 100 modules, 1998 passed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- server/app/services/reminders.py | 5 ++++- server/tests/test_quota.py | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/server/app/services/reminders.py b/server/app/services/reminders.py index dbda922d..cbc24f9d 100644 --- a/server/app/services/reminders.py +++ b/server/app/services/reminders.py @@ -287,7 +287,10 @@ async def due_task_reminders( ) due: list[tuple[PersonalTask, SchoolClass]] = [] for task, school_class in rows: - if task.remind_at <= local_now(now_utc, school_class): + # The WHERE above already refuses a NULL; SQLAlchemy 2.1 types the + # row, so the column's own `datetime | None` reaches here and the + # guard is what tells the type checker what the query already knows. + if task.remind_at is not None and task.remind_at <= local_now(now_utc, school_class): due.append((task, school_class)) if len(due) >= MAX_PER_TICK: break diff --git a/server/tests/test_quota.py b/server/tests/test_quota.py index 4846b827..a02f1f75 100644 --- a/server/tests/test_quota.py +++ b/server/tests/test_quota.py @@ -20,6 +20,7 @@ import importlib.util import io import os +import re import sqlite3 import subprocess import sys @@ -144,7 +145,13 @@ async def test_the_spend_on_postgres_is_one_guarded_upsert(): assert await quota.spend(captured, "a", 2, cap=5, day=date(2026, 9, 25)) (statement,) = captured.statements - sql = _words(str(statement.compile(dialect=postgresql.dialect()))) + # Newer SQLAlchemy releases write an explicit cast after every bind + # parameter on this dialect (`%(used_2)s::INTEGER`), older ones do not, + # and CI installs whatever `>=` resolves to that day — so the casts are + # taken out before the shape is compared. What the test asks is the + # statement's shape: one insert, one guarded update, one RETURNING. + rendered = _words(str(statement.compile(dialect=postgresql.dialect()))) + sql = re.sub(r"::[A-Z]+(?:\(\d+\))?", "", rendered) assert sql.startswith("INSERT INTO usage_counters (scope, day, used) VALUES") assert "ON CONFLICT (scope, day) DO UPDATE SET used = (usage_counters.used +" in sql assert "WHERE usage_counters.used + %(used_2)s <= %(param_1)s" in sql From f31e5ed0d39eacd885f27680cf168e896caf4b14 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 08:55:20 +0000 Subject: [PATCH 27/30] Label Dependabot's bumps and template reports with the families the project filters on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dependabot asked for `dependencies`, `android`, `server`, `vercel` and `ci`, none of which exists, and it skips a missing label without a word — so every bump it ever opened arrived bare. The two issue templates applied GitHub's untouched `bug` and `enhancement`, so a report filed from the new-issue page landed outside `type:` and `status:` and no view built on them listed it (#162). Bumps now carry `type:chore` and the `area:` their ecosystem lives in; a bug report `type:bug` and a proposal `type:feature`, both `status:next` so a new one has a status before anybody reads it. No `area:` on the templates: the reporter cannot know which half is at fault, and a guess there is worse than none. Not covered: whether GitHub's board auto-add picks these up is the owner's filter, which a session here cannot read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- .github/ISSUE_TEMPLATE/feature_request.yml | 2 +- .github/dependabot.yml | 23 +++++++++++++--------- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4bc6f80c..6136647a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,6 +1,6 @@ name: Bug description: Something behaves wrongly — in the app, the widget, the bot or on the server -labels: ["bug"] +labels: ["type:bug", "status:next"] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index ea8936fc..34096f4d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,6 +1,6 @@ name: Proposal description: Propose a new capability, or a change to how something behaves -labels: ["enhancement"] +labels: ["type:feature", "status:next"] body: - type: markdown attributes: diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9e5b8981..d541cb6a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,12 @@ version: 2 # over from projects that build on them, and the catalog's header names the # source of each. That is why updates are grouped and capped — five open pull # requests carrying Compose alphas one at a time is a lottery, not an update. +# +# The labels are the project's own families, `type:` and `area:`, and each one +# has to exist already: Dependabot skips a label the repository does not have, +# without a word. It asked for `dependencies`, `android`, `server`, `vercel` +# and `ci` for months, none of which existed, and every bump arrived bare +# (#162). updates: - package-ecosystem: gradle directory: /android @@ -19,8 +25,8 @@ updates: day: monday open-pull-requests-limit: 5 labels: - - dependencies - - android + - type:chore + - area:android groups: androidx: patterns: @@ -58,8 +64,8 @@ updates: day: monday open-pull-requests-limit: 5 labels: - - dependencies - - server + - type:chore + - area:server groups: testing: patterns: @@ -87,14 +93,13 @@ updates: day: monday open-pull-requests-limit: 3 labels: - - dependencies - - server - - vercel + - type:chore + - area:server - package-ecosystem: github-actions directory: / schedule: interval: monthly labels: - - dependencies - - ci + - type:chore + - area:ci From 50464d0671bf13930f300163e1c5fa21e64c4105 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 08:59:10 +0000 Subject: [PATCH 28/30] Say where #140 stands now that both reviews are in: one decision left, and the migrations held for it HANDOVER's schema paragraph promised to be replaced with a time and an outcome. The outcome, for now, is that `0015` and `0016` have not run and are held on purpose. The owner allowed them on the condition that the code has no known defect, and #165 is one: a session registered from a phone names its own login, and corrections are filed under it. Its fix is the owner's product decision, and the first answer was withdrawn before it touched a file. The opening now says what stands between #140 and the merge, in order. The defect table carries #161 to #165, and the issue ranges and the close/stay-open lists follow it. The counts are the measured ones in all four places that quote them: server 1998 (run on SQLAlchemy 2.1.1, which CI and Vercel install), and Android 1408, whose test tasks Gradle found up to date against the current sources. The per-module split in docs/architecture.md moves with it. Not covered: the grep for Russian in Kotlin was not re-run, and no Kotlin has changed since it last was. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- CLAUDE.md | 2 +- HANDOVER.md | 86 +++++++++++++++++++++++++++++++------------- README.md | 4 +-- docs/architecture.md | 4 +-- 4 files changed, 66 insertions(+), 30 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0e5b12de..6f0765dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,7 +47,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 1944 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 1998 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at diff --git a/HANDOVER.md b/HANDOVER.md index c1774337..a3de272a 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -4,7 +4,7 @@ A working document, not part of the reference set in `docs/`. It describes **the the moment of handover**, so that a new session — human or agent — continues from the same place without reopening or redoing anything. -Last updated: **25 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are +Last updated: **26 September 2026**. **PRs #63 through #85, #128, #129, #133 and #134 are merged**; `main` is at `fa4fe0c`, the merge of #134. `dev` is still at `a43c6e8`, the merge of #129, because #133 and #134 each went in from a branch of their own, and #140 is on one too. It is behind `main` and has nothing `main` lacks, so bringing it level is a @@ -13,10 +13,15 @@ fast-forward. **The only thing open is the pull request carrying this paragraph, `v0.9.0 — NetSchool e-diary, onboarding via the school's diary`. It is no longer a draft: the owner created that milestone on 25 September and renamed the other nine the same day (the table, with what each was called before, is under «And before that: nothing on a -screen is cut off»). What stands between it and the merge is the `github-pr` skill's -checklist — CI green on the exact head, and the findings of the review of its code fixed on -the branch — and `0015` and `0016` on the production database, below. The SHA of its own merge -is for the next close-out to write. +screen is cut off»). Both reviews of its code have finished, and every confirmed finding is +fixed on the branch but one. That one is **#165**, and it is the owner's to decide. Three +things now stand between #140 and the merge, in this order: +1. The owner decides #165, and its fix lands here. +2. `0015` and `0016` go onto the production database. The owner made them conditional on + code with no known defect, and «Schema» below says why they have not run. +3. The `github-pr` skill's checklist passes on the exact head. + +The SHA of its own merge is for the next close-out to write. **Code moved on both halves, and the schema with it.** #140 carries two batches. The first (#139, `4c34cb5` to `42fdf0a`) reads a second electronic diary, «Сетевой город» (ИРТех @@ -25,10 +30,11 @@ unchanged. The second (#141, from `17c0473`) is the owner's request of 25 Septem run with two ways in — the class code, or the family's own school's diary — on which the password goes from the phone to the diary and never to this server, and a phone that reads only its diary gets a home of its own. Both halves' gates were run rather than quoted: -server **1944** tests, Android **1371**. +server **1998** tests, Android **1408**. -**Once #140 merges, twenty issues are meant to close and twenty-four stay open.** Meant to -close: #136–#139, #141, #145–#155 and #157–#160. Staying open: **#156**, whose fix is in +**Once #140 merges, twenty-four issues are meant to close and twenty-five stay open.** Meant to +close: #136–#139, #141, #145–#155 and #157–#164. Staying open: **#165** until the owner +decides it; **#156**, whose fix is in `ce9c749` but which waits for a phone's backup to be read (`needs:device`); **#135**, the owner's decision about the second diary, which the code has now answered but which is theirs to close; **#142**, **#143** and **#144**, this batch's deliberate follow-ups, on no @@ -74,7 +80,7 @@ milestones were the only grouping the history had. Forty-two issues were opened open, for the whole of what was left. Several of the open ones record a decision *not* to do something, so that a later session does not re-discover it as an oversight. From #129 on, a found defect becomes an issue before it becomes a fix: #131 and #132 were the first two -filed under that rule, and #140's branch filed #136–#138 and #145–#160. +filed under that rule, and #140's branch filed #136–#138 and #145–#165. ## Where the work happens from here: a local machine @@ -124,10 +130,10 @@ section describes, **#118–#122** are the owner's alone, and **#126** collects things carried deliberately, so that a later session does not re-discover a decision as if it were an oversight. -**Twenty-eight have been filed since.** #130 was the survey #134 closed, and #131 and #132 +**Thirty-three have been filed since.** #130 was the survey #134 closed, and #131 and #132 the two defects #133 closed. #135 is the owner's decision about the second diary; #136–#139 and #141 are the work #140 carries; #142–#144 are its deliberate follow-ups, on no -milestone; and #145–#160 are the defects found on its branch, each filed before its fix. +milestone; and #145–#165 are the defects found on its branch, each filed before its fix. Labels are `type:` (feature, bug, chore, research, decision, epic), `area:`, `status:` (now, next, someday, done) and `needs:` (device, owner). **A session cannot create a GitHub @@ -249,7 +255,7 @@ and four of documents. ### The defects, each filed before its fix -Sixteen, on top of part one's three (#136–#138): +Twenty-one, on top of part one's three (#136–#138): | Issue | What was wrong | Fixed in | | --- | --- | --- | @@ -269,10 +275,18 @@ Sixteen, on top of part one's three (#136–#138): | #158 | the bot's sign-in page sent a «Сетевой город» family to Петербург's diary on an unreadable answer | `0a9a188` | | #159 | CI skipped the server tests that read `docs/deploy.md` and `docs/build.md` when only those changed | `ba9170c` | | #160 | contributor and agent documents quoted a stale test command, stale counts, wrong secret names and milestone facts | `8bad211` | +| #161 | a join whose screen was gone before it landed left its result behind; the next «Добавить класс» sheet closed on it, and the first run could skip the class's diary sign-in | `061a716` | +| #162 | Dependabot and the issue templates applied labels the project does not have, so bumps arrived bare and reports outside `type:` and `status:` | `f31e5ed` | +| #163 | the join and diary sign-in throttles counted before they recorded, so a burst went past them (24 wrong passwords against a limit of 10) | `6b0878f` | +| #164 | the server's checks assumed SQLAlchemy 2.0 while every fresh install resolves 2.1: one test compared SQL without casts, and mypy failed on `main` | `d208251` | +| #165 | a session registered from a phone names its own login, unchecked, and that login keys another family's corrections | **not fixed** — waits for the owner (`needs:owner`) | Twelve more, from an adversarial review of the new Android data layer, were fixed in -`9c797a2`, each with a test that failed before its fix; they are listed in that commit's body -and have no issues of their own. +`9c797a2`, each with a test that failed before its fix. They are listed in that commit's +body and have no issues of their own: they were in code this branch adds, and none of it +had reached `main`. The same holds for the thirty findings of the second review of the +screens (`061a716`, 31 in all, one of them #161) and for twenty of the audit of the server +half (`6b0878f`, 22 in all: #163 fixed, #165 open). **One commit body is wrong, and the code is right.** `6fa1c6e` says rebinding a class to another *school* expires its diary sessions. `services/diary.expire_off_binding` expires them @@ -299,7 +313,19 @@ first, and `alembic_version` stamped to `0016` in the same transaction. On 25 Se production read `0014`, with **0** rows in `diary_sessions` and **1** class, so neither revision had a row to touch. -**Not applied yet, at the time of this commit.** The owner allowed both on one condition: that the code they serve is free of defects. The audit of the server half and of the two revisions was still running, and the DDL taken from the models had been compared with both revision files op by op, with no difference. This paragraph is replaced with the time and the outcome when the transaction runs, and that happens before the merge or not at all. +**Not applied, and held on purpose, as of 26 September.** The owner allowed both on one +condition: that the code they serve is free of defects. The audit of the server half and of +both revisions has finished since. 22 findings survived two refuters each, and `6b0878f` +fixed 21 of them. The revisions' PostgreSQL DDL came out of that unchanged, and it still +matches the models op by op, which `test_quota` and `test_diary_provider_revision` now pin. +The 22nd finding is **#165**: a session registered from a phone names its own login, and +the family's corrections are filed under it. Its fix is a product decision. The owner first +chose to key corrections on the account the diary vouches for, then stopped that +implementation before it changed a file, so the decision is open (`needs:owner`). Until it +closes, the condition is not met, so the transaction has not run and #140 does not merge; +merging without `0015` and `0016` would take the bot down. Neither revision depends on how +#165 is decided: two of its three answers need no schema, and the third would be an additive +`0017`. When it runs, this paragraph gets the time and what the database said. ### What was deliberately left alone @@ -332,14 +358,19 @@ revision had a row to touch. ### Gates -Run, not quoted, on the branch as it stood at `8bad211`: `ruff check app tests scripts -migrations` clean; `pytest -q -n auto` **1944** passed (1634 on `main`); `python -m mypy` -**Success** across **100** modules (84 on `main`); `./gradlew test` **1371** (968 on `main`) — -`:app` 513, `:core:data` 532, `:core:designsystem` 99, `:core:model` 125, `:widget` 102. -`assembleDebug` and `assembleRelease` were last run locally at `c032ff2`, and CI builds both -on every push. `b19e6b2` and `c032ff2` report the grep for Russian in Kotlin finding nothing -new but `UpstreamMarkers.kt`, the diaries' own words matched in their answers; it was not -re-run for this close-out. +Run, not quoted. The server was run on the branch at `d208251`, against **SQLAlchemy +2.1.1**, which is what CI and Vercel install now (#164): `ruff check app tests scripts +migrations` clean; `pytest -q -n auto` **1998** passed (1634 on `main`); `python -m mypy` +**Success** across **100** modules (84 on `main`). The Android tests were run at `061a716`, +and Gradle found every test task up to date against the sources at `f31e5ed`: `./gradlew +test` **1408** (968 on `main`), with `:app` 548, `:core:data` 532, `:core:designsystem` 99, +`:core:model` 125 and `:widget` 104. `assembleDebug` and `assembleRelease` were last run +locally at `061a716`, and CI builds both on every push. A checkout set up before 2.1 was +published keeps SQLAlchemy 2.0.54 until it is upgraded. The suite passes on both, and a +mypy run on 2.0 does not see what 2.1's typing sees. `b19e6b2` and `c032ff2` report the +grep for Russian in Kotlin finding nothing new but `UpstreamMarkers.kt`, the diaries' own +words matched in their answers. It was not re-run for this close-out, and no Kotlin has +changed since `061a716`. ### What nobody has verified in this batch @@ -357,6 +388,11 @@ Section 5 carries each of these with the reason it is unverifiable. In short: - **DaData**: whether its company rows carry `region_kladr_id`, the codes of the four regions admitted in 2022, and whether its day turns at Moscow midnight. - **The legal texts have never been read by a lawyer.** +- **The throttles' record-then-count (#163) is proven on SQLite only.** On PostgreSQL it + rests on READ COMMITTED showing each statement every commit before it, and it has not run + against a live database. Neither has `alembic upgrade head` on an empty PostgreSQL. The + permission system refused a local server, so `0015`'s guard for a database that `0001` + built is proven offline and on SQLite. ## What the session before it added: the electronic diary of every Russian region, and the routes each platform exposes @@ -2736,9 +2772,9 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 1944 tests, ~4 min (CI runs this) +cd server && pytest -q -n auto # 1998 tests, ~4 min (CI runs this) cd server && python -m mypy # clean, 100 modules -cd android && ./gradlew test # 1371 tests across the five modules +cd android && ./gradlew test # 1408 tests across the five modules cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` diff --git a/README.md b/README.md index 1b7a25ee..1d7dbe2f 100644 --- a/README.md +++ b/README.md @@ -206,8 +206,8 @@ Read this before planning a release. | --- | --- | | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 1944 tests, green, about four minutes — the command CI runs | -| `./gradlew test` | 1371 tests, green, all five modules | +| `pytest -q -n auto` | 1998 tests, green, about four minutes — the command CI runs | +| `./gradlew test` | 1408 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | diff --git a/docs/architecture.md b/docs/architecture.md index 7364f4d6..39ef41e8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -715,9 +715,9 @@ with the host. ## Testing -1944 tests on the server, 1371 on Android; `pytest -q -n auto` and `./gradlew test`, both +1998 tests on the server, 1408 on Android; `pytest -q -n auto` and `./gradlew test`, both offline, both in CI. On Android that is `:core:model` 125, `:core:data` 532, -`:core:designsystem` 99, `:widget` 102, `:app` 513. +`:core:designsystem` 99, `:widget` 104, `:app` 548. The table below is the load-bearing part of that rather than the whole of it: From e01443d91882bfa2a0d2e78320502c57599bb2ba Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 11:18:27 +0000 Subject: [PATCH 29/30] File the family's diary corrections under the child, so a login a phone names reaches nothing its own diary does not list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A session registered from a phone names its own login, and nothing upstream vouches for it; the corrections were filed under that login, so another adult whose diary listed the same child could name the first family's login and read or rewrite its corrections (#165). The owner decided on 26 September that the corrections are the child's: shared by everyone whose own diary lists the child — both parents, and the pupil's own account — and reached only through that list. - The key is `child_scope(provider, region)`: `CHILD:petersburg`, or `CHILD:netschool:` and the host of the region's diary server, since a «Сетевой город» pupil is numbered per server — a region that moves server loses its corrections rather than handing them to whoever carries the same number there. It lives in the column still called `login`; no schema change. The upper-case prefix means no key can equal an old one, which is always a lowercased login, so code reverted to main can neither read nor write a per-child row. - The routes build the key from the session's diary, never from its login, after `_student` has found the child among this session's own pupils; the store refuses anything that is not a scope. Reset-all stays bounded by the child. - Two children can no longer share a key: a Petersburg child listed by a plain `id` instead of `identity.id` gets no corrections at all (a 422 on write, nothing laid over its reads), and «Сетевой город»'s JSON `true` is no longer pupil 1 or class 1. - `0017` is data only. It deletes the branch-only «Сетевой город» hash-keyed rows, keeps the newest row where two logins corrected one field of one child, and files the rest under the child, after a lock on PostgreSQL. Its docstring gives the count of what each step deletes, and why, on a deployment that holds corrections, it goes on just after the merge. Production held 0 corrections and 0 diary sessions when read on 26 September, so there it rewrites nothing and goes on with 0015 and 0016. - The privacy policy and the terms in both languages, the phone's correction note, docs/api.md, docs/guide.md, docs/deploy.md, CLAUDE.md, README, AGENTS.md and the migration skill say what is now true: shared per child, a reset removes it for everyone, the last writer wins, no row says who wrote it, and a deletion request can be met per child or per named correction. Legal edition 1 was never published, so it is edited in place. An adversarial review of this change (five lenses, two refuters per finding) confirmed 17 of 23 findings; all 17 are fixed here, each with a test that failed without it or, for the documentation ones, with the text made true. Gates: ruff clean, mypy clean (100 files), pytest -n auto 2024 passed (1998 before) on SQLAlchemy 2.1.1; ./gradlew test 1408, rerun after the last text edit; the alembic chain from nothing lands on 0017. Not covered: that a «Сетевой город» pupil id is unique per server rather than per school, and that two parents' accounts see one child under one id in either diary, have never been observed live. 0017's lock was proven on a scratch PostgreSQL 16, not on Neon. Closes #165 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/agents/server-migrations.md | 16 +- .claude/skills/migration/SKILL.md | 11 +- AGENTS.md | 3 +- CLAUDE.md | 28 +- README.md | 12 +- .../lessons/ui/diary/DiaryViewModel.kt | 10 + .../src/main/res/values-en/strings_diary.xml | 2 +- .../app/src/main/res/values/strings_diary.xml | 2 +- .../lessons/core/data/network/DiaryApi.kt | 11 +- .../core/data/repository/DiaryLogin.kt | 7 +- .../core/data/repository/DiaryRepository.kt | 3 +- .../core/data/repository/DiarySignInImpl.kt | 5 +- .../core/data/repository/DiaryTarget.kt | 4 +- docs/api.md | 71 ++- docs/architecture.md | 4 +- docs/deploy.md | 56 ++- docs/guide.md | 19 +- docs/legal/privacy.en.md | 15 +- docs/legal/privacy.ru.md | 21 +- docs/legal/terms.en.md | 4 +- docs/legal/terms.ru.md | 4 +- server/app/api/diary.py | 107 +++-- server/app/db.py | 2 +- server/app/models.py | 50 +- server/app/providers/diary/models.py | 7 + server/app/providers/netschool/mapper.py | 20 +- server/app/providers/petersburg/mapper.py | 21 +- server/app/schemas.py | 21 +- server/app/services/diary.py | 242 ++++++---- .../versions/0017_corrections_per_child.py | 198 ++++++++ .../test_corrections_per_child_revision.py | 372 +++++++++++++++ server/tests/test_diary_api.py | 70 ++- .../tests/test_diary_corrections_per_child.py | 448 ++++++++++++++++++ server/tests/test_diary_mapper.py | 14 + server/tests/test_diary_protocol_vectors.py | 6 +- server/tests/test_diary_provider_revision.py | 6 +- server/tests/test_diary_session.py | 10 +- server/tests/test_netschool_mapper.py | 20 + server/tests/test_quota.py | 6 +- server/tests/test_schema_version.py | 46 ++ 40 files changed, 1727 insertions(+), 247 deletions(-) create mode 100644 server/migrations/versions/0017_corrections_per_child.py create mode 100644 server/tests/test_corrections_per_child_revision.py create mode 100644 server/tests/test_diary_corrections_per_child.py diff --git a/.claude/agents/server-migrations.md b/.claude/agents/server-migrations.md index c87aee3c..17b7c700 100644 --- a/.claude/agents/server-migrations.md +++ b/.claude/agents/server-migrations.md @@ -4,7 +4,8 @@ description: Alembic revisions and the Neon protocol. Use whenever a model chang tools: Read, Glob, Grep, Bash, Edit, Write --- -You own `server/migrations/`. Production is at **`0013`**, which is the head. +You own `server/migrations/`. Head is **`0017`**; production was last read at `0014`, and +`0015`, `0016` and `0017` go on together before #140 merges. ## The chain, and what each one did @@ -17,7 +18,11 @@ number (1–11) and cuts its year into quarters or half-years. `0009` adds the c family lays over the diary. `0010` gives a class its join mode and adds the personal connect codes. `0011` tightens two `diary_overrides` timestamps. `0012` tightens eight more across seven tables — and on this database it was **not** a no-op: all eight were nullable and all -eight held zero nulls. `0013` adds `uq_homework_per_subject_per_day`. +eight held zero nulls. `0013` adds `uq_homework_per_subject_per_day`. `0014` widens +`day_overrides.kind` for a new `DayKind`. `0015` adds the second diary provider's columns. +`0016` creates `usage_counters`. `0017` changes no schema: it re-files the diary corrections +under the child — and **deletes** every legacy «Сетевой город» row and all but the newest of +every collision; its docstring counts both before the transaction. ## Two rules that point in opposite directions @@ -32,8 +37,11 @@ eight held zero nulls. `0013` adds `uq_homework_per_subject_per_day`. `services/homework.py` is written to be correct with or without it so the window in between behaves exactly like production did before. -Read the database before either. `0012` turned out to be a real fix rather than the no-op -`0011` was, because the columns really were nullable there. +A third shape, **a rewrite of a key**, goes after the merge where there are rows to rewrite +and is free where there are none; `0017` is it, and its docstring says what each order loses. + +Read the database before any of them. `0012` turned out to be a real fix rather than the +no-op `0011` was, because the columns really were nullable there. ## How a revision is actually applied here diff --git a/.claude/skills/migration/SKILL.md b/.claude/skills/migration/SKILL.md index ed9fc112..ca5dd191 100644 --- a/.claude/skills/migration/SKILL.md +++ b/.claude/skills/migration/SKILL.md @@ -5,7 +5,7 @@ description: Write and apply an Alembic revision for this project — including # A migration, start to finish -Head is **`0016`**. Nothing after `0001` may use `create_all`. +Head is **`0017`**. Nothing after `0001` may use `create_all`. ## 1. Decide the direction @@ -18,6 +18,15 @@ Head is **`0016`**. Nothing after `0001` may use `create_all`. breaks against the constraint, with an `IntegrityError` nobody catches. Write the service so it is correct with or without the constraint, so the window behaves like production did before. `0013` is this shape and says so in its own docstring. +- **A rewrite of a key** (rows moved from one key to another, no schema change) → **free** + where there are no rows to move, so it goes on with the additive revisions; **after** the + merge where there are. Old and new code file the same rows under different keys, so each + order loses what the window makes: before the merge, what the old code writes is filed + where the new code never reads; after it, nothing typed is lost but a reset made in the + window is undone when the rewrite runs — keep that window to minutes, and expect + `/api/v1/warmup` to say «База отстала от кода» through it. Lock the table on PostgreSQL + first, or a write landing between the rewrite's statements breaks it. A redeploy never + re-runs a stamped revision, so after a revert run it again by hand. `0017` is this shape. ## 2. Read the database first diff --git a/AGENTS.md b/AGENTS.md index 15ca8b06..546a7299 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,8 @@ CI is exactly: ruff, pytest `-n auto`, `./gradlew test`, both assembles. `./grad 2. **Telegram refuses a message over 4096 characters whole**, rather than clipping it, and everything from outside must be HTML-escaped before it goes in. 3. **A model change needs an Alembic revision**, and the direction matters: additive goes on - before the merge, a `UNIQUE` or `NOT NULL` after. Head is `0013`. + before the merge, a `UNIQUE` or `NOT NULL` after, a rewrite of a key after where there are + rows to rewrite. Head is `0017`. 4. **`LocalDateTime.now()` and `ZoneId.systemDefault()` on the Android side are almost always a bug** — time is naive local wall time in the *class's* zone. 5. **Secrets never enter the repository.** Redact as `` in issues, logs and diff --git a/CLAUDE.md b/CLAUDE.md index 6f0765dd..360906c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,7 +47,7 @@ Server, from `server/`: - `python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"` — setup - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 1998 tests in about four minutes, and **the exact command +- **`pytest -q -n auto`** — 2024 tests in about four minutes, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` form puts the current directory on `sys.path` and the bare one does not, so a `from tests.test_api import …` in a test file passes locally and fails at @@ -354,7 +354,7 @@ points Hilt does not inject cleanly. a half-applied revision cannot claim to be whole. And say what a revision destroys before running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a sentence the owner needs *before* the transaction, not after. -- **Migrations are Alembic and the head is `0016`, which goes on with `0015` before this batch's merge.** `0001` is a guarded +- **Migrations are Alembic and the head is `0017`, which goes on with `0015` and `0016` before this batch's merge.** `0001` is a guarded `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds @@ -395,6 +395,30 @@ points Hilt does not inject cleanly. creates a table and nothing else — additive, the ordinary shape, rewrites and destroys no row — and goes on **before** the merge, together with `0015`; its downgrade drops the table and with it nothing but the counts. + `0017` changes no schema: it files the corrections over the diary under the + **child** rather than under a login (#165, the owner's decision of 26 + September) — `diary_overrides.login` keeps its name and holds the scope + `services/diary.child_scope` builds, `CHILD:petersburg` or `CHILD:netschool:` + and the regional server's host and no other shape (a child the diary lists + outside its own numbering gets no corrections at all), upper case so that + no casefolded login can ever equal one. It **destroys rows**: every legacy + «Сетевой город» key (a hash whose region is recoverable at best for authors + still signed in; only where #140's branch ran), and, wherever two logins — + or a legacy and a per-child row — corrected the same field of the same + child, all but the newest (`updated_at`, then `id`); the rest of the old + Petersburg rows are rewritten to `CHILD:petersburg`. Its docstring carries a + count per destructive step to read before the transaction, and on + PostgreSQL it locks the table against writes first. On this database, with + no correction in it on 26 September, that is nothing, and it goes on with + `0015` and `0016` **before** the merge. On a deployment that holds + corrections it is better applied just **after** the merge — a key rewrite, + a third shape beside the column and the constraint: before it, whatever the + old code writes in the window is filed under a login the new code never + reads; after it, the rewrite folds the old rows into what was typed + meanwhile, but a reset made in the window comes back, so the window is + minutes. Its downgrade is a no-op, and a revert is **not** lossless: after + any window of older code, run its statements again, or + `alembic downgrade 0016 && alembic upgrade head`. Nothing after `0001` may use `create_all`. Beware the enum: `SAEnum(SomeStrEnum)` stores the member **name**, so a `server_default` written as `.value` is a string the ORM cannot read back — which on `classes` is a diff --git a/README.md b/README.md index 1d7dbe2f..d44ebefd 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ Read this before planning a release. | --- | --- | | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 100 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 1998 tests, green, about four minutes — the command CI runs | +| `pytest -q -n auto` | 2024 tests, green, about four minutes — the command CI runs | | `./gradlew test` | 1408 tests, green, all five modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | @@ -453,10 +453,12 @@ one of them is proved by a test rather than by a screen. nobody has watched. * **`/api/v1/warmup` itself has not been read since #61**, when it answered `{"status":"ok","api_version":1,"schema":"0013"}`. Production was last recorded at `0014`; - the code on this branch expects `0016`, and `0015` and `0016` are to be applied before #140 - merges, after which it should say `0016`. That one request is the cheapest check of whether - the migrations and the code that needs them actually met — but the deployment previews sit - behind Vercel's protection, and nobody has made the check against production either. + the code on this branch expects `0017`, and `0015`, `0016` and `0017` are to be applied + before #140 merges — production holds no diary corrections, so `0017` has nothing to + rewrite there — after which it should say `0017`. That one request is the cheapest check + of whether the migrations and the code that needs them actually met — but the deployment + previews sit behind Vercel's protection, and nobody has made the check against production + either. * **`docker compose up` has not been run.** There is no Docker in this environment: the compose file was parsed and its dependency conditions asserted. The `migrate` service and the revisions now in the image are written and never watched coming up. diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt index d374e5fb..f0dd9c1e 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/diary/DiaryViewModel.kt @@ -728,6 +728,16 @@ class DiaryViewModel( * correction equal to the upstream: keeping a row that says "show exactly * what you were going to show anyway" would leave the value marked as * corrected forever, with a reset button that appears to do nothing. + * + * "What changed" is measured against the row as the sheet opened on it, + * not against a fresh read — and the row is not this account's alone. The + * corrections are the child's (#165), so the other parent may have + * rewritten or reset a field since: a field the snapshot already shows + * corrected to the typed value sends nothing, and a field typed back to the + * diary's value resets whatever is there now, theirs included. That is + * last-writer-wins, which is what the server is too — it keeps no version + * to compare against — and the reload after every save is what puts the + * outcome on screen. */ fun saveEdit(typed: Map) { val open = state.value.editing ?: return diff --git a/android/app/src/main/res/values-en/strings_diary.xml b/android/app/src/main/res/values-en/strings_diary.xml index abb5126e..45248097 100644 --- a/android/app/src/main/res/values-en/strings_diary.xml +++ b/android/app/src/main/res/values-en/strings_diary.xml @@ -91,7 +91,7 @@ This field cannot be corrected. Correct - A correction changes only what you see here. Nothing changes in the diary itself, and the teacher will not see it. + Corrections are shared: everyone whose diary in the app shows this pupil — the other parent, for example — sees them and can change them, and a reset removes them for everyone. Nothing changes in the diary itself, and the teacher will not see them. Homework Room Teacher diff --git a/android/app/src/main/res/values/strings_diary.xml b/android/app/src/main/res/values/strings_diary.xml index 118d6a4d..5d74befd 100644 --- a/android/app/src/main/res/values/strings_diary.xml +++ b/android/app/src/main/res/values/strings_diary.xml @@ -93,7 +93,7 @@ Это поле нельзя исправить. Исправить - Правка меняет только то, что вы видите здесь. В самом дневнике ничего не меняется, и учитель её не увидит. + Правки общие: их видит и может изменить каждый, чей дневник в приложении показывает этого ученика, — например, второй родитель, — а сброс убирает их у всех. В самом дневнике ничего не меняется, и учитель их не увидит. Домашнее задание Кабинет Учитель diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt index 1795dd7a..041258df 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/DiaryApi.kt @@ -127,7 +127,10 @@ internal interface DiaryApi { suspend fun attendance(@Path("id") studentId: Long): List /** - * Every correction this account has stored for this child. + * Every correction stored for this child, whoever stored it: the server + * files them under the pupil rather than under an account, so every + * account whose diary lists the pupil reads, replaces and resets the same + * rows, and nothing in them says who wrote which. * * The only calls in this interface that write anything, and they write * nothing upstream: a correction is laid over the diary's answer on the way @@ -171,7 +174,11 @@ internal interface DiaryApi { @Body body: DiaryResetRequestDto, ) - /** Drops every correction for this child, so the diary answers for itself again. */ + /** + * Drops every correction for this child, so the diary answers for itself + * again — for every account that sees the pupil, not just this one, since + * the rows are the child's. + */ @DELETE("api/v1/diary/students/{id}/overrides/all") suspend fun resetOverrides(@Path("id") studentId: Long) } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt index 9a1ed301..401e39e4 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryLogin.kt @@ -6,9 +6,10 @@ package com.lumenpearson.lessons.core.data.repository * vectors. * * One cleaning, used everywhere a login leaves the phone: the diary's own - * sign-in and our server's registration. The server keys a family's - * corrections on the login it stores, and it used to receive the password and - * clean the login itself before any upstream call. When the phone signs in on + * sign-in and our server's registration. The server stores the login only to + * name the session — it keys nothing, corrections included, which belong to + * the child — and it used to receive the password and clean the login itself + * before any upstream call. When the phone signs in on * its own, a login pasted from a chat with a bidi mark or a zero-width space * around it went upstream exactly as pasted: the diary compared it to the * account's name, said no, and the screen asked for the password again, diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt index 785461fa..6d4b2bf0 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryRepository.kt @@ -80,7 +80,8 @@ interface DiaryRepository { suspend fun periods(studentId: Long): Result> /** - * Every correction this family has stored for this child. + * Every correction stored for this child, by anyone whose diary lists the + * pupil — the other parent's as much as this account's. * * Not needed to *draw* a corrected lesson — [schedule] already comes back * corrected, with [DiaryLesson.edits] saying which fields were — but needed diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt index cf3dcfe1..fce5b403 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiarySignInImpl.kt @@ -304,8 +304,9 @@ internal class DiarySignInImpl( * it — its zone above all, so the phone's «today» is the server's. */ private fun sessionFrom(response: DiarySessionResponseDto, sent: DiaryTarget): DiarySession { - // The login as the server stored it, which keys the corrections; what - // was sent, cleaned the same way, if it ever stops echoing one. + // The login as the server stored it, which is what «Вход выполнен» + // prints and what `accountKey` compares; what was sent, cleaned the + // same way, if it ever stops echoing one. val login = DiaryLogin.clean(response.login) ?: DiaryLogin.clean(sent.login) ?: sent.login.trim() val target = sent.copy( region = response.region ?: sent.region, diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt index 5c981e69..d01436d7 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/repository/DiaryTarget.kt @@ -65,7 +65,9 @@ data class DiaryTarget( /** * Whether two targets are the same account, for deciding whether what is * cached on the phone still belongs to whoever just signed in. Local only: - * it is not the server's `owner_key` and never leaves the device. + * it never leaves the device, and it is not what the server files + * corrections under — those belong to the child, and every account whose + * diary lists that pupil reads the same ones. */ fun accountKey(): String = "${provider.wire}|${region.orEmpty()}|${login.trim().lowercase(Locale.ROOT)}" diff --git a/docs/api.md b/docs/api.md index d8a616a0..db9e59d4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -999,7 +999,7 @@ whether the schema is the one this code was written against. Three answers: | | Body | Meaning | | --- | --- | --- | -| `200` | `{"status": "ok", "api_version": 1, "schema": "0016"}` | the database is reachable and at the revision the code expects | +| `200` | `{"status": "ok", "api_version": 1, "schema": "0017"}` | the database is reachable and at the revision the code expects | | `200` | `{"status": "degraded", …, "schema": …, "expected_schema": …, "detail": …}` | both revisions named, and `detail` says **which way** they diverge | | `503` | `{"status": "down", "api_version": 1, "detail": "База недоступна."}` | the database could not be reached | @@ -1110,9 +1110,11 @@ POST /api/v1/diary/session The body is one of two shapes, chosen by `provider`, and every level of it refuses a key it does not know: **a `password` key anywhere is a `422`**, so no client can send one here, by mistake or otherwise. `login` is what the person typed into the client's own form. Nothing -upstream vouches for it; it names the session and keys the family's corrections (see -[Corrections over the diary](#corrections-over-the-diary)), so a client sends the same -string every time. For «Сетевой город», `region` must be an allow-listed key that takes a +upstream vouches for it, so it names the session — it is what the answer echoes and what +the client prints as the account signed in — and decides nothing: a login copied from +another family reaches nothing of theirs, because what a session reaches is what its own +diary lists (see [Corrections over the diary](#corrections-over-the-diary)). For «Сетевой +город», `region` must be an allow-listed key that takes a password and `school_id` the diary's own school id — both checked before any upstream call, so a region this server does not serve never receives a request. In `credential`, Petersburg's `token` must be a JWT; `NSSESSIONID` is required and `ESRNSec`, `ver` and @@ -1233,10 +1235,10 @@ diary inside a window whose limit is ten. The same holds for `/join` and the dir | `GET /api/v1/diary/students/{id}/subjects?period_id=` | a period's subjects | | `GET /api/v1/diary/students/{id}/teachers` | the teachers | | `GET /api/v1/diary/students/{id}/attendance` | the turnstile passages | -| `GET /api/v1/diary/students/{id}/overrides` | the family's corrections over the diary | +| `GET /api/v1/diary/students/{id}/overrides` | the child's corrections over the diary, whoever wrote them | | `PUT /api/v1/diary/students/{id}/overrides` | write a correction | -| `POST /api/v1/diary/students/{id}/overrides/reset` | reset one | -| `DELETE /api/v1/diary/students/{id}/overrides/all` | reset them all | +| `POST /api/v1/diary/students/{id}/overrides/reset` | reset one, for everyone who sees the child | +| `DELETE /api/v1/diary/students/{id}/overrides/all` | reset them all, for everyone who sees the child | | `POST /api/v1/diary/logout` | forget the session | `from` and `to` are ISO dates; the default is two weeks ahead and the maximum is 62 days. @@ -1263,7 +1265,7 @@ takes it out and hands it back as a list, because that is how people ask for it. The diary is **read-only** for us, and that does not change: nothing goes upstream. A correction is a value laid **over** what came from above, on the way out, and a reset takes -it off. Nothing changes in dnevnik2, and the teacher does not see the correction. +it off. Nothing changes in the diary itself, and the teacher does not see the correction. A lesson and an assignment arrive with a key and a list of corrections: @@ -1299,9 +1301,56 @@ and a passage are statements about what happened, and an app that lets you rewri produces a forged record that looks official. `subject` is not correctable because it is half of the key. -Corrections live on the **account's login** rather than on the session: a diary session dies -every few days, and a correction that went with it would disappear by itself, silently, -before anybody pressed "reset". +Corrections belong to the **child** — not to the session, and not to the login. The key is +the diary's server (Petersburg's, or the «Сетевой город» regional server's host) and the +pupil's id on it. A diary session dies every few days, and a correction that went with it +would disappear by itself, silently, before anybody pressed "reset"; and the login is only +what a client typed at +[`POST /session`](#registering-a-session-the-client-opened-post-apiv1diarysession), which +nothing upstream vouches for, so it decides nothing. + +So the corrections are **shared by everyone whose own diary lists the child**: both +parents, each signed in with their own account; the pupil's own account, when the diary +lists the pupil to themselves; and, literally, any account the diary answers with that +child — a staff account included, should its list ever not be empty (a staff account gets +`403` at registration only because its list has so far been empty, which is an observation +rather than a rule). What decides is the `{id}` check above, before any correction is read +or written: on every call the id is looked up among the pupils **this session's own diary** +lists, and anything else is a 404. **A login gains nothing**, because no correction route +reads it: naming another family's login at `/session`, or a string spelled exactly like the +server's internal key, reaches the pupils one's own diary lists and nothing else. + +What sharing means for a client: + +- **One correction per field per child, and the last writer wins** — `original` included, so + the other adult's `changed_upstream` is measured against what the last writer saw. Nothing + checks a version: a client's copy may be stale, because the other adult may have changed + or reset a field since its last read. +- **No row says who wrote it.** There is no author column, so a client cannot tell «your + correction» from «theirs», and should not say either. +- **A reset takes the correction off for everyone who sees the child** — one field, or all of + them. `DELETE …/overrides/all` never reaches beyond the one child in its path. + +The same pupil number on two diaries is two children: pupil 11 on one regional server is not +pupil 11 on another, nor the Petersburg person whose id is 11. The key follows the server's +host rather than the region's name, so if a region's origin ever moved, its corrections would +stop matching — lost — rather than attach to whichever child the new server gives the same +number. +A session whose region names no server this code knows is sent to sign in again (`401` with +`X-Diary-Reauth: required`) rather than given a guess. + +A Petersburg child the diary lists by a plain `id` rather than by its person id gets **no +corrections at all**. Nothing says what that number counts, and with the login out of the key +it would be all that told one family's child from another's. Its schedule and homework come +back as the diary has them, its list is empty, a reset answers `204` with nothing to take +off, and `PUT` answers `422` «Для этого ученика правки недоступны», which the app shows as it +shows any field it cannot correct. No live answer has been seen to take that path. + +Two things are assumed and have not been observed: that a «Сетевой город» pupil id is unique +on its server rather than only within a school, and that two parents' accounts see one child +under one id, in either diary. If the id turned out to be per school, the school would have to +come from the diary's own answer — never from the `school_id` a client sends at `/session`, +which nothing compares with the diary. Resetting one correction is `POST .../overrides/reset` with a body of `{"target": …, "field": …}`, not a `DELETE` with the same fields in the query. `target` is a diff --git a/docs/architecture.md b/docs/architecture.md index 39ef41e8..ba12cbb4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -715,7 +715,7 @@ with the host. ## Testing -1998 tests on the server, 1408 on Android; `pytest -q -n auto` and `./gradlew test`, both +2024 tests on the server, 1408 on Android; `pytest -q -n auto` and `./gradlew test`, both offline, both in CI. On Android that is `:core:model` 125, `:core:data` 532, `:core:designsystem` 99, `:widget` 104, `:app` 548. @@ -739,6 +739,8 @@ The table below is the load-bearing part of that rather than the whole of it: | `server/tests/test_diary_protocol_vectors.py` | both diaries' sign-in protocols against the known-answer vectors in `tests/vectors/diary_protocol.json`, the bytes the phone's port is tested against too | pytest + `httpx.MockTransport` | | `server/tests/test_region_catalog.py` | that the committed catalog is what the generator writes, and that only Петербург and the sixteen password «Сетевой город» regions are a sign-in | pytest | | `server/tests/test_directory.py`, `test_quota.py` | the anonymous school directory's order of refusals, the per-caller throttle, the daily share and its atomic spend, and `0016`'s DDL against the model | pytest | +| `server/tests/test_diary_corrections_per_child.py` | the corrections are the child's (#165): every account whose own diary lists the child shares them, a login copied from another family reaches nothing, one pupil number on two servers is two children, a child listed by a plain id gets no corrections at all, no scope equals a casefolded login | pytest + a fake upstream per account | +| `server/tests/test_corrections_per_child_revision.py` | `0017` is data only and locks PostgreSQL's table first, its PostgreSQL text runs on SQLite, a real upgrade leaves exactly the rows it should — collisions, legacy «Сетевой город» keys, per-child rows — twice over and after a downgrade, the counts its docstring gives the owner are what each step deletes, a reset in the after-the-merge window comes back, and a downgrade and upgrade re-file what reverted code wrote | pytest + alembic | | `android/core/model/.../ScheduleEngineTest.kt` | every `DayState`, boundary conditions, event precedence, next-transition scheduling | JVM JUnit | | `android/widget/.../WidgetSizeClassTest.kt` | the launcher's nearest-breakpoint rule over real sizes, and that the ladder is monotonic | JVM JUnit | | `android/app/.../ResourceTranslationTest.kt` | every Russian string has an English twin, in every module that ships strings | JVM JUnit | diff --git a/docs/deploy.md b/docs/deploy.md index c7e7050d..bb35303b 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -334,7 +334,27 @@ admin's card and «не привязан» behind the diary button. `0016` creat `usage_counters` — one row per external allowance per Moscow day, the anonymous school directory's share of DaData's — and nothing else: one new table, no existing row read or rewritten, additive, and it goes on **together with `0015`, before #140 merges**. Its -downgrade drops the table, which loses nothing but the counts. +downgrade drops the table, which loses nothing but the counts. `0017` changes no schema at +all: it files the corrections over the diary under the child instead of under a login +(#165) — `diary_overrides.login` keeps its name and now holds the diary's scope, +`CHILD:petersburg` or `CHILD:netschool:` and the regional server's host, and no other shape +(a child the diary lists outside its own numbering gets no corrections at all). It +**deletes** every legacy «Сетевой город» row (its region is inside a hash, recoverable at +best for authors still signed in, and such rows exist only where #140's branch ran), +deletes all but the newest row wherever two logins corrected the same field of the same +child, and rewrites the rest of the old Petersburg rows to `CHILD:petersburg`. Its +docstring carries the two counts to read before the transaction, one per destructive step. +On PostgreSQL it first locks the table against writes until it commits, so a correction +saved while it runs waits instead of making it roll back. On production, read on 26 +September with no correction in it, that is nothing, and it goes on with `0015` and `0016` +before the merge. On a deployment that holds corrections it is better applied just +**after** the merge — see the third shape below. Its downgrade does nothing, on purpose — a +login cannot be recovered from a scope, and the old code cannot read or write an +upper-case scope under any login — but a revert is not lossless: what older code writes +while it runs is filed under logins the new code never reads, and redeploying does not +re-run `0017`. After any such window, run its statements again, or +`alembic downgrade 0016 && alembic upgrade head`, which re-runs it because the downgrade does +nothing. Everything up to `0012` checks with an inspector what is not in the database yet and does not rewrite existing tables, so those can be applied to a live class in the middle of a @@ -342,8 +362,9 @@ school day. `0013`, `0015` and `0016` ask the inspector too — per constraint, per table — because on an empty database `0001` has already built today's schema, and a second `ADD COLUMN` or `ADD CONSTRAINT` there is a hard error that stops the `migrate` service below; and because a SQLite file `scripts.init_db` built before a model change is -stamped at the old head without the new columns, and only the revision adds them. The head -is `0016`. +stamped at the old head without the new columns, and only the revision adds them. `0017` +asks only whether the table is there; its statements are plain SQL that PostgreSQL and SQLite +both run, and a second run finds nothing to do. The head is `0017`. ### A migration goes BEFORE the deploy, not after @@ -368,6 +389,21 @@ nobody catches. `0013` is that shape and says so in its own docstring — it wen the merge, and `services/homework.py` is written to be correct with or without it, so the window in between behaved exactly as production did before. +**A rewrite of a key is a third shape.** `0017` breaks neither code — it changes no column — +but the old code and the new file the same rows under different keys, so whichever runs in +the window between the migration and the deploy writes rows the other cannot see, and +neither order is free of loss. Before the merge, every correction typed in the window is +filed under a login the new code never reads. After the merge, nothing typed is lost — the +new code writes per-child rows at once, and the rewrite folds the old ones into them, the +newer winning — but a **reset** made in the window is undone: the new code cannot see the +legacy row to take it off, so «Сбросить правки» or «Сбросить всё» leaves it, and `0017` then +files it under the child and the value comes back for everyone who sees the child. After is +still the smaller loss, so it is the order for a deployment that holds corrections — with +the window kept to minutes, and with `/api/v1/warmup` saying «База отстала от кода» through +it, which there is expected. Where there is nothing to rewrite — production, on 26 +September — the order is free, and it goes on with the additive revisions before the merge, +which keeps `/api/v1/warmup` level. + That the database really has caught up with the code is shown by `alembic current` — it should print the same revision as `alembic heads`. The same thing over HTTP, without going into the database by hand: @@ -376,18 +412,20 @@ into the database by hand: curl -s https://.vercel.app/api/v1/warmup ``` -`{"status":"ok","schema":"0016"}` means it all lines up. `"status":"degraded"` together with +`{"status":"ok","schema":"0017"}` means it all lines up. `"status":"degraded"` together with `expected_schema` names both revisions and says which way they diverged: «База отстала от -кода» — the database is behind the code — is an incident, while «База впереди кода» — the -database is ahead — is the normal window between steps 1 and 2, which the deploy closes. +кода» — the database is behind the code — is an incident, except in the minutes a key +rewrite such as `0017` is deliberately applied after the merge (above), while «База впереди +кода» — the database is ahead — is the normal window between steps 1 and 2, which the +deploy closes. `/api/v1/health` deliberately does not show this: it opens no database connection at all, or a ping meant to warm things up would keep waking a sleeping Neon. ### What to apply them with In practice this project's migrations are applied **through the Neon connector** rather than -with the `alembic` command — that is how `0005`–`0014` were applied, and how `0015` and -`0016` are to go on before #140 merges. The Neon project is +with the `alembic` command — that is how `0005`–`0014` were applied, and how `0015`, +`0016` and `0017` are to go on before #140 merges. The Neon project is called `lessons`; its identifier is not kept in the repository — anybody with access sees it in the Neon console anyway, and in a public repository it is just the address of somebody else's database. @@ -531,7 +569,7 @@ stack instead of being buried in the API's log, and so that a migration can be r with `docker compose run --rm migrate`. It needs only `DATABASE_URL`: `get_settings()` is never called there, so `BOT_TOKEN` and `OWNER_IDS` are not its business. `GET /api/v1/warmup` is what confirms the result, and it is the endpoint that can: it says -`{"status": "ok", "schema": "0016"}` when the two agree and names both revisions when they +`{"status": "ok", "schema": "0017"}` when the two agree and names both revisions when they do not. The app on the phone needs to reach the API. The options are a public IP with a forwarded diff --git a/docs/guide.md b/docs/guide.md index 30e16b0b..bf426805 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -321,18 +321,25 @@ assignment and a window opens where every field can be rewritten. Under each fie **what the diary actually holds**: a correction lies over the school's answer rather than erasing it. -Corrected rows are marked with the word «Исправлено». «Сбросить правки» puts everything -back the way the diary has it. +Corrected rows are marked with the word «Исправлено». «Сбросить правки» puts the row the +window is open on back the way the diary has it — for everyone who sees this child, not +only for you. -Three things worth knowing: +Four things worth knowing: * **Nothing changes in the diary itself.** Nothing goes upstream, the teacher does not see - the correction, and it does not affect a mark. It is only what you see. + the correction, and it does not affect a mark. It is only what the app shows. +* **A correction belongs to the child, not to whoever made it.** Everybody who signs in to + the diary in the app with an account that lists this child — the other parent, the pupil + in their own account — sees the same corrections and can change or reset them, and + nothing on screen says who wrote one. Signing out does not take them away. If two + people save the same field at nearly the same moment, the one who saves last wins: + nothing checks whether somebody else changed it first. * **Marks and the turnstile cannot be corrected.** A mark is a statement about what happened; an app that lets you rewrite one makes a forged record that looks genuine. * **If the teacher later fills the field in**, the app says the diary now holds something - else and shows the new value beside yours — but it does not drop your correction by - itself. + else and shows the new value beside the correction — but it does not drop the correction + by itself. The bot does not show corrections: there the diary is seen as it is. diff --git a/docs/legal/privacy.en.md b/docs/legal/privacy.en.md index 74b1fbe5..e9bb8642 100644 --- a/docs/legal/privacy.en.md +++ b/docs/legal/privacy.en.md @@ -64,7 +64,7 @@ When you sign in to a diary, the server keeps: A session opened in the app is linked to neither a Telegram account nor a class, and the bot does not see it. A session opened from the bot is linked to your Telegram account and to the class, and remembers which pupil you chose. -Your corrections to the diary: what you corrected, the new value and what the diary said when you made the correction. They are tied to your login and the pupil's number, not to the session, so they remain after you sign out of the diary. +Corrections to the diary: what was corrected, the new value and what the diary said when the correction was made. They are tied not to a login or a session but to the pupil — to the diary system (for Setevoy Gorod, the region's server) and the pupil's number in it — so they remain after you sign out of the diary and are shared by everyone whose account shows that pupil (see “Who can read your diary”). The server does not record who made a correction, and no login is kept with it. If the operator has turned school search on, you can find your region by your school's name while choosing a diary: the server passes the text you typed to the DaData service. The server does not write that text to its database, but it is part of the request's address, and so it stays in the hosting's request log. @@ -88,7 +88,7 @@ The class's own data — the timetable, substitutions, homework, events, teacher The password does pass through the server in two cases: when you sign in to a diary on the page the bot opens — the browser sends the password to the server, and the server passes it to the diary once — and when an older version of the app signs in, one that does not have this text yet. In both cases the server writes the password down nowhere. -**The diary's contents** — marks, homework, timetable, the list of pupils — are read by the server when you ask and passed on without being kept. The exception is what an entry said when you corrected it. +**The diary's contents** — marks, homework, timetable, the list of pupils — are read by the server when you ask and passed on without being kept. The exception is what an entry said when it was corrected. **There are no analytics, no advertising identifiers and no automatic crash reporting**, in the app or on the server. @@ -105,12 +105,13 @@ If the diary does not accept the session from the server's address, the server d The app does not sign in to Gosuslugi or to My School: it opens the system's page in your browser, and nothing from Gosuslugi reaches either the app or the server. ## Who can read your diary - + - **The diary's system**, after sign-in, sees the server's address using your session, not your phone's. - **The operator** holds the key the sessions are encrypted with, and so can technically open your diary. The encryption protects against whoever gets the database without the key, not against the operator. - **Telegram** keeps in the chat history whatever the bot sent you from the diary — marks, homework, timetable. - **Whoever holds your phone:** the diary access key sits on it unencrypted, and the app opens the diary without a password until you sign out. +- **Everyone whose diary account shows the same pupil** — the other parent, the pupil in their own account, and any other account in which the diary shows that pupil — sees in the app the corrections made for that pupil, whoever made them, and can change or reset them. Beyond the corrections, they see only what the diary shows their own account. ## Keeping the session open @@ -132,7 +133,7 @@ The server does not keep Petersburg Education sessions open: they last as long a - The link for signing in to a diary from the bot: 15 minutes; a personal code for connecting a phone: one day after its 15 minutes have run out. - What you started typing in the bot: 2 days without a change. -**With no time limit** — until somebody deletes them or deletes the class — the server keeps the change log, tasks and “done” ticks, reminder times, requests for rights, invitations by phone number, your membership of the class in the bot, and the class's data. Diary corrections and the class chosen in the bot are not deleted even with the class; corrections are deleted by the “Reset corrections” button. +**With no time limit** — until somebody deletes them or deletes the class — the server keeps the change log, tasks and “done” ticks, reminder times, requests for rights, invitations by phone number, your membership of the class in the bot, and the class's data. Diary corrections and the class chosen in the bot are not deleted even with the class. A correction is deleted by the “Reset corrections” button — for everyone at once, and anybody who sees that pupil can press it. These periods are kept by the server's clock. If the operator has not set that clock up, the records in this list stay past their periods, and Setevoy Gorod sessions are not kept open. @@ -183,7 +184,7 @@ If you have connected to a different server, whoever started it decides where it A diary is information about a child: their marks, homework and timetable. If a pupil under 18 uses Lessons, it should be with the knowledge and consent of their parent or another legal guardian. -The app does not ask anybody's age and checks nothing about who signs in. A parent's diary account may show several children, and everybody who signs in to it sees all of them. +The app does not ask anybody's age and checks nothing about who signs in. A parent's diary account may show several children, and everybody who signs in to it sees all of them. Corrections to the diary are shared for the child: everyone whose account shows that child sees them and can change or reset them — the child too, in their own account. A parent who wants the server to delete their child's data can write to the operator — the “Contact” section says how. @@ -202,11 +203,11 @@ In the app, whatever the server's address, the diary password goes only to the d - Sign out of the diary in the app or in the bot — the server deletes the session. If the phone is offline at that moment, the session is deleted by itself 30 days after it was last used, and until then the server keeps a Setevoy Gorod session open. -- Reset your corrections to the diary. +- Reset a correction to the diary — for everyone who sees that pupil, whoever made it. - Leave a class — this erases the copy on the phone, but not the server's record of the phone. - Turn off the automatic update check. Crash reports stay off until you turn them on yourself. -You cannot remove yourself from the bot or delete your data from the server on your own: there are no commands for that, so write to the operator. The operator cannot delete your Telegram chat history or the data in the diary's system — that is done there. +You cannot remove yourself from the bot or delete your data from the server on your own: there are no commands for that, so write to the operator. The operator cannot tell which corrections to the diary are yours: the server does not record who made each. So a request to delete your corrections is met by deleting that pupil's corrections — including those somebody else made for that pupil — or the particular ones the request names. The operator cannot delete your Telegram chat history or the data in the diary's system — that is done there. ## Changes diff --git a/docs/legal/privacy.ru.md b/docs/legal/privacy.ru.md index 2dab46fd..136048ed 100644 --- a/docs/legal/privacy.ru.md +++ b/docs/legal/privacy.ru.md @@ -22,7 +22,11 @@ not in Russia; the operator holds the key and can read the diary; leaving a class deletes nothing on the server; the phone encrypts nothing itself; an http:// server address carries everything in the clear; the keep-alive runs for up to 30 days after the last - use, not only while somebody is active; and no diary has yet been opened for real. + use, not only while somebody is active; a correction to the diary is the child's rather + than the account's, so every account whose diary lists that pupil reads, changes and + resets it, and no row says who wrote it, so the operator cannot pick out one adult's + corrections: a request to delete "mine" is met for the whole child, or for the particular + corrections it names; and no diary has yet been opened for real. Passages under a comment that starts with FORK describe the upstream deployment. A fork that runs its own server rewrites them; the bracketed names in each comment are the fields @@ -85,7 +89,7 @@ Сессия, открытая в приложении, не связана ни с учётной записью Telegram, ни с классом, и бот её не видит. Сессия, открытая из бота, связана с вашей учётной записью Telegram и с классом, и в ней запоминается выбранный ученик. -Ваши правки дневника: что вы поправили, новое значение и то, что было в дневнике в момент правки. Они привязаны к вашему логину и номеру ученика, а не к сессии, поэтому остаются после выхода из дневника. +Правки дневника: что поправили, новое значение и то, что было в дневнике в момент правки. Они привязаны не к логину и не к сессии, а к ученику — к системе дневника (у «Сетевого города» — к серверу региона) и номеру ученика в ней, — поэтому остаются после выхода из дневника и общие для всех, чья учётная запись показывает этого ученика (см. «Кто может прочитать ваш дневник»). Кто сделал правку, сервер не записывает, и логин вместе с ней не хранится. Если оператор включил поиск школ, при выборе дневника можно найти свой регион по названию школы: сервер передаёт набранный текст сервису DaData. В базу сервер этот текст не записывает, но он входит в адрес запроса и поэтому остаётся в журнале запросов хостинга. @@ -109,7 +113,7 @@ Через сервер пароль всё же проходит в двух случаях: когда вы входите в дневник на странице, которую открывает бот, — браузер отправляет пароль серверу, а сервер один раз передаёт его дневнику, — и когда входят старые версии приложения, в которых этого текста ещё нет. В обоих случаях сервер нигде пароль не записывает. -**Содержимое дневника** — оценки, задания, расписание, список учеников — сервер читает по вашему запросу и передаёт дальше, не сохраняя. Исключение — то, что было в записи, которую вы поправили. +**Содержимое дневника** — оценки, задания, расписание, список учеников — сервер читает по вашему запросу и передаёт дальше, не сохраняя. Исключение — то, что было в записи, когда её поправили. **Аналитики, рекламных идентификаторов и автоматической отправки отчётов о сбоях** нет ни в приложении, ни на сервере. @@ -126,12 +130,13 @@ В Госуслуги и в «Мою школу» приложение не входит: оно открывает страницу системы в вашем браузере, и ничего из Госуслуг не попадает ни в приложение, ни на сервер. ## Кто может прочитать ваш дневник - + - **Система дневника** после входа видит, что вашей сессией пользуется адрес сервера, а не вашего телефона. - **Оператор** держит ключ, которым зашифрованы сессии, и поэтому технически может открыть ваш дневник. Шифрование защищает от того, к кому попадёт база данных без ключа, а не от оператора. - **Telegram** хранит в истории чата то, что бот прислал вам из дневника, — оценки, задания, расписание. - **Тот, у кого в руках ваш телефон:** ключ доступа к дневнику лежит на нём без шифрования, и приложение открывает дневник без пароля, пока вы из него не вышли. +- **Все, чья учётная запись дневника показывает того же ученика**, — второй родитель, сам ученик в своей учётной записи и любая другая, в которой дневник его покажет, — видят в приложении правки, сделанные для этого ученика, кем бы они ни были сделаны, и могут их изменить или сбросить. Помимо правок им видно только то, что дневник показывает их собственной учётной записи. ## Поддержание сеанса @@ -153,7 +158,7 @@ - Ссылка для входа в дневник из бота — 15 минут; личный код для подключения телефона — сутки после того, как истекли его 15 минут. - Незаконченный ввод в боте — 2 дня без изменений. -**Без срока** — пока их не удалят или пока не удалят класс — хранятся журнал изменений, задачи и отметки «сделал», время напоминаний, запросы прав, приглашения по номеру телефона, ваше участие в классе в боте и данные класса. Правки дневника и класс, выбранный в боте, не удаляются и вместе с классом; правки удаляет кнопка «Сбросить правки». +**Без срока** — пока их не удалят или пока не удалят класс — хранятся журнал изменений, задачи и отметки «сделал», время напоминаний, запросы прав, приглашения по номеру телефона, ваше участие в классе в боте и данные класса. Правки дневника и класс, выбранный в боте, не удаляются и вместе с классом. Правку удаляет кнопка «Сбросить правки» — у всех сразу, и нажать её может каждый, кто видит этого ученика. Эти сроки выдерживают часы сервера. Если оператор их не настроил, записи из этого списка остаются и после срока, а сессии «Сетевого города» не поддерживаются. @@ -204,7 +209,7 @@ Дневник — это сведения о ребёнке: его оценки, задания и расписание. Если «Дневником» пользуется ученик младше 18 лет, это должно происходить с ведома и согласия его родителя или другого законного представителя. -Приложение не спрашивает возраст и ничего не проверяет о том, кто входит. Родительская учётная запись дневника может показывать нескольких детей, и всех их видит каждый, кто в неё вошёл. +Приложение не спрашивает возраст и ничего не проверяет о том, кто входит. Родительская учётная запись дневника может показывать нескольких детей, и всех их видит каждый, кто в неё вошёл. Правки дневника для ребёнка общие: их видит и может изменить или сбросить каждый, чья учётная запись показывает этого ребёнка, — в том числе сам ребёнок в своей. Родитель, который хочет, чтобы сервер удалил данные его ребёнка, может написать оператору — способ указан в разделе «Контакты». @@ -223,11 +228,11 @@ - Выйти из дневника в приложении или в боте — сервер удалит сессию. Если телефон в этот момент не в сети, сессия удалится сама через 30 дней после последнего пользования, а сессию «Сетевого города» сервер до тех пор продолжит поддерживать. -- Сбросить свои правки дневника. +- Сбросить правку дневника — у всех, кто видит этого ученика, кто бы её ни сделал. - Выйти из класса — это сотрёт копию на телефоне, но не запись о телефоне на сервере. - Выключить автоматическую проверку обновлений. Отчёты о сбоях выключены, пока вы сами их не включите. -Удалить себя из бота или свои данные с сервера самостоятельно нельзя: таких команд нет, для этого напишите оператору. Историю чата в Telegram и данные в системе дневника оператор удалить не может — это делается там. +Удалить себя из бота или свои данные с сервера самостоятельно нельзя: таких команд нет, для этого напишите оператору. Какие правки дневника сделали именно вы, оператор определить не может: кто сделал какую правку, сервер не записывает. Поэтому просьбу удалить ваши правки он выполнит, удалив правки этого ученика — вместе с теми, что сделал для него кто-то другой, — или те, что названы в просьбе. Историю чата в Telegram и данные в системе дневника оператор удалить не может — это делается там. ## Изменения diff --git a/docs/legal/terms.en.md b/docs/legal/terms.en.md index 619e6daf..bb3b4b9a 100644 --- a/docs/legal/terms.en.md +++ b/docs/legal/terms.en.md @@ -40,7 +40,7 @@ The app does not ask your age and does not check who signs in to a diary, so thi - It shows the class timetable that people with rights in that class keep in the Telegram bot, once you have entered the class code or a personal code from the bot. - It shows your electronic diary — lessons, homework, marks — if you have signed in to it. The server reads the diary from the diary's system and passes it on to the app. -- It lets you correct what came from the diary: the homework text, the room, the teacher, the lesson's topic. A correction is kept on the server next to the diary and **is never sent to the diary's system** — the school register does not change because of it. Marks and attendance cannot be corrected. +- It lets you correct what came from the diary: the homework text, the room, the teacher, the lesson's topic. A correction is kept on the server next to the diary and **is never sent to the diary's system** — the school register does not change because of it. Corrections are shared per pupil: everyone whose diary account shows that pupil — the other parent, for example — sees them in the app and can change or reset them. Marks and attendance cannot be corrected. ## This is not the official record @@ -97,7 +97,7 @@ The operator is liable for the consequences of using Lessons only to the extent ## How to stop using it -- **Sign out of the diary** — in the app or in the bot. The server deletes the session and, for Setevoy Gorod, also tells the diary you have signed out; your corrections to the diary stay on the server until you reset them. +- **Sign out of the diary** — in the app or in the bot. The server deletes the session and, for Setevoy Gorod, also tells the diary you have signed out; the corrections to the diary stay on the server until somebody who sees that pupil resets them — you, or the other parent, for example. - **Leave a class** in the app — this erases only what is kept on the phone. The server deletes its record of the phone by itself 180 days after the phone's last request; an admin can disconnect the phone sooner, but even then the record is kept until that date. - **Uninstall the app** — this erases everything it keeps on the phone; on the server, data is kept for the periods the privacy policy gives. diff --git a/docs/legal/terms.ru.md b/docs/legal/terms.ru.md index e8ef477a..06026db4 100644 --- a/docs/legal/terms.ru.md +++ b/docs/legal/terms.ru.md @@ -57,7 +57,7 @@ - Показывает расписание класса, которое в Telegram-боте ведут люди с правами в этом классе, — после того как вы ввели код класса или личный код из бота. - Показывает ваш электронный дневник — уроки, задания, оценки, — если вы в него вошли. Дневник читает сервер у системы дневника и передаёт приложению. -- Даёт поправить то, что пришло из дневника: текст задания, кабинет, учителя, тему урока. Правка хранится на сервере рядом с дневником и **в систему дневника не отправляется** — школьный журнал от неё не меняется. Оценки и посещаемость поправить нельзя. +- Даёт поправить то, что пришло из дневника: текст задания, кабинет, учителя, тему урока. Правка хранится на сервере рядом с дневником и **в систему дневника не отправляется** — школьный журнал от неё не меняется. Правки общие для ученика: их видит в приложении и может изменить или сбросить каждый, чья учётная запись дневника показывает этого ученика, — например, второй родитель. Оценки и посещаемость поправить нельзя. ## Это не официальный журнал @@ -114,7 +114,7 @@ ## Как прекратить пользоваться -- **Выйти из дневника** — в приложении или в боте. Сервер удалит сессию, а «Сетевому городу» ещё и сообщит о выходе; ваши правки дневника останутся на сервере, пока вы их не сбросите. +- **Выйти из дневника** — в приложении или в боте. Сервер удалит сессию, а «Сетевому городу» ещё и сообщит о выходе; правки дневника останутся на сервере, пока их не сбросит кто-то из тех, кто видит этого ученика, — вы или, например, второй родитель. - **Выйти из класса** в приложении — это сотрёт только то, что хранится на телефоне. Запись о телефоне сервер удаляет сам через 180 дней после его последнего обращения; администратор может отключить телефон раньше, но запись и тогда хранится до этого срока. - **Удалить приложение** — это сотрёт всё, что оно хранит на телефоне; на сервере данные хранятся в сроки, указанные в политике конфиденциальности. diff --git a/server/app/api/diary.py b/server/app/api/diary.py index 1bb27393..c372ccf0 100644 --- a/server/app/api/diary.py +++ b/server/app/api/diary.py @@ -47,6 +47,7 @@ UnexpectedResponse, UpstreamUnavailable, ) +from app.providers.diary.models import Student from app.providers.diary.registry import NETSCHOOL, PETERSBURG from app.providers.petersburg import ( today as diary_today, @@ -651,22 +652,41 @@ async def _student(svc: service.DiaryService, student_id: int): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Unknown student") +async def _child(svc: service.DiaryService, student_id: int) -> tuple[Student, str | None]: + """The student, or 404, and the scope its corrections are filed under. + + The one door every correction read and write goes through, so that the + 404 comes before any row is touched and the scope comes from the session's + diary — never from the login it was registered under (#165). ``None`` is a + child that can have no corrections (`DiaryService.scope_of`): the reads lay + none over it, the list is empty, a reset has nothing to take off, and a + write is refused. + """ + student = await _student(svc, student_id) + return student, await _guard(svc.scope_of(student)) + + +async def _corrections( + session: AsyncSession, scope: str | None, student_id: int +) -> dict[str, dict[str, tuple[str, str | None]]]: + if scope is None: + return {} + return await service.load_corrections(session, scope, student_id) + + @router.get("/students/{student_id}/schedule", response_model=list[DiaryLessonOut]) async def schedule( student_id: int, date_from: Date | None = Query(default=None, alias="from"), date_to: Date | None = Query(default=None, alias="to"), svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> list[DiaryLessonOut]: - student = await _student(svc, student_id) + student, scope = await _child(svc, student_id) start, end = _range(date_from, date_to, svc.today()) lessons = await _guard(svc.schedule(student.education_id, start, end)) - corrections = await service.load_corrections( - session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region - ) + corrections = await _corrections(session, scope, student_id) return [ DiaryLessonOut.of(overlaid) for overlaid in overrides.overlay_lessons(lessons, corrections) @@ -679,7 +699,6 @@ async def homework( date_from: Date | None = Query(default=None, alias="from"), date_to: Date | None = Query(default=None, alias="to"), svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> list[DiaryHomeworkOut]: @@ -688,12 +707,10 @@ async def homework( Upstream it is a field on a lesson; the client should not have to know that, so the provider pulls it out and this endpoint exists. """ - student = await _student(svc, student_id) + student, scope = await _child(svc, student_id) start, end = _range(date_from, date_to, svc.today()) items = await _guard(svc.homework(student.education_id, start, end)) - corrections = await service.load_corrections( - session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region - ) + corrections = await _corrections(session, scope, student_id) return [ DiaryHomeworkOut.of(overlaid) for overlaid in overrides.overlay_homework(items, corrections) @@ -777,25 +794,34 @@ async def attendance( # ``services/diary_overrides`` for why an app that let a family rewrite a grade # would be producing a false record that looks official. # -# Scoped by the upstream login rather than by the session, so signing out and -# back in finds the corrections where they were left. The student is checked -# against the account on every call for the same reason the read endpoints do -# it: an id from another family is otherwise a way to write into their diary. +# Filed under the child — the diary's server and the pupil's id on it +# (`services/diary.child_scope`) — rather than under the session or the login, +# so signing out and back in finds them where they were left, and everyone +# whose own diary lists the child reads and writes the same set: both parents, +# the pupil's own account if it lists itself, and any other account the diary +# answers with the child, whatever its role. The login plays no part; it +# is whatever the phone typed, and a login copied from another family reaches +# nothing (#165). What does decide is `_child`, before every read and write: +# the id is looked up among the pupils this session's own diary lists, on +# every call, and anything else is a 404 — an id from another family is +# otherwise a way to write into their diary. A child the diary lists by an id +# outside its own numbering gets no corrections at all (`scope_of`): with the +# login gone from the key, that number alone would decide whose they were. @router.get("/students/{student_id}/overrides", response_model=list[DiaryOverrideOut]) async def list_overrides( student_id: int, svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> list[DiaryOverrideOut]: - """Every correction this account has made for this child.""" - await _student(svc, student_id) - found = await service.list_overrides( - session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region - ) + """Every correction anybody who sees this child has made for them — + this account's and, say, the other parent's alike; no row says whose.""" + _, scope = await _child(svc, student_id) + if scope is None: + return [] + found = await service.list_overrides(session, scope, student_id) return [DiaryOverrideOut.of(item) for item in found] @@ -804,7 +830,6 @@ async def put_override( student_id: int, payload: DiaryOverrideIn, svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> DiaryOverrideOut: @@ -816,8 +841,20 @@ async def put_override( match would sit in the table looking like a correction somebody made, with no way to reset it, because the button that resets it only appears next to the value it changed. + + Replaces whatever was there, whoever wrote it: the last writer wins, + ``original`` included. + + A child that can have no corrections is a ``422``, the status the app + already reads on this route as «Это поле нельзя исправить» — true of every + field of that child. """ - await _student(svc, student_id) + _, scope = await _child(svc, student_id) + if scope is None: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Для этого ученика правки недоступны", + ) try: overrides.check(payload.target, payload.field) except overrides.UnknownTarget as failure: @@ -840,14 +877,12 @@ async def put_override( stored = await service.put_override( session, - login=row.login, + scope=scope, student_id=student_id, target=payload.target, field=payload.field, value=payload.value, original=payload.original, - provider=row.provider or PETERSBURG, - region=row.region, ) return DiaryOverrideOut.of(stored) @@ -860,7 +895,6 @@ async def reset_override( student_id: int, payload: DiaryResetIn, svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> None: @@ -873,12 +907,11 @@ async def reset_override( Idempotent, and answers 204 whether or not there was a row: "there is no correction here" is the state the caller asked for, and a 404 would make the client decide whether to show an error for having got what it wanted. + It takes the correction off for everyone who sees the child. """ - await _student(svc, student_id) - await service.drop_override( - session, row.login, student_id, payload.target, payload.field, - provider=row.provider or PETERSBURG, region=row.region, - ) + _, scope = await _child(svc, student_id) + if scope is not None: + await service.drop_override(session, scope, student_id, payload.target, payload.field) @router.delete( @@ -888,12 +921,12 @@ async def reset_override( async def reset_all_overrides( student_id: int, svc: service.DiaryService = Depends(_service), - row: DiarySession = Depends(current_diary), *, session: FromDishka[AsyncSession], ) -> None: - """Resets every correction for this child. The diary answers for itself again.""" - await _student(svc, student_id) - await service.drop_overrides( - session, row.login, student_id, provider=row.provider or PETERSBURG, region=row.region - ) + """Resets every correction for this child, whoever wrote it, for everyone + who sees the child — and nothing of any other child's. The diary answers + for itself again.""" + _, scope = await _child(svc, student_id) + if scope is not None: + await service.drop_overrides(session, scope, student_id) diff --git a/server/app/db.py b/server/app/db.py index e07ea7c8..1f44174c 100644 --- a/server/app/db.py +++ b/server/app/db.py @@ -134,7 +134,7 @@ def rows_affected(result: Any) -> int: #: inside a request. A constant that has to be kept in step by hand would rot, #: so ``tests/test_schema_version.py`` pins it to the real head and fails the #: build if a new revision lands without updating it. -EXPECTED_REVISION = "0016" +EXPECTED_REVISION = "0017" async def current_revision(session: AsyncSession) -> str | None: diff --git a/server/app/models.py b/server/app/models.py index a2df0da1..1f1b829e 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -819,9 +819,10 @@ class DiarySession(Base): # that is encrypted instead. Refreshed in place (and re-sealed) whenever the # upstream hands back a new one, which it does on most calls. upstream_token: Mapped[str] = mapped_column(Text, nullable=False) - # Who signed in. Shown on the "you are signed in as" line, and also the key - # a family's corrections hang on (`services/diary.py:owner_key`), so the - # same login re-used later lays its overrides over the same lessons. + # Who signed in, as typed: shown on the "you are signed in as" line and + # nothing more. A phone's registration names it and nothing upstream + # vouches for it, so it decides nothing — a family's corrections are filed + # under the child (`services/diary.py:child_scope`), not under this (#165). login: Mapped[str] = mapped_column(String(200), nullable=False) # The Telegram account this session belongs to. Set when the session was # opened from the bot's sign-in ticket (`api/diary_web.py`); NULL for a @@ -952,17 +953,23 @@ def is_used(self) -> bool: class DiaryOverride(Base): """One correction a family laid over something the diary sent down. - Nothing here changes dnevnik2. The upstream is read-only to this project + Nothing here changes the diary. The upstream is read-only to this project and will stay that way; what this table holds is a value put **over** the one that came down, on the way out, so that «сбросить» is a delete rather than a second guess at what was there before. A row is the correction; its absence is the upstream's own answer. - **Keyed by the account, not by the session.** Signing out and back in makes - a new :class:`DiarySession` row, and a correction that went with it would - make the reset button meaningless — the correction would already be gone, - silently, the first time the upstream session expired. ``login`` is what - survives, and it is the same string the session row already stores. + **Keyed by the child, not by the session and not by the login.** Signing + out and back in makes a new :class:`DiarySession` row, and a correction + that went with it would make the reset button meaningless — the correction + would already be gone, silently, the first time the upstream session + expired. And the login is whatever the phone typed, which nothing upstream + vouches for, so keyed on it one family could name another's (#165). The + key is the diary's server (``login``, holding a scope) and the pupil's id + on it (``student_id``), so everyone whose own diary lists the child — + both parents, the pupil's own account — reads and writes one set: one row + per field, the last writer's, with no column saying who that was. The + routes decide who reaches a child, by asking the session's own diary. ``target`` names the thing being corrected **semantically** rather than by position: a homework item by its upstream id when it has one and by (day, @@ -988,18 +995,23 @@ class DiaryOverride(Base): ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - #: The upstream account, **case-folded** — ``services/diary.py:owner_key`` - #: is the only thing that writes or queries this column, and it folds. + #: **Not a login any more**, whatever the name says: the diary a child's + #: corrections belong to, as ``services/diary.py:child_scope`` spells it — + #: ``CHILD:petersburg``, or ``CHILD:netschool:`` and the regional server's + #: host, and nothing else: a child listed outside its diary's own + #: numbering gets no row at all (``DiaryService.scope_of``). So one child's + #: rows are exactly ``login = AND student_id = `` — what an + #: operator deleting them on request writes. The name stayed because + #: renaming a column is a migration and the key needed none; revision + #: ``0017`` rewrote the rows that held a login. #: - #: Unlike ``DiarySession.login``, which is kept exactly as it was typed - #: because it is what «вы вошли как» prints. This one is a key, and the - #: upstream treats ``Ivan@mail.ru`` and ``ivan@mail.ru`` as one account — - #: so keeping the casing here would file one family's corrections under two - #: owners, and the set that went missing would have no reset button left, - #: there being nothing to reset. The consequence to remember: this column - #: **must not** be joined against ``diary_sessions.login``. + #: ``child_scope`` is the only thing that writes or queries it. It **must + #: not** be compared with ``diary_sessions.login``, or with any login: the + #: upper-case prefix is there precisely so that no casefolded login — the + #: form this column held before — can ever equal a scope. login: Mapped[str] = mapped_column(String(200), nullable=False) - #: Which child, for an account that carries several. + #: The pupil's id on that diary (``Student.id``, not the education id the + #: bot keeps on a session) — the other half of the key: which child. student_id: Mapped[int] = mapped_column(BigInteger, nullable=False) #: See the class docstring: semantic, never positional. target: Mapped[str] = mapped_column(String(300), nullable=False) diff --git a/server/app/providers/diary/models.py b/server/app/providers/diary/models.py index 14eb3b16..818a5aaf 100644 --- a/server/app/providers/diary/models.py +++ b/server/app/providers/diary/models.py @@ -51,6 +51,13 @@ class Student(BaseModel): #: client passes them straight back; never parsed by the phone. education_id: int group_id: int | None = None + #: Which numbering ``id`` is in, when a provider can fill it from more than + #: one; ``None`` is the provider's own pupil id. Never sent to a client + #: (`DiaryStudentOut` names its fields). A child with any other numbering + #: gets no corrections (`services/diary.DiaryService.scope_of`): the key + #: they are filed under is the diary and the number, so a number nothing + #: says is one person's would let two families' children meet under it. + id_space: str | None = None @property def full_name(self) -> str: diff --git a/server/app/providers/netschool/mapper.py b/server/app/providers/netschool/mapper.py index 78954064..a2022076 100644 --- a/server/app/providers/netschool/mapper.py +++ b/server/app/providers/netschool/mapper.py @@ -69,6 +69,20 @@ def _parse_time(raw: Any) -> Time | None: return None +def _json_int(value: Any) -> int | None: + """A JSON integer, or ``None`` — never a bool. + + `bool` is an `int` in Python, so a JSON ``true`` passes + ``isinstance(value, int)`` as 1. A pupil's id is half of the key the + child's corrections are filed under (`services/diary.child_scope`), so a + ``true`` read as pupil 1 would lay pupil 1's corrections over another + child. Petersburg's `number` refuses a bool too, and the client's + `_json_int` is the same rule — not imported, because the client brings the + HTTP module with it. + """ + return value if isinstance(value, int) and not isinstance(value, bool) else None + + def to_students(init: dict[str, Any], school: str | None) -> list[Student]: """``student/diary/init`` → the pupils this account may see. @@ -85,8 +99,8 @@ def to_students(init: dict[str, Any], school: str | None) -> list[Student]: for row in raw: if not isinstance(row, dict): continue - sid = row.get("studentId") - if not isinstance(sid, int): + sid = _json_int(row.get("studentId")) + if sid is None: continue nick = _text(row.get("nickName")) or "" students.append( @@ -97,7 +111,7 @@ def to_students(init: dict[str, Any], school: str | None) -> list[Student]: school=school, class_name=_text(row.get("className")), education_id=sid, - group_id=row.get("classId") if isinstance(row.get("classId"), int) else None, + group_id=_json_int(row.get("classId")), ) ) if raw and not students: diff --git a/server/app/providers/petersburg/mapper.py b/server/app/providers/petersburg/mapper.py index 870eadb5..ea983f5b 100644 --- a/server/app/providers/petersburg/mapper.py +++ b/server/app/providers/petersburg/mapper.py @@ -48,6 +48,10 @@ LATE_MARK = "О" REMARK_MARK = "!" +#: `Student.id_space` of a child found by a plain ``id`` rather than by +#: ``identity.id`` — see `to_students`. +PLAIN_ID = "plain-id" + _DATE_FORMATS = ("%d.%m.%Y", "%Y-%m-%d", "%d.%m.%y") _TIME_FORMATS = ("%H:%M:%S", "%H:%M") @@ -274,7 +278,21 @@ def to_students(items: list[dict[str, Any]]) -> list[Student]: if education is None or education_id is None: continue - student_id = identity_id(item) + # The person's `identity.id` is what every related-child-list item the + # third-party clients document carries (none of it from a live diary + # here), and it is taken to be city-wide — that two parents' accounts + # name one child by it is assumed, not observed (see + # `services/diary.child_scope`). A plain `id` is `identity_id`'s + # fallback for endpoints that send one instead, and nothing says what + # it numbers — so a child found by it is marked, and gets no + # corrections at all (`services/diary.DiaryService.scope_of`), rather + # than share them with whichever child anywhere has the same number. + identity = item.get("identity") + student_id = number(identity, "id") if isinstance(identity, dict) else None + id_space = None + if student_id is None: + student_id = number(item, "id") + id_space = PLAIN_ID if student_id is None: continue @@ -288,6 +306,7 @@ def to_students(items: list[dict[str, Any]]) -> list[Student]: class_name=text(education, "group_name", "class_name"), education_id=education_id, group_id=number(education, "group_id"), + id_space=id_space, ) ) note_if_nothing_read("student", items, students) diff --git a/server/app/schemas.py b/server/app/schemas.py index cf6a809f..dfee7f07 100644 --- a/server/app/schemas.py +++ b/server/app/schemas.py @@ -634,9 +634,11 @@ def _clean_login_value(value: str) -> str: """A login as the upstream will see it: printable, trimmed, three or more. Shared by the password sign-in and the registration of a phone's session, - because both write it to the same column and key the same corrections on - it — two cleanings of one value would file one family's corrections under - two names. + because both write it to the same column and «Вход выполнен» prints it + from there — and the phone cleans it character for character the same way + (`DiaryLogin.clean`), so a login pasted with an invisible character is not + a wrong password on one side only. It keys nothing: corrections are filed + under the child (`services/diary.child_scope`). """ cleaned = _strip_control_chars(value).strip() if len(cleaned) < 3: @@ -757,8 +759,9 @@ class _SessionIn(BaseModel): model_config = ConfigDict(extra="forbid") #: What the person typed into the phone's own form. Nothing upstream - #: vouches for it; it names the session and keys the corrections, so the - #: phone sends the same string on every sign-in. + #: vouches for it, so it only names the session: a login copied from + #: another family reaches nothing of theirs (#165), because what a session + #: reaches is what its own diary lists. login: str = Field(min_length=3, max_length=200) @field_validator("login") @@ -1034,8 +1037,12 @@ class DiaryOverrideIn(BaseModel): #: question it exists to answer is "has the diary changed since the person #: decided to replace this", and the answer is about what *they* saw, not #: about what the upstream happened to say in the second this request - #: landed. It is also nobody else's data — a family's own correction of - #: their own diary — so there is no boundary here to defend. + #: landed. The row is shared by everyone whose diary lists the child, so + #: the last writer's ``original`` is what everybody's ``changed_upstream`` + #: is measured against — and still there is no boundary here to defend: + #: whoever can write it sees the child in their own diary and could write + #: the value itself, and a wrong ``original`` only raises or lowers a flag + #: that is drawn beside the diary's own current answer. original: str | None = Field(default=None, max_length=4000) diff --git a/server/app/services/diary.py b/server/app/services/diary.py index 6b4b8193..dcde3d20 100644 --- a/server/app/services/diary.py +++ b/server/app/services/diary.py @@ -21,11 +21,11 @@ from __future__ import annotations -import hashlib import logging from dataclasses import dataclass from datetime import UTC, datetime from datetime import date as Date +from urllib.parse import urlsplit from sqlalchemy import ColumnElement, and_, func, select from sqlalchemy import delete as sa_delete @@ -48,7 +48,7 @@ Subject, Teacher, ) -from app.providers.diary.registry import PETERSBURG, Binding, provider_for +from app.providers.diary.registry import NETSCHOOL, PETERSBURG, Binding, provider_for from app.providers.diary.registry import binding as class_binding from app.security import hash_token, new_token @@ -194,8 +194,9 @@ async def adopt( hands back (possibly rotated) is what is sealed. ``login`` is what the person typed on the phone. Nothing upstream vouches - for it; it names the row and keys the corrections (:func:`owner_key`), - which every route reaches only through a pupil this session can see. + for it, so it names the row — what «Вход выполнен» prints — and nothing + else: corrections are filed under the child (:func:`child_scope`) and + reached only through a pupil this session's own diary lists. The row carries no Telegram account and no class: a phone's session is not the bot's, and linking the two is deliberately left for later. @@ -310,43 +311,99 @@ async def find_session(session: AsyncSession, token: str) -> DiarySession | None # # The rules for applying them live in ``services/diary_overrides.py``, which is # free of SQLAlchemy so that they can be tested without a database. This is the -# other half: getting the rows in and out. They are keyed by the upstream login -# rather than by the session, because a session ends every few days and a -# correction must not. - - -def owner_key(login: str, provider: str = PETERSBURG, region: str | None = None) -> str: - """The form of a login that corrections are filed under. - - Case-folded, because an upstream does not care: a family that signed in as - ``Ivan@mail.ru`` and later types ``ivan@mail.ru`` lands in the same account - there, and must land on the same corrections here. Keyed on the raw string, - every one of them would vanish the first time somebody's keyboard - capitalised the first letter — with no reset button, because there would be - nothing left to reset. - - The row's own ``login`` stays as it was typed: it is what «вы вошли как» - prints, and that should say what the person wrote. - - **Petersburg's key is the bare case-folded login, unchanged**, so every - correction filed before there was a second provider still matches. For any - other provider a login is unique only on its own regional server, so the - key folds in the provider and region — through a hash, because - ``login:region:`` prefixes would push a 200-character login past the - ``DiaryOverride.login`` column, and a family whose corrections silently - stopped saving would have no way to see why. The hash is 71 characters, so - it always fits and never collides. +# other half: getting the rows in and out. They are filed under the child — the +# diary, and the pupil's id on it — rather than under the session or the login: +# a session ends every few days and a correction must not, and the login is +# whatever the phone typed, which nothing upstream vouches for (#165). So they +# are shared by everyone whose own diary lists the child. Which children a +# session reaches is decided in the routes, by `_student`: the session's own +# diary is asked for its pupils on every call, and an id it does not list is a +# 404 before any row here is read or written. + +#: What every scope starts with — upper case on purpose; see `child_scope`. +SCOPE_PREFIX = "CHILD:" + + +class UnknownDiaryServer(ValueError): + """A session whose diary this code cannot name a server for: a provider no + implementation answers, or a «Сетевой город» region the allow-list does not + hold. Refused rather than given a fallback scope, which would file one + server's pupils beside another's.""" + + +def child_scope(provider: str | None, region: str | None) -> str: + """The diary a child's corrections are filed under; ``student_id`` is the + child. Stored in ``DiaryOverride.login``, a column named for what it held + before. + + Not the session: a diary session ends every few days, and a correction + that went with it would vanish before anybody pressed «сбросить», with + nothing left to reset. Not the login either: it is what the phone typed, + and nothing upstream vouches for it. + + **Petersburg** is one city-wide server, and a ``NULL`` provider is a row + from before there was a second one: ``CHILD:petersburg``. + + **«Сетевой город»** is taken to number its pupils per regional server (see + below), so the scope names the server — ``CHILD:netschool:`` and the host + of the region's origin, resolved through the allow-list exactly as the + session's own calls are. The host, not the region key: if a region's + origin ever moves, the corrections stop matching (lost) rather than attach + to whichever child carries the same number on the new server (leaked), and + two regions on one server rightly share its numbering. A region the + allow-list does not hold raises :class:`UnknownDiaryServer`, never a guess. + + Those two are the only shapes. A child a diary lists by an id outside the + provider's own numbering (``Student.id_space``) gets no scope at all — + :meth:`DiaryService.scope_of` answers ``None`` and the routes offer it no + corrections — because the number would then be the whole key, and nothing + says that numbering names one person across families. + + Assumed and never observed: that a «Сетевой город» pupil id is unique per + server rather than per school, and that two parents' accounts see one + child under one id, in either diary. Were it per school, the school would + have to come from the diary's own answer — never from the ``school_id`` a + phone sends at registration, which nothing compares with the diary. + + **Upper case is the point of the prefix.** A key written before this + function existed is ``login.strip().casefold()`` for Petersburg, or + ``netschool:`` and 64 lower-case hex digits — casefolded or lower-case + either way — so no scope can ever equal one, whatever login somebody types: + «CHILD:petersburg» folds to ``child:petersburg``. Code reverted to before + this change therefore cannot read a per-child row, or write into one, under + any login; revision ``0017`` rewrites the old rows into scopes. What such + code writes while it runs is filed under logins this code never reads, so + a revert is not lossless — ``0017``'s docstring says how to fold them in. """ - folded = login.strip().casefold() + provider = provider or PETERSBURG if provider == PETERSBURG: - return folded - digest = hashlib.sha256(f"{region}\0{folded}".encode()).hexdigest() - return f"{provider}:{digest}" + scope = f"{SCOPE_PREFIX}{PETERSBURG}" + elif provider == NETSCHOOL: + from app.providers.netschool import regions + + known = regions.get(region) + if known is None: + raise UnknownDiaryServer(f"no «Сетевой город» server for region {region!r}") + scope = f"{SCOPE_PREFIX}{NETSCHOOL}:{urlsplit(known.origin).netloc.lower()}" + else: + raise UnknownDiaryServer(f"unknown diary provider {provider!r}") + return scope + + +def _of_child(scope: str, student_id: int) -> tuple[ColumnElement[bool], ColumnElement[bool]]: + """The two halves of the key, as the WHERE clause every query here uses. + + Refuses anything that is not a scope, because a login passed where a scope + belongs is #165 again — a string the phone chose deciding whose + corrections are read — and it would type-check perfectly well. + """ + if not scope.startswith(SCOPE_PREFIX): + raise ValueError("corrections are filed under child_scope(), not under a login") + return DiaryOverride.login == scope, DiaryOverride.student_id == student_id async def load_corrections( - session: AsyncSession, login: str, student_id: int, - *, provider: str = PETERSBURG, region: str | None = None + session: AsyncSession, scope: str, student_id: int ) -> dict[str, dict[str, tuple[str, str | None]]]: """Every correction for one child, shaped the way the overlay wants it. @@ -354,12 +411,7 @@ async def load_corrections( and asking the database to reason about that would make the key format something the schema knows. A family has a handful of these. """ - rows = await session.scalars( - select(DiaryOverride).where( - DiaryOverride.login == owner_key(login, provider, region), - DiaryOverride.student_id == student_id, - ) - ) + rows = await session.scalars(select(DiaryOverride).where(*_of_child(scope, student_id))) corrections: dict[str, dict[str, tuple[str, str | None]]] = {} for row in rows: corrections.setdefault(row.target, {})[row.field] = (row.value, row.original) @@ -367,16 +419,12 @@ async def load_corrections( async def list_overrides( - session: AsyncSession, login: str, student_id: int, - *, provider: str = PETERSBURG, region: str | None = None + session: AsyncSession, scope: str, student_id: int ) -> list[DiaryOverride]: """The raw rows, for the screen that lists and resets them.""" rows = await session.scalars( select(DiaryOverride) - .where( - DiaryOverride.login == owner_key(login, provider, region), - DiaryOverride.student_id == student_id, - ) + .where(*_of_child(scope, student_id)) .order_by(DiaryOverride.target, DiaryOverride.field) ) return list(rows) @@ -384,28 +432,27 @@ async def list_overrides( async def put_override( session: AsyncSession, - login: str, + scope: str, student_id: int, target: str, field: str, value: str, original: str | None, - *, provider: str = PETERSBURG, region: str | None = None ) -> DiaryOverride: """Writes a correction, replacing the one that was there. Upsert rather than insert: correcting the same field twice is the ordinary case — a person fixes a typo in their own fix — and a second row would make - the unique constraint the thing that reports it. + the unique constraint the thing that reports it. The last writer wins, + ``original`` included, whoever wrote the row before: there is one + correction per field per child, and no column says whose it was. """ - row = await session.scalar( - select(DiaryOverride).where( - DiaryOverride.login == owner_key(login, provider, region), - DiaryOverride.student_id == student_id, - DiaryOverride.target == target, - DiaryOverride.field == field, - ) + one = ( + *_of_child(scope, student_id), + DiaryOverride.target == target, + DiaryOverride.field == field, ) + row = await session.scalar(select(DiaryOverride).where(*one)) if row is not None: row.value = value row.original = original @@ -414,7 +461,7 @@ async def put_override( return row row = DiaryOverride( - login=owner_key(login, provider, region), + login=scope, student_id=student_id, target=target, field=field, @@ -425,21 +472,13 @@ async def put_override( try: await session.commit() except IntegrityError: - # Select-then-insert has a gap, and two devices of one family — or one - # device double-tapping through a retry — fall into it. The unique - # constraint catches it, which is the constraint doing its job; what it - # must not do is become a 500 on the way out, because from the person's - # side both taps said the same thing and the answer to both is the row - # that is now there. + # Select-then-insert has a gap, and two adults who both see the child — + # or one device double-tapping through a retry — fall into it. The + # unique constraint catches it, which is the constraint doing its job; + # what it must not do is become a 500 on the way out: the answer to + # both writes is the row that is now there, carrying the later value. await session.rollback() - row = await session.scalar( - select(DiaryOverride).where( - DiaryOverride.login == owner_key(login, provider, region), - DiaryOverride.student_id == student_id, - DiaryOverride.target == target, - DiaryOverride.field == field, - ) - ) + row = await session.scalar(select(DiaryOverride).where(*one)) if row is None: raise row.value = value @@ -450,14 +489,12 @@ async def put_override( async def drop_override( - session: AsyncSession, login: str, student_id: int, target: str, field: str, - *, provider: str = PETERSBURG, region: str | None = None + session: AsyncSession, scope: str, student_id: int, target: str, field: str ) -> bool: """Resets one field. @return whether there was anything to reset.""" row = await session.scalar( select(DiaryOverride).where( - DiaryOverride.login == owner_key(login, provider, region), - DiaryOverride.student_id == student_id, + *_of_child(scope, student_id), DiaryOverride.target == target, DiaryOverride.field == field, ) @@ -469,12 +506,14 @@ async def drop_override( return True -async def drop_overrides( - session: AsyncSession, login: str, student_id: int, - *, provider: str = PETERSBURG, region: str | None = None -) -> int: - """Resets everything for one child. @return how many were dropped.""" - rows = await list_overrides(session, login, student_id, provider=provider, region=region) +async def drop_overrides(session: AsyncSession, scope: str, student_id: int) -> int: + """Resets everything for one child, for everyone who sees that child — the + corrections are the child's, not the account's — and never beyond it: the + rows go through `list_overrides`, whose WHERE carries ``student_id``. + + @return how many were dropped. + """ + rows = await list_overrides(session, scope, student_id) for row in rows: await session.delete(row) if rows: @@ -626,6 +665,36 @@ def today(self) -> Date: Petersburg, the region's zone for «Сетевой город».""" return self.connection.today() + async def scope_of(self, student: Student) -> str | None: + """The scope ``student``'s corrections are filed under, from this + session's diary — its provider and region, never its login — or + ``None`` when this child can have no corrections at all. + + ``None`` is a child the diary listed by an id outside the provider's + own numbering (``Student.id_space``: Petersburg's plain ``id``, where + ``identity.id`` was missing). With the login out of the key, the + number would be all that tells one family's child from another's, and + nothing — no answer seen, no client read — says that numbering names a + person across accounts rather than, say, a relation within one. Two + families each listing a plain 7 would share, overwrite and reset one + set. So such a child fails closed: its diary is shown as it came, and a + correction is refused. No live answer has ever taken this path. + + Asked only of a pupil this session's own diary has just listed. A row + whose region names no server this code knows is treated the way an + unreadable credential is: expired, and :class:`SessionExpired` for the + route to turn into «войдите заново», because a session this server + cannot place is not one to keep reading, and a fallback scope would + file its pupils beside another server's. + """ + try: + scope = child_scope(self.row.provider, self.row.region) + except UnknownDiaryServer: + log.warning("diary session %s names no known server", self.row.id) + await self._expire() + raise SessionExpired from None + return None if student.id_space is not None else scope + # ---- plumbing ----------------------------------------------------- async def _call(self, awaitable): @@ -675,9 +744,10 @@ async def _remember_token(self) -> None: # A rollback expires every instance in the session, including this # one — and an expired instance in an async session reloads itself # lazily, which raises MissingGreenlet from whatever attribute is - # touched next. The routes read `row.login` after calling in here, - # so without this the failure this branch exists to absorb comes - # back as a 500 from a line that only wanted a string. + # touched next. `scope_of` reads the row's provider and region + # straight after `_student`'s call in here, so without this the + # failure this branch exists to absorb comes back as a 500 from a + # line that only wanted a string. # `api/deps.py:_touch_last_seen` carries the same refresh, for the # same reason and after the same outage. await _refresh_quietly(self.session, self.row) diff --git a/server/migrations/versions/0017_corrections_per_child.py b/server/migrations/versions/0017_corrections_per_child.py new file mode 100644 index 00000000..d20d56bb --- /dev/null +++ b/server/migrations/versions/0017_corrections_per_child.py @@ -0,0 +1,198 @@ +"""File the diary corrections under the child, not under a login. + +Revision ID: 0017 +Revises: 0016 +Create Date: 2026-09-26 + +``diary_overrides.login`` held the key a family's corrections were filed under: +the Petersburg login, case-folded, and — only on a database that ran #140's +branch — ``netschool:`` and a SHA-256 of the region and the login. A phone's +registration names its own login and nothing upstream vouches for it, so that +key let one family name another's (#165). The owner decided on 26 September +2026 that the corrections are the **child's**: shared by everyone whose own +diary lists the child, reached only through that list. The column keeps its +name and now holds a scope, ``services/diary.child_scope``: ``CHILD:petersburg``, +or ``CHILD:netschool:`` and the regional server's host — those two shapes and +no other. + +**Data only.** No table, column, index or constraint changes; three statements, +in this order, after a lock (below): + +1. **Deletes every legacy «Сетевой город» row** — ``netschool:`` and 64 + characters, 74 in all. Its region is inside a hash: it could be recovered + only by recomputing the hash from a diary session of the same login and + region, which exists only while its author is still signed in, so some + could be re-filed and the rest never. All of them go instead. Such rows + exist only where #140's branch ran — ``main`` never wrote one — and what + nobody can read or reset is exactly what the privacy policy promises not to + keep. The count, before the transaction:: + + SELECT count(*) FROM diary_overrides + WHERE substr(login, 1, 10) = 'netschool:' AND length(login) = 74; + +2. **Deletes the losers of every collision** among the Petersburg rows. Two + logins that corrected the same field of the same child — two parents, + which is the case this change exists for — become one row per field, and so + does a legacy row beside a per-child row. The one kept is the newest by + ``updated_at``, then the highest ``id``, as ``0013`` kept ``max(id)``: the + value somebody would have been shown last. The rest is text somebody typed; + what goes, per field of a child, before the transaction:: + + SELECT student_id, target, field, count(*) - 1 AS lost + FROM diary_overrides + WHERE (substr(login, 1, 6) <> 'CHILD:' OR login = 'CHILD:petersburg') + AND NOT (substr(login, 1, 10) = 'netschool:' AND length(login) = 74) + GROUP BY 1, 2, 3 HAVING count(*) > 1; + + The legacy «Сетевой город» rows are left out of it because step 1 has + already deleted them by the time this step ranks anything, whatever their + dates. Deleted **before** the update, so ``uq_diary_override`` cannot fire — + provided nothing writes in between, which is what the lock is for. +3. **Rewrites every remaining legacy row** to ``login = 'CHILD:petersburg'``, + keeping ``student_id``, ``target``, ``field`` and the values. A legacy + ``student_id`` cannot say which numbering it came from; it is taken as the + person's ``identity.id``, the one the ``related-child-list`` items that + third-party clients document carry. A child listed by a plain ``id`` + instead gets no corrections from now on (``DiaryService.scope_of``), so a + legacy row that came from one would surface on whichever child has that + number as a person id. Production holds none. + +**The lock.** On PostgreSQL the first statement is ``LOCK TABLE diary_overrides +IN SHARE ROW EXCLUSIVE MODE``: reads go on, and a write waits for the commit. +Without it, applied while the new code runs (the order recommended below for a +deployment that holds corrections), a correction saved between step 2 and step +3 — a per-child row for a field that still has a legacy row — made step 3 raise +``UniqueViolation`` and the whole transaction roll back. With it, that save +waits, then meets the rewritten row in ``uq_diary_override``, which +``put_override`` already answers by updating that row. SQLite has no ``LOCK +TABLE``, so it is skipped there; migrate a SQLite file with the app stopped. + +**Idempotent.** A second run finds no legacy row and no duplicate, which +``uq_diary_override`` rules out, and changes nothing. Portable SQL throughout, +so the same statements run on PostgreSQL and on SQLite, where the tests run +the chain through alembic. + +A per-child row is one whose login starts with ``CHILD:`` in upper case, which +no legacy key can: those are casefolded or lower-case hex. ``substr`` rather +than ``LIKE`` because SQLite's ``LIKE`` ignores case. A legacy Petersburg login +that was literally ``netschool:`` followed by 64 characters would be taken for +the other kind and deleted; dnevnik2 signs nobody in with such a login, and +only this branch's ``/session`` ever stored one unchecked. + +**On production it rewrites and deletes nothing.** Read through the Neon +connector on 26 September 2026: schema ``0014``, ``diary_overrides`` 0 rows, +``diary_sessions`` 0 rows. There it goes on **together with ``0015`` and +``0016``, before #140 merges**, in their one transaction — re-read the counts +first, since nothing stops a family writing a correction in between. + +**On a deployment that holds corrections it is better applied just AFTER the +merge** — the other side from every additive revision, as ``0013`` was, though +for a different reason: nothing here breaks either code, but the old code and +the new file the same corrections under different keys, and each order loses +something made in the window between. Applied first, every rewritten row +vanishes from the running app until the deploy lands, and every correction +typed in that window is filed under a login the new code never reads — lost, +unless somebody runs these statements again by hand. Applied after, nothing +*typed* in the window is lost: new writes are already per-child, and the +rewrite folds the legacy rows into them, the newer value winning. What is lost +is a **reset** made in the window. The new code resets only per-child rows, so +a legacy row it could not see survives «Сбросить правки» or «Сбросить всё», +and this revision then files it under the child — the value somebody just took +off comes back, for everyone who sees the child. The code cannot tell a reset +from a correction that was never made, so the only defence is a short window: +minutes, not a day. In it ``/api/v1/warmup`` reports «База отстала от кода»; +here that is the expected state, not an incident. + +**Downgrade is a no-op, on purpose.** The logins are not recoverable from a +scope. Code at ``0016`` looks corrections up by a casefolded login or a +lower-case hash, neither of which can equal an upper-case scope, so it cannot +read a per-child row or write into one, and those rows stay as they are. What +such code *writes* is another matter, and a revert is not lossless: every +correction typed while older code runs against this database is filed under a +login, where the per-child code never reads it, and a redeploy does not re-run +this revision, because ``alembic_version`` already says ``0017``. So after any +window in which older code ran here — a revert, or this revision applied +before its merge — run the statements again by hand; they are idempotent. With +alembic, ``alembic downgrade 0016 && alembic upgrade head`` does the same, +because the downgrade does nothing and the upgrade runs this revision again. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "0017" +down_revision: str | None = "0016" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +#: `services/diary.child_scope(PETERSBURG, None)`, written out: a revision must +#: not import the app it predates, or it changes when the app does. The colon +#: is escaped because `text()` reads «:name» as a bound parameter even inside a +#: quoted string. +_PETERSBURG = r"'CHILD\:petersburg'" + +#: The key #140's branch built for «Сетевой город»: the provider, a colon and +#: a SHA-256 in lower-case hex. +_LEGACY_NETSCHOOL = "substr({t}login, 1, 10) = 'netschool:' AND length({t}login) = 74" + +#: Everything that ends up under the Petersburg scope: that scope itself, and +#: every row that is not per-child (the «Сетевой город» ones are gone by then). +_PETERSBURG_SET = "(substr({t}login, 1, 6) <> 'CHILD:' OR {t}login = " + _PETERSBURG + ")" + +#: Held to the commit: see the docstring. PostgreSQL only. +_LOCK = sa.text("LOCK TABLE diary_overrides IN SHARE ROW EXCLUSIVE MODE") + +_DROP_LEGACY_NETSCHOOL = sa.text( + "DELETE FROM diary_overrides WHERE " + _LEGACY_NETSCHOOL.format(t="") +) + +#: A row loses to a row of the same field of the same child that is newer, or +#: as new and written later. `updated_at` is NOT NULL since `0011`, so the +#: comparison is total and exactly one row per group survives. +_DROP_COLLISIONS = sa.text( + "DELETE FROM diary_overrides WHERE " + + _PETERSBURG_SET.format(t="") + + " AND EXISTS (SELECT 1 FROM diary_overrides AS keeper WHERE " + + _PETERSBURG_SET.format(t="keeper.") + + " AND keeper.student_id = diary_overrides.student_id" + " AND keeper.target = diary_overrides.target" + " AND keeper.field = diary_overrides.field" + " AND (keeper.updated_at > diary_overrides.updated_at" + " OR (keeper.updated_at = diary_overrides.updated_at" + " AND keeper.id > diary_overrides.id)))" +) + +_REFILE = sa.text( + "UPDATE diary_overrides SET login = " + _PETERSBURG + " WHERE substr(login, 1, 6) <> 'CHILD:'" +) + + +def _has_table(table: str) -> bool: + # Offline (`--sql`) there is nobody to ask, and the database the script is + # written for has the table: `0009` made it. Asked of the migration context + # rather than `alembic.context`, so a test that renders this revision + # in-process runs this very guard, as `0015`'s does. + if op.get_context().as_sql: + return True + return sa.inspect(op.get_bind()).has_table(table) + + +def upgrade() -> None: + if not _has_table("diary_overrides"): + return + if op.get_context().dialect.name == "postgresql": + op.execute(_LOCK) + op.execute(_DROP_LEGACY_NETSCHOOL) + op.execute(_DROP_COLLISIONS) + op.execute(_REFILE) + + +def downgrade() -> None: + # See the docstring: nothing to put back, and nothing the old code can + # misread — and doing nothing is what lets a downgrade and an upgrade + # re-file what reverted code wrote. + pass diff --git a/server/tests/test_corrections_per_child_revision.py b/server/tests/test_corrections_per_child_revision.py new file mode 100644 index 00000000..bc17efca --- /dev/null +++ b/server/tests/test_corrections_per_child_revision.py @@ -0,0 +1,372 @@ +"""``0017``, the revision that files the diary corrections under the child. + +What it has to be, each half held here: + +- **data only** — rendered offline for PostgreSQL, the way ``alembic upgrade + --sql`` and the Neon connector see it, it is a table lock, DELETEs and an + UPDATE and no DDL, and the very statements it renders for PostgreSQL run on + SQLite too (all but the lock, which SQLite has no word for), which is what + "portable" has to mean when the chain is tested on SQLite; +- **exact** — on a real ``alembic upgrade`` it deletes every legacy «Сетевой + город» row, keeps one row per field per child among the Petersburg ones (the + newest, then the highest id) and re-files the rest, and touches no row that + is already per-child; +- **idempotent**, and its downgrade leaves every row where it is — and a + downgrade and an upgrade re-file what code older than it wrote meanwhile; +- **what it tells the owner** before the transaction is what it does: the + counts in its docstring are the rows each destructive step then deletes. + +Nothing here connects to Postgres. +""" + +from __future__ import annotations + +import importlib.util +import io +import os +import re +import sqlite3 +import subprocess +import sys +from pathlib import Path + +from alembic.migration import MigrationContext +from alembic.operations import Operations + +from app.db import EXPECTED_REVISION +from app.services import diary as service + +SERVER_ROOT = Path(__file__).resolve().parent.parent +REVISION = SERVER_ROOT / "migrations" / "versions" / "0017_corrections_per_child.py" + +#: What `services/diary.child_scope` answers for Petersburg — asserted below, +#: so the revision's literal and the function cannot drift apart. +PETERSBURG = "CHILD:petersburg" +#: Keys the branch's old `owner_key` built for «Сетевой город»: 74 characters, +#: one per parent's login. +LEGACY_NETSCHOOL = "netschool:" + "0123456789abcdef" * 4 +LEGACY_NETSCHOOL_MOTHER = "netschool:" + "fedcba9876543210" * 4 +LEGACY_NETSCHOOL_FATHER = "netschool:" + "00112233445566778899aabbccddeeff" * 2 +LOCK = "LOCK TABLE diary_overrides IN SHARE ROW EXCLUSIVE MODE" +LESSON = "lesson:2026-09-15:n1:Алгебра" +HOMEWORK = "hw:id:77" + + +def _revision(): + spec = importlib.util.spec_from_file_location("revision_0017", REVISION) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _render(function, dialect: str = "postgresql") -> list[str]: + rendered = io.StringIO() + context = MigrationContext.configure( + dialect_name=dialect, opts={"as_sql": True, "output_buffer": rendered} + ) + with Operations.context(context): + function() + return [" ".join(part.split()) for part in rendered.getvalue().split(";") if part.strip()] + + +def _runs_on_sqlite(statements: list[str]) -> list[str]: + """The PostgreSQL statements minus the lock, the one SQLite has no word + for and the revision skips there itself.""" + return [statement for statement in statements if not statement.startswith(LOCK)] + + +def _alembic(database: Path, *args: str) -> subprocess.CompletedProcess: + env = dict(os.environ, DATABASE_URL=f"sqlite+aiosqlite:///{database}") + return subprocess.run( + [sys.executable, "-m", "alembic", *args], + env=env, + cwd=str(SERVER_ROOT), + capture_output=True, + text=True, + ) + + +def _at_0016(database: Path) -> None: + """A database one revision behind, built the way the chain builds one — + which runs ``0017`` over an empty table first, the state production was + read in on 26 September, and has to go through it untouched.""" + database.touch() + built = _alembic(database, "upgrade", "head") + assert built.returncode == 0, built.stderr + with sqlite3.connect(database) as db: + db.execute("UPDATE alembic_version SET version_num = '0016'") + + +def _insert(db: sqlite3.Connection, rows: list[tuple]) -> None: + db.executemany( + "INSERT INTO diary_overrides (id, login, student_id, target, field, value, " + "original, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)", + [(row_id, login, student, target, field, value, when, when) + for row_id, login, student, target, field, value, when in rows], + ) + + +def _rows(database: Path) -> set[tuple]: + with sqlite3.connect(database) as db: + return set( + db.execute("SELECT login, student_id, target, field, value FROM diary_overrides") + ) + + +#: Every shape a database can hold at 0016, with the row it must become. +BEFORE = [ + # Two parents' logins on one field of one child: the newer one wins. + (1, "parent@example.com", 4021, LESSON, "room", "204", "2026-09-10 10:00:00"), + (2, "other@example.com", 4021, LESSON, "room", "301", "2026-09-12 10:00:00"), + # Three on another field, the newest written first: it survives although + # its id is the lowest, so `updated_at` ranks before `id`. (Whether the + # DELETE sees its own deletions cannot change the survivor: the newest row + # of a group never has a newer keeper and is every other row's.) + (3, "c@example.com", 4021, LESSON, "teacher", "Третья", "2026-09-14 10:00:00"), + (4, "a@example.com", 4021, LESSON, "teacher", "Первая", "2026-09-11 10:00:00"), + (5, "b@example.com", 4021, LESSON, "teacher", "Вторая", "2026-09-13 10:00:00"), + # As new as each other: the higher id wins, as 0013 kept max(id). + (6, "a@example.com", 4021, HOMEWORK, "text", "раньше", "2026-09-12 10:00:00"), + (7, "b@example.com", 4021, HOMEWORK, "text", "позже", "2026-09-12 10:00:00"), + # A legacy row beside a per-child one, either way round. + (8, "parent@example.com", 4021, LESSON, "topic", "legacy newer", "2026-09-20 10:00:00"), + (9, PETERSBURG, 4021, LESSON, "topic", "per-child older", "2026-09-15 10:00:00"), + (10, "parent@example.com", 4021, LESSON, "homework", "legacy older", "2026-09-10 10:00:00"), + (11, PETERSBURG, 4021, LESSON, "homework", "per-child newer", "2026-09-16 10:00:00"), + # A login somebody typed as «CHILD:petersburg», casefolded: a legacy key, + # re-filed like any other, and nothing collides with it here. + (12, "child:petersburg", 4022, LESSON, "room", "7", "2026-09-10 10:00:00"), + # A legacy «Сетевой город» key: gone, whatever its date — and the older + # Petersburg row on the same (student_id, target, field) is not a loser + # of anything, which a pre-flight count that ranked the two called it. + (13, LEGACY_NETSCHOOL, 11, LESSON, "room", "hashed", "2026-09-10 10:00:00"), + (16, "person11@example.com", 11, LESSON, "room", "person 11", "2026-09-09 10:00:00"), + # Two parents' legacy «Сетевой город» keys for one pupil: both gone, and + # neither is a collision step 2 resolves. + (17, LEGACY_NETSCHOOL_MOTHER, 12, HOMEWORK, "text", "мама", "2026-09-10 10:00:00"), + (18, LEGACY_NETSCHOOL_FATHER, 12, HOMEWORK, "text", "папа", "2026-09-11 10:00:00"), + # Already per-child, in other scopes: untouched, even on a field that + # collides by (student_id, target, field) with the Petersburg rows above. + (14, "CHILD:netschool:region.zabedu.ru", 11, LESSON, "room", "ns", "2026-09-10 10:00:00"), + (15, "CHILD:netschool:region.zabedu.ru", 4021, LESSON, "room", "ns 4021", + "2026-09-01 10:00:00"), +] + +AFTER = { + (PETERSBURG, 4021, LESSON, "room", "301"), + (PETERSBURG, 4021, LESSON, "teacher", "Третья"), + (PETERSBURG, 4021, HOMEWORK, "text", "позже"), + (PETERSBURG, 4021, LESSON, "topic", "legacy newer"), + (PETERSBURG, 4021, LESSON, "homework", "per-child newer"), + (PETERSBURG, 4022, LESSON, "room", "7"), + (PETERSBURG, 11, LESSON, "room", "person 11"), + ("CHILD:netschool:region.zabedu.ru", 11, LESSON, "room", "ns"), + ("CHILD:netschool:region.zabedu.ru", 4021, LESSON, "room", "ns 4021"), +} + + +def test_the_revision_is_data_only_and_names_the_scope_the_code_uses(): + """No DDL: the column keeps its name and every constraint stays as it is. + And the literal it writes is the one `child_scope` answers.""" + revision = _revision() + assert (revision.revision, revision.down_revision) == ("0017", "0016") + assert service.child_scope(None, None) == service.child_scope("petersburg", None) == PETERSBURG + + statements = _render(revision.upgrade) + assert [statement.split()[0] for statement in statements] == [ + "LOCK", "DELETE", "DELETE", "UPDATE" + ] + for statement in statements: + words = set(statement.upper().replace("(", " ").split()) + assert not words & {"CREATE", "ALTER", "DROP", "TRUNCATE", "INDEX", "CONSTRAINT"} + assert statement.startswith( + (LOCK, "DELETE FROM diary_overrides", "UPDATE diary_overrides") + ) + assert statements[3] == ( + f"UPDATE diary_overrides SET login = '{PETERSBURG}' " + "WHERE substr(login, 1, 6) <> 'CHILD:'" + ) + # Nothing to put back: a scope does not remember the login it replaced. + assert _render(revision.downgrade) == [] + + +def test_postgres_is_locked_against_writes_first_and_sqlite_is_not_asked_to(): + """Applied after the merge, the new code writes while this runs. Under READ + COMMITTED a per-child row committed between the collision DELETE and the + UPDATE made the UPDATE raise UniqueViolation (reproduced on PostgreSQL 16) + and the transaction roll back whole; the lock makes that write wait for + the commit instead. It has to come first — a lock taken after the DELETE + guards nothing — and SQLite, which has no LOCK TABLE, must not be sent + one.""" + revision = _revision() + assert _render(revision.upgrade)[0] == LOCK + assert [statement.split()[0] for statement in _render(revision.upgrade, "sqlite")] == [ + "DELETE", "DELETE", "UPDATE" + ] + + +def test_the_statements_rendered_for_postgres_run_on_sqlite_and_do_the_same(tmp_path): + """The PostgreSQL text itself, executed — not a SQLite twin of it. Nothing + here can run Postgres, so this is what "valid SQL" can be asked as: the + statements parse and run on a second engine, over the model's own table, + and leave exactly what the real run below leaves.""" + database = tmp_path / "rendered.db" + _at_0016(database) + with sqlite3.connect(database) as db: + _insert(db, BEFORE) + for statement in _runs_on_sqlite(_render(_revision().upgrade)): + db.execute(statement) + + assert _rows(database) == AFTER + + +def test_a_real_upgrade_leaves_exactly_the_survivors(tmp_path): + database = tmp_path / "at16.db" + _at_0016(database) + with sqlite3.connect(database) as db: + _insert(db, BEFORE) + + upgraded = _alembic(database, "upgrade", "head") + assert upgraded.returncode == 0, upgraded.stderr + + assert _rows(database) == AFTER + with sqlite3.connect(database) as db: + assert db.execute("SELECT version_num FROM alembic_version").fetchall() == [ + (EXPECTED_REVISION,) + ] + # The kept row is the kept row, not a copy: id 2 won the room. + assert db.execute( + "SELECT id FROM diary_overrides WHERE field = 'room' AND student_id = 4021 " + "AND login = ?", + (PETERSBURG,), + ).fetchall() == [(2,)] + + +def test_a_second_run_changes_nothing_and_the_way_down_leaves_every_row(tmp_path): + """Idempotent, because after the first run there is no legacy row and no + duplicate — `uq_diary_override` rules the second out. And the downgrade + is a no-op: the rows wait for the code to come back.""" + database = tmp_path / "twice.db" + _at_0016(database) + with sqlite3.connect(database) as db: + _insert(db, BEFORE) + assert _alembic(database, "upgrade", "head").returncode == 0 + + with sqlite3.connect(database) as db: + for statement in _runs_on_sqlite(_render(_revision().upgrade)): + db.execute(statement) + assert _rows(database) == AFTER + + down = _alembic(database, "downgrade", "0016") + assert down.returncode == 0, down.stderr + assert _rows(database) == AFTER + + up = _alembic(database, "upgrade", "head") + assert up.returncode == 0, up.stderr + assert _rows(database) == AFTER + + +def _preflight(docstring: str) -> list[str]: + """The queries the docstring gives the owner to run before the transaction, + in the order it gives them.""" + queries = re.findall(r"^\s*(SELECT\b.*?;)", docstring, re.S | re.M) + return [" ".join(query.split()) for query in queries] + + +def test_the_counts_the_docstring_gives_the_owner_are_what_each_step_deletes(tmp_path): + """What the revision destroys is a sentence the owner reads *before* the + transaction, and here it is a query: so it is run, over every shape the + table can hold, and held to what each step then deletes. The query this + replaced ranked a legacy «Сетевой город» row against a Petersburg one it + never meets, and counted two parents' hashes for one pupil as a collision + step 2 never resolves — while step 1's deletions had no count at all.""" + netschool, collisions = _preflight(_revision().__doc__) + database = tmp_path / "preflight.db" + _at_0016(database) + with sqlite3.connect(database) as db: + _insert(db, BEFORE) + told = [ + db.execute(netschool).fetchone()[0], + sum(row[-1] for row in db.execute(collisions)), + ] + deleted = [] + for statement in _runs_on_sqlite(_render(_revision().upgrade))[:2]: + before = db.total_changes + db.execute(statement) + deleted.append(db.total_changes - before) + + assert told == deleted == [3, 6] + + +def _service_run(database: Path, work) -> object: + """Run the app's own correction code against the file, the way the new + code would in the window around this revision.""" + import asyncio + + from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine + + async def run(): + engine = create_async_engine(f"sqlite+aiosqlite:///{database}") + try: + async with AsyncSession(engine, expire_on_commit=False) as session: + return await work(session) + finally: + await engine.dispose() + + return asyncio.run(run()) + + +def test_a_reset_in_the_window_after_the_merge_comes_back_when_this_runs(tmp_path): + """Why the docstring, `docs/deploy.md` and CLAUDE.md say to keep the + after-the-merge window to minutes rather than calling it lossless. The new + code resets only per-child rows, so the legacy row it cannot see survives + «Сбросить всё», and this revision then files it under the child: the value + a parent just took off comes back, for everyone who sees the child.""" + database = tmp_path / "window.db" + _at_0016(database) + with sqlite3.connect(database) as db: + _insert(db, [(1, "parent@example.com", 4021, LESSON, "room", "204", + "2026-09-10 10:00:00")]) + + async def in_the_window(session): + assert await service.load_corrections(session, PETERSBURG, 4021) == {} + await service.put_override(session, PETERSBURG, 4021, LESSON, "room", "301", "12") + return await service.drop_overrides(session, PETERSBURG, 4021) + + assert _service_run(database, in_the_window) == 1 + assert _alembic(database, "upgrade", "head").returncode == 0 + + async def after(session): + return await service.load_corrections(session, PETERSBURG, 4021) + + assert _service_run(database, after) == {LESSON: {"room": ("204", None)}} + + +def test_what_older_code_wrote_meanwhile_is_refiled_by_the_remedy_the_docs_name(tmp_path): + """A revert is not lossless. Code older than this revision, running against + a database already at it, files what it is given under a login — and + ``upgrade head`` does nothing then, because the stamp says 0017. The + remedy is written where whoever reverted will look, as a command, and the + command works: the downgrade does nothing, so the upgrade runs this again.""" + remedy = "alembic downgrade 0016 && alembic upgrade head" + deploy = (SERVER_ROOT.parent / "docs" / "deploy.md").read_text("utf-8") + assert remedy in " ".join(_revision().__doc__.split()) + assert remedy in " ".join(deploy.split()) + + database = tmp_path / "reverted.db" + database.touch() + assert _alembic(database, "upgrade", "head").returncode == 0 + with sqlite3.connect(database) as db: + _insert(db, [ + (1, PETERSBURG, 4021, LESSON, "room", "204", "2026-09-10 10:00:00"), + # What reverted code wrote for the same field, later. + (2, "parent@example.com", 4021, LESSON, "room", "305", "2026-09-20 10:00:00"), + ]) + + assert _alembic(database, "upgrade", "head").returncode == 0 + assert (PETERSBURG, 4021, LESSON, "room", "204") in _rows(database) + + for step in (("downgrade", "0016"), ("upgrade", "head")): + ran = _alembic(database, *step) + assert ran.returncode == 0, ran.stderr + assert _rows(database) == {(PETERSBURG, 4021, LESSON, "room", "305")} diff --git a/server/tests/test_diary_api.py b/server/tests/test_diary_api.py index 85ea1c1f..aeebd2ec 100644 --- a/server/tests/test_diary_api.py +++ b/server/tests/test_diary_api.py @@ -836,7 +836,7 @@ async def test_resetting_everything_clears_the_lot(client, upstream, LOGIN_PATH, async def test_corrections_survive_signing_out_and_back_in( client, upstream, session, LOGIN_PATH, with_token ): - """The whole point of keying them on the account rather than the session. + """The whole point of keying them on the child rather than the session. The upstream token dies every few days and the row goes with it; a correction that went too would already be gone by the time anybody pressed @@ -929,14 +929,31 @@ async def test_the_correction_endpoints_need_a_bearer(client): assert response.status_code == 401, path -async def test_corrections_are_private_to_the_account_that_wrote_them( - client, upstream, LOGIN_PATH, with_token +def _one_session_per_account(request: httpx.Request) -> httpx.Response: + """The login answer, with a session of the account's own — two parents + signing in are two upstream sessions, not one handed round.""" + body = json.loads(request.content) + if body.get("password") != "correct": + return httpx.Response(401, json={"message": "Неверный логин или пароль"}) + response = httpx.Response(200, json={"data": {"token": "body-token"}}) + account = body["login"].split("@")[0] + response.headers["set-cookie"] = f"X-JWT-Token=cookie-{account}; Path=/" + return response + + +async def test_corrections_are_shared_by_every_account_that_lists_the_child( + client, upstream, session, LOGIN_PATH ): - """Two parents of one child sign in with their own upstream accounts. The - key is (login, student), so each set of corrections is theirs — and the - fixture gives both accounts the same child, which is the only way this - property can actually be observed.""" - mine = await signed_in_with_a_lesson(client, upstream, LOGIN_PATH, with_token) + """Two parents of one child sign in with their own upstream accounts. + This test used to pin the opposite — each parent's set their own, keyed by + the login — and the owner decided otherwise (#165): the corrections are + the child's, so whoever's own diary lists the child reads them, overwrites + them and resets them, and the other parent sees each of those. The fixture + gives both accounts the same child, which is the only way this can be + observed.""" + mine = await sign_in(client, upstream, LOGIN_PATH, _one_session_per_account) + upstream.routes["/api/journal/person/related-child-list"] = {"items": [CHILD]} + upstream.routes[SCHEDULE_PATH] = {"items": [a_lesson()]} target = (await read_schedule(client, mine))[0]["target"] await client.put( "/api/v1/diary/students/4021/overrides", @@ -944,24 +961,47 @@ async def test_corrections_are_private_to_the_account_that_wrote_them( json={"target": target, "field": "room", "value": "204"}, ) - theirs = await sign_in(client, upstream, LOGIN_PATH, with_token, login="other@example.com") + theirs = await sign_in( + client, upstream, LOGIN_PATH, _one_session_per_account, login="other@example.com" + ) + upstream_sessions = { + service.upstream_of(row) for row in await session.scalars(select(DiarySession)) + } + assert upstream_sessions == {"cookie-parent", "cookie-other"} listed = await client.get( "/api/v1/diary/students/4021/overrides", headers={"Authorization": f"Bearer {theirs}"}, ) - assert listed.json() == [] + assert [row["value"] for row in listed.json()] == ["204"] + assert (await read_schedule(client, theirs))[0]["room"] == "204" + + # Either of them edits the one row, and the other sees it… + await client.put( + "/api/v1/diary/students/4021/overrides", + headers={"Authorization": f"Bearer {theirs}"}, + json={"target": target, "field": "room", "value": "301"}, + ) + assert (await read_schedule(client, mine))[0]["room"] == "301" + + # …and a reset by one is a reset for both. + reset = await client.post( + "/api/v1/diary/students/4021/overrides/reset", + headers={"Authorization": f"Bearer {mine}"}, + json={"target": target, "field": "room"}, + ) + assert reset.status_code == 204 assert (await read_schedule(client, theirs))[0]["room"] == "12" - # …and mine are still mine. - assert (await read_schedule(client, mine))[0]["room"] == "204" async def test_a_login_typed_with_different_capitals_finds_its_corrections( client, upstream, LOGIN_PATH, with_token ): - """The upstream does not care about the case, so neither may we: a family - whose keyboard capitalises the first letter must not find every correction - gone, with no reset button because there is nothing left to reset.""" + """Once the reason was the case-folding of a login-shaped key. Now the + login plays no part at all — the corrections are the child's — and a + family whose keyboard capitalises the first letter must still not find + every correction gone, with no reset button because there is nothing left + to reset.""" first = await signed_in_with_a_lesson(client, upstream, LOGIN_PATH, with_token) target = (await read_schedule(client, first))[0]["target"] await client.put( diff --git a/server/tests/test_diary_corrections_per_child.py b/server/tests/test_diary_corrections_per_child.py new file mode 100644 index 00000000..cac1bf90 --- /dev/null +++ b/server/tests/test_diary_corrections_per_child.py @@ -0,0 +1,448 @@ +"""The corrections over the diary belong to the child (#165). + +The owner's decision of 26 September 2026: everyone whose **own** diary lists a +child sees and edits that child's corrections — both parents, the pupil's own +account — and the login a phone names at ``POST /api/v1/diary/session`` plays no +part, because nothing upstream vouches for it. What this file pins: + +- the key is the diary's server and the pupil's id on it, so one number on two + servers is two children, and a child listed by a number nothing says is one + person's gets no corrections at all; +- a login — copied from another family, or spelled like a scope — reaches + exactly what the session's own diary lists and nothing else; +- a reset for one child reaches everybody's corrections for that child, and no + other child's; +- no scope can ever equal a key the code before this change wrote, so neither + side can read or write the other's rows. + +Nothing here reaches a real diary: each account's pupils are answered by a fake +upstream that reads which session is asking, the way the real one does. +""" + +from __future__ import annotations + +from urllib.parse import unquote + +import httpx +import pytest +from httpx import ASGITransport +from sqlalchemy import select + +from app.main import app +from app.models import DiaryOverride, DiarySession +from app.providers.diary import http as diary_http +from app.providers.diary.registry import NETSCHOOL, PETERSBURG +from app.providers.netschool import client as nsclient +from app.providers.netschool import regions +from app.providers.petersburg import client as pbclient +from app.services import diary as service + +CHILDREN_PATH = "/api/journal/person/related-child-list" +SCHEDULE_PATH = "/api/journal/schedule/list-by-education" +LESSON_TARGET = "lesson:2026-09-15:n1:Алгебра" +WEEK = "from=2026-09-14&to=2026-09-20" + +#: Three Petersburg accounts: three sessions the diary handed three phones. +JWT_A = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBIn0.account-a-signature" +JWT_B = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJCIn0.account-b-signature" +JWT_C = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJDIn0.account-c-signature" + + +def a_child(person: int | None, *, plain_id: int | None = None, education: int = 90210) -> dict: + """A related-child-list item: by ``identity.id``, or — the fallback — by a + plain ``id`` with no identity at all.""" + item: dict = { + "firstname": "Пётр", + "surname": "Иванов", + "educations": [{"education_id": education, "group_id": 771, "group_name": "9А"}], + } + if person is not None: + item["identity"] = {"id": person} + if plain_id is not None: + item["id"] = plain_id + return item + + +class _Petersburg: + """Petersburg's server: each session's own pupils, and one lesson a week.""" + + def __init__(self) -> None: + self.children: dict[str, list[dict]] = {} + + def handler(self, request: httpx.Request) -> httpx.Response: + cookies = dict( + part.strip().split("=", 1) + for part in request.headers.get("cookie", "").split(";") + if "=" in part + ) + token = unquote(cookies.get("X-JWT-Token", "")) + if request.url.path == CHILDREN_PATH: + return httpx.Response(200, json={"data": {"items": self.children.get(token, [])}}) + if request.url.path == SCHEDULE_PATH: + lesson = {"date": "15.09.2026", "subject_name": "Алгебра", "number": 1, "office": "12"} + return httpx.Response(200, json={"data": {"items": [lesson]}}) + return httpx.Response(404, json={"message": "no such path"}) + + +class _NetSchool: + """Every «Сетевой город» server at once: the bootstrap, and each session's + pupils by its ``at``. Which server was asked is on the request's host.""" + + def __init__(self) -> None: + self.pupils: dict[str, list[int]] = {} + + def handler(self, request: httpx.Request) -> httpx.Response: + path = request.url.path + if path == "/webapi/student/diary/init": + ids = self.pupils.get(request.headers.get("at", ""), []) + return httpx.Response(200, json={"students": [ + {"studentId": sid, "nickName": "Иванов Иван", "classId": 3} for sid in ids + ]}) + if path == "/webapi/years/current": + return httpx.Response( + 200, json={"id": 2026, "startDate": "2026-09-01", "endDate": "2027-05-31"} + ) + if path == "/webapi/context": + return httpx.Response(200, json={"organizationName": "Гимназия № 7"}) + if path == "/webapi/grade/assignment/types": + return httpx.Response(200, json=[{"id": 3, "name": "Домашнее задание"}]) + return httpx.Response(404, json={}) + + +@pytest.fixture +async def client(): + async with httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac: + yield ac + + +@pytest.fixture +def petersburg(monkeypatch) -> _Petersburg: + fake = _Petersburg() + + async def shared(): + return httpx.AsyncClient( + base_url=pbclient.BASE_URL, transport=httpx.MockTransport(fake.handler) + ) + + monkeypatch.setattr(pbclient, "shared_client", shared) + return fake + + +@pytest.fixture +def netschool(monkeypatch) -> _NetSchool: + fake = _NetSchool() + + async def shared(): + return httpx.AsyncClient( + transport=httpx.MockTransport(fake.handler), cookies=diary_http.NoCookieJar() + ) + + monkeypatch.setattr(nsclient, "shared_client", shared) + return fake + + +async def register_petersburg(client, jwt: str, login: str) -> dict[str, str]: + response = await client.post( + "/api/v1/diary/session", + json={"provider": "petersburg", "login": login, "credential": {"token": jwt}}, + ) + assert response.status_code == 200, response.text + return {"Authorization": f"Bearer {response.json()['token']}"} + + +async def register_netschool(client, at: str, login: str, region: str) -> dict[str, str]: + response = await client.post( + "/api/v1/diary/session", + json={ + "provider": "netschool", + "login": login, + "region": region, + "school_id": 42, + "credential": {"at": at, "cookies": {"NSSESSIONID": f"sess-{at}"}}, + }, + ) + assert response.status_code == 200, response.text + return {"Authorization": f"Bearer {response.json()['token']}"} + + +def overrides(student: int) -> str: + return f"/api/v1/diary/students/{student}/overrides" + + +async def write(client, headers, student: int, value: str, target: str = LESSON_TARGET, + field: str = "room") -> None: + written = await client.put( + overrides(student), headers=headers, + json={"target": target, "field": field, "value": value, "original": "12"}, + ) + assert written.status_code == 200, written.text + + +async def values(client, headers, student: int) -> list[str]: + listed = await client.get(overrides(student), headers=headers) + assert listed.status_code == 200, listed.text + return [row["value"] for row in listed.json()] + + +async def room(client, headers, student: int) -> str: + lessons = await client.get( + f"/api/v1/diary/students/{student}/schedule?{WEEK}", headers=headers + ) + assert lessons.status_code == 200, lessons.text + return lessons.json()[0]["room"] + + +# ---- the scope ------------------------------------------------------------- + + +def _every_scope() -> list[str]: + scopes = [service.child_scope(None, None), service.child_scope(PETERSBURG, None)] + for region in regions.listed(password_only=False): + scopes.append(service.child_scope(NETSCHOOL, region.key)) + return scopes + + +def test_a_scope_names_the_diary_s_server_and_nothing_a_phone_typed(): + assert service.child_scope(None, None) == "CHILD:petersburg" + assert service.child_scope(PETERSBURG, None) == "CHILD:petersburg" + assert service.child_scope(NETSCHOOL, "zabaikalsky") == "CHILD:netschool:region.zabedu.ru" + # The host with its port, as the session's own calls reach it. + assert ( + service.child_scope(NETSCHOOL, "sakhalin") + == "CHILD:netschool:netcity.admsakhalin.ru:11111" + ) + # Every server is its own scope; the only two that coincide are + # Petersburg's two spellings, NULL and its name. + scopes = _every_scope() + assert len(set(scopes)) == len(scopes) - 1 + assert all(len(scope) <= DiaryOverride.__table__.c.login.type.length for scope in scopes) + + +@pytest.mark.parametrize( + "login", + [ + "parent@example.com", + "CHILD:petersburg", + "child:petersburg", + " Child:Petersburg ", + "CHILD:netschool:region.zabedu.ru", + ], +) +def test_no_scope_is_the_key_any_login_ever_made(login): + """The key before this change was ``login.strip().casefold()`` (or a + lower-case hash), and a scope starts in upper case — so no login, even one + typed to look like a scope, lands on a per-child row under the old code, + and no per-child row is ever read as somebody's login under the new.""" + legacy = login.strip().casefold() + for scope in _every_scope(): + assert scope != legacy + # The general form: a casefolded string is its own casefold, a scope never is. + assert scope != scope.casefold() + + +def test_a_region_the_allow_list_does_not_hold_has_no_scope(): + """Refused, never guessed: a fallback would file one server's pupils beside + another's under one number.""" + for provider, region in ((NETSCHOOL, "atlantis"), (NETSCHOOL, None), ("elsewhere", None)): + with pytest.raises(service.UnknownDiaryServer): + service.child_scope(provider, region) + + +def test_the_scope_follows_the_server_not_the_region_key(monkeypatch): + """Two regions on one server share its numbering, and a region whose + origin moves stops matching its old corrections — lost, rather than laid + over whichever child has the same number on the new server.""" + zabaikalsky = regions.get("zabaikalsky") + twin = regions.Region("twin", "Двойник", "https://REGION.zabedu.ru", "Asia/Chita") + monkeypatch.setitem(regions._BY_KEY, "twin", twin) + assert service.child_scope(NETSCHOOL, "twin") == service.child_scope(NETSCHOOL, "zabaikalsky") + + before = service.child_scope(NETSCHOOL, "zabaikalsky") + moved = regions.Region("zabaikalsky", zabaikalsky.title, "https://sgo.zabedu.ru", + zabaikalsky.zone) + monkeypatch.setitem(regions._BY_KEY, "zabaikalsky", moved) + assert service.child_scope(NETSCHOOL, "zabaikalsky") != before + + +async def test_the_store_refuses_a_login_where_a_scope_belongs(session): + """A login passed where a scope belongs is #165 again, and it would + type-check: so the store refuses it rather than filing under it.""" + for call in ( + lambda: service.list_overrides(session, "parent@example.com", 4021), + lambda: service.load_corrections(session, "parent@example.com", 4021), + lambda: service.drop_overrides(session, "child:petersburg", 4021), + ): + with pytest.raises(ValueError, match="not under a login"): + await call() + assert await service.list_overrides(session, "CHILD:petersburg", 4021) == [] + + +# ---- who reaches a child --------------------------------------------------- + + +async def test_a_login_copied_from_another_family_reaches_only_its_own_diary( + client, petersburg +): + """#165. B's phone registers B's own session and names A's login — or a + login spelled like a scope. B reaches exactly the pupils B's own diary + lists: every door onto A's child is a 404, A's correction survives B's + attempts at it, and what B sees of its own child does not depend on which + login B named.""" + petersburg.children = {JWT_A: [a_child(4021)], JWT_B: [a_child(5055, education=90555)]} + a = await register_petersburg(client, JWT_A, "parent@example.com") + await write(client, a, 4021, "204") + + for login in ("parent@example.com", "CHILD:petersburg", "child:petersburg"): + b = await register_petersburg(client, JWT_B, login) + listed = await client.get("/api/v1/diary/students", headers=b) + assert [pupil["id"] for pupil in listed.json()] == [5055] + + refusals = [ + await client.get(f"/api/v1/diary/students/4021/schedule?{WEEK}", headers=b), + await client.get(f"/api/v1/diary/students/4021/homework?{WEEK}", headers=b), + await client.get(overrides(4021), headers=b), + await client.put(overrides(4021), headers=b, json={ + "target": LESSON_TARGET, "field": "room", "value": "666"}), + await client.post(f"{overrides(4021)}/reset", headers=b, json={ + "target": LESSON_TARGET, "field": "room"}), + await client.delete(f"{overrides(4021)}/all", headers=b), + ] + assert [answer.status_code for answer in refusals] == [404] * 6, login + assert await values(client, b, 5055) == [] + + assert await values(client, a, 4021) == ["204"] + assert await room(client, a, 4021) == "204" + + # The login plays no part in what B sees of B's own child either: written + # under A's login, read under B's own. + as_a = await register_petersburg(client, JWT_B, "parent@example.com") + await write(client, as_a, 5055, "301") + as_b = await register_petersburg(client, JWT_B, "b@example.com") + assert await values(client, as_b, 5055) == ["301"] + # And A, whose diary does not list 5055, cannot reach it at all. + assert (await client.get(overrides(5055), headers=a)).status_code == 404 + + +async def test_a_child_found_by_a_plain_id_gets_no_corrections_at_all( + client, petersburg, session +): + """`identity_id` falls back to a plain ``id`` when there is no identity, + and nothing says what that numbers. With the login out of the key, the + number would be all that told two families' children apart: B and C each + list a different child as plain 4021, and a shared scope would let either + read, overwrite and reset the other's. So such a child fails closed — its + diary as it came, nothing listed, a write refused with the 422 the app + reads as «Это поле нельзя исправить», a reset with nothing to take off — + and none of it reaches A's child, whose person id is 4021.""" + petersburg.children = { + JWT_A: [a_child(4021)], + JWT_B: [a_child(None, plain_id=4021, education=90555)], + JWT_C: [a_child(None, plain_id=4021, education=90777)], + } + a = await register_petersburg(client, JWT_A, "parent@example.com") + await write(client, a, 4021, "204") + + for jwt in (JWT_B, JWT_C): + other = await register_petersburg(client, jwt, "parent@example.com") + refused = await client.put(overrides(4021), headers=other, json={ + "target": LESSON_TARGET, "field": "room", "value": "999", "original": "12"}) + assert refused.status_code == 422, refused.text + assert refused.json()["detail"] == "Для этого ученика правки недоступны" + assert await values(client, other, 4021) == [] + assert await room(client, other, 4021) == "12" + resets = [ + await client.post(f"{overrides(4021)}/reset", headers=other, json={ + "target": LESSON_TARGET, "field": "room"}), + await client.delete(f"{overrides(4021)}/all", headers=other), + ] + assert [answer.status_code for answer in resets] == [204, 204] + + stored = await session.scalars(select(DiaryOverride)) + assert [(row.login, row.student_id, row.value) for row in stored] == [ + ("CHILD:petersburg", 4021, "204") + ] + assert await values(client, a, 4021) == ["204"] + + +async def test_one_pupil_number_on_two_servers_is_two_children(client, petersburg, netschool): + """A «Сетевой город» pupil id is numbered per regional server: pupil 11 in + Забайкалье is not pupil 11 in Приамурье, nor the Petersburg person whose + identity is 11. On one server it is one child, whichever parent asks.""" + netschool.pupils = {"at-zab-mother-001": [11], "at-zab-father-002": [11], + "at-amur-00000003": [11]} + petersburg.children = {JWT_C: [a_child(11)]} + + mother = await register_netschool(client, "at-zab-mother-001", "ivanova", "zabaikalsky") + await write(client, mother, 11, "из Забайкалья", target="hw:id:77", field="text") + + father = await register_netschool(client, "at-zab-father-002", "ivanov", "zabaikalsky") + assert await values(client, father, 11) == ["из Забайкалья"] + + amur = await register_netschool(client, "at-amur-00000003", "ivanova", "amur") + assert await values(client, amur, 11) == [] + await write(client, amur, 11, "из Приамурья", target="hw:id:77", field="text") + + city = await register_petersburg(client, JWT_C, "ivanova") + assert await values(client, city, 11) == [] + + assert await values(client, mother, 11) == ["из Забайкалья"] + assert await values(client, amur, 11) == ["из Приамурья"] + + +async def test_resetting_everything_for_one_child_reaches_everyone_and_no_other_child( + client, petersburg +): + """The reset is the child's too: the other parent's «сбросить всё» takes + off what this parent wrote for that child — and nothing of the sibling's, + because the delete is bounded by the pupil.""" + siblings = [a_child(4021), a_child(4022, education=90222)] + petersburg.children = {JWT_A: siblings, JWT_B: siblings} + a = await register_petersburg(client, JWT_A, "mother@example.com") + await write(client, a, 4021, "204") + await write(client, a, 4022, "305") + + b = await register_petersburg(client, JWT_B, "father@example.com") + dropped = await client.delete(f"{overrides(4021)}/all", headers=b) + assert dropped.status_code == 204 + + assert await values(client, a, 4021) == [] + assert await values(client, a, 4022) == ["305"] + + +async def test_a_row_filed_under_a_login_is_read_by_nobody(client, petersburg, session): + """What revision 0017 re-files: until it runs, a row keyed by a login is + invisible to every session — including one that names that very login, + and one whose login is spelled like the scope.""" + session.add_all([ + DiaryOverride(login="parent@example.com", student_id=4021, target=LESSON_TARGET, + field="room", value="legacy"), + DiaryOverride(login="child:petersburg", student_id=4021, target=LESSON_TARGET, + field="topic", value="legacy"), + ]) + await session.commit() + petersburg.children = {JWT_A: [a_child(4021)]} + + for login in ("parent@example.com", "CHILD:petersburg"): + a = await register_petersburg(client, JWT_A, login) + assert await values(client, a, 4021) == [] + assert await room(client, a, 4021) == "12" + + +async def test_a_session_whose_region_names_no_server_is_sent_to_sign_in_again( + client, netschool, session +): + """A «Сетевой город» row the allow-list cannot place gets no scope and no + fallback: it is expired, and the route says «войдите заново», the way an + unreadable credential does.""" + netschool.pupils = {"at-zab-mother-001": [11]} + headers = await register_netschool(client, "at-zab-mother-001", "ivanova", "zabaikalsky") + row = await session.scalar(select(DiarySession)) + row.region = "atlantis" + await session.commit() + + response = await client.get(overrides(11), headers=headers) + + assert response.status_code == 401, response.text + assert response.headers["X-Diary-Reauth"] == "required" + await session.refresh(row) + assert row.expired_at is not None diff --git a/server/tests/test_diary_mapper.py b/server/tests/test_diary_mapper.py index a84a8c40..b34cda83 100644 --- a/server/tests/test_diary_mapper.py +++ b/server/tests/test_diary_mapper.py @@ -84,6 +84,20 @@ def test_a_child_with_no_identity_is_skipped(): assert m.to_students([child(identity={})]) == [] +def test_a_child_found_by_a_plain_id_says_so(): + """`identity.id` is taken to be the person, city-wide. A plain ``id`` is + the fallback some endpoints send instead, and nothing says what it + numbers — so a child found by one carries it in `id_space`, which is what + keeps corrections off that child altogether.""" + by_identity = m.to_students([child()])[0] + assert (by_identity.id, by_identity.id_space) == (4021, None) + + by_plain_id = m.to_students([child(identity=None, id=4021)])[0] + assert (by_plain_id.id, by_plain_id.id_space) == (4021, m.PLAIN_ID) + # An identity that does not carry a number falls back the same way. + assert m.to_students([child(identity={}, id=4021)])[0].id_space == m.PLAIN_ID + + def test_a_missing_middle_name_is_absent_rather_than_empty(): student = m.to_students([child(middlename="")])[0] assert student.middle_name is None diff --git a/server/tests/test_diary_protocol_vectors.py b/server/tests/test_diary_protocol_vectors.py index fa00adb9..fff149d8 100644 --- a/server/tests/test_diary_protocol_vectors.py +++ b/server/tests/test_diary_protocol_vectors.py @@ -467,8 +467,10 @@ def test_header_token_rule_matches_the_vectors(case): @pytest.mark.parametrize("case", VECTORS["login"]["cases"], ids=lambda c: ascii(c["typed"])) def test_login_cleaning_matches_the_vectors(case): - """The login the server keys a family's corrections on is the login the - phone sends the diary and registers — one cleaning, on both sides. The + """The login the server stores and prints on «Вход выполнен» is the login + the phone sends the diary and registers — one cleaning, on both sides, so + a login pasted with an invisible character is not a wrong password on one + side only. It keys nothing (the corrections are the child's). The registration body and the password sign-in each run it, so each is asked.""" wanted = case["sent"] assert VECTORS["login"]["min_code_points"] == 3 diff --git a/server/tests/test_diary_provider_revision.py b/server/tests/test_diary_provider_revision.py index d3703b60..53bdc354 100644 --- a/server/tests/test_diary_provider_revision.py +++ b/server/tests/test_diary_provider_revision.py @@ -35,6 +35,7 @@ from alembic.operations import Operations from sqlalchemy.dialects import postgresql +from app.db import EXPECTED_REVISION from app.models import DiarySession, SchoolClass SERVER_ROOT = Path(__file__).resolve().parent.parent @@ -169,7 +170,10 @@ def test_a_file_built_before_the_model_changed_gets_every_column(tmp_path): with sqlite3.connect(database) as db: for table, columns in ADDED.items(): assert set(columns) <= _columns(db, table), table - assert db.execute("select version_num from alembic_version").fetchall() == [("0016",)] + # The head, whichever it is: a later revision runs after this one. + assert db.execute("select version_num from alembic_version").fetchall() == [ + (EXPECTED_REVISION,) + ] # What the app itself reads: every mapped column of both tables. engine = sa.create_engine(f"sqlite:///{database}") diff --git a/server/tests/test_diary_session.py b/server/tests/test_diary_session.py index eb2f213b..a76cca90 100644 --- a/server/tests/test_diary_session.py +++ b/server/tests/test_diary_session.py @@ -501,11 +501,13 @@ async def test_a_registered_session_reads_like_a_signed_in_one(client, petersbur assert all(f"X-JWT-Token={JWT}" in r.headers["cookie"] for r in petersburg.seen) -async def test_the_login_finds_the_corrections_a_password_sign_in_left( +async def test_a_registration_finds_the_corrections_a_password_sign_in_left( client, petersburg, LOGIN_PATH, with_token ): - """Corrections are keyed by the login, case-folded. A family that used to - sign in with a password and now registers from the phone keeps them.""" + """A family that used to sign in with a password and now registers from + the phone keeps its corrections. Once that was because both keyed them by + the same login, case-folded; now it is because they belong to the child, + and the login — typed differently here on purpose — plays no part (#165).""" petersburg.routes[LOGIN_PATH] = with_token petersburg.routes[SCHEDULE_PATH] = {"items": [ {"date": "15.09.2026", "subject_name": "Алгебра", "number": 1, "office": "12"}]} @@ -522,7 +524,7 @@ async def test_the_login_finds_the_corrections_a_password_sign_in_left( ) assert put.status_code == 200, put.text - token = (await _register(client, _petersburg_body(login="parent@example.com"))).json()["token"] + token = (await _register(client, _petersburg_body(login="ivanova.m"))).json()["token"] lesson = (await client.get(schedule, headers={"Authorization": f"Bearer {token}"})).json()[0] assert lesson["room"] == "204" diff --git a/server/tests/test_netschool_mapper.py b/server/tests/test_netschool_mapper.py index 7b118352..b2825097 100644 --- a/server/tests/test_netschool_mapper.py +++ b/server/tests/test_netschool_mapper.py @@ -111,6 +111,26 @@ def test_a_wholly_unreadable_children_answer_raises(): m.to_students({"students": "nonsense"}, None) +def test_a_json_true_is_no_pupil_and_no_class(): + """`bool` is an `int` in Python, so `true` passed `isinstance(sid, int)` + as pupil 1 — and a pupil's id is half of the key the child's corrections + are filed under, shared by everyone whose diary lists that child. Read as + pupil 1, it would have laid pupil 1's corrections over another child. + Refused, as Petersburg's `number` refuses one; `classId` the same.""" + import pytest + + students = m.to_students( + {"students": [{"studentId": True, "nickName": "Никто"}, + {"studentId": 12, "nickName": "Петров Пётр", "classId": True}]}, + None, + ) + assert [(pupil.id, pupil.group_id) for pupil in students] == [(12, None)] + + # A list of nothing but that is a list nobody can read, not an empty one. + with pytest.raises(m.UnexpectedResponseError): + m.to_students({"students": [{"studentId": True, "nickName": "Никто"}]}, None) + + def test_periods_mark_the_term_holding_today(): terms = [ {"id": 1, "termName": "1 четверть", "startDate": "2026-09-01", "endDate": "2026-10-26"}, diff --git a/server/tests/test_quota.py b/server/tests/test_quota.py index a02f1f75..7a59c192 100644 --- a/server/tests/test_quota.py +++ b/server/tests/test_quota.py @@ -34,6 +34,7 @@ from sqlalchemy.dialects import postgresql from sqlalchemy.schema import CreateTable +from app.db import EXPECTED_REVISION from app.models import UsageCounter from app.services import quota @@ -241,7 +242,10 @@ def test_the_revision_creates_the_table_where_it_is_missing_and_drops_it_going_d # (cid, name, type, notnull, default, pk) assert [columns[name][5] for name in ("scope", "day")] == [1, 2] assert columns["used"][3] == 1 - assert db.execute("select version_num from alembic_version").fetchall() == [("0016",)] + # The head, whichever it is: a later revision runs after this one. + assert db.execute("select version_num from alembic_version").fetchall() == [ + (EXPECTED_REVISION,) + ] downgraded = _alembic(database, "downgrade", "0015") assert downgraded.returncode == 0, downgraded.stderr diff --git a/server/tests/test_schema_version.py b/server/tests/test_schema_version.py index 45fd108c..2a4cd7a7 100644 --- a/server/tests/test_schema_version.py +++ b/server/tests/test_schema_version.py @@ -14,6 +14,7 @@ from __future__ import annotations +import re from pathlib import Path import pytest @@ -78,6 +79,51 @@ def test_the_constant_the_app_ships_is_the_real_migration_head(): assert EXPECTED_REVISION == _head() +REPOSITORY = SERVER_ROOT.parent + +#: How a document says which revision is the head. A sentence cannot be +#: checked; a revision number in one of these can. +_HEAD_SENTENCES = ( + re.compile(r"[Hh]ead is \**`(\d{4})`"), + re.compile(r"expects `(\d{4})`"), +) +#: The answer `/warmup` gives when all is well, as the reference documents +#: print it. Only under docs/: the README quotes an answer from #61 on purpose. +_WARMUP_OK = re.compile(r'"status": ?"ok"[^}\n]*"schema": ?"(\d{4})"') + + +def _documents() -> list[Path]: + """Everything a person or an agent reads to learn the head — not + HANDOVER.md, which is a history and holds every head there has been.""" + found = [REPOSITORY / name for name in ("README.md", "CLAUDE.md", "AGENTS.md")] + found.append(REPOSITORY / ".github" / "copilot-instructions.md") + found += sorted((REPOSITORY / "docs").rglob("*.md")) + found += sorted((REPOSITORY / ".claude").rglob("*.md")) + return [document for document in found if document.is_file()] + + +def test_every_document_that_names_the_head_names_this_one(): + """The constant is pinned above; the documents quoting it were not, and a + batch that moved the head to `0017` left the README telling the operator to + expect `0016` from `/warmup` — which after the merge answers «degraded» — + and the migration skill, the procedure the next revision follows, a head + behind. A document that names a head names this one.""" + named: dict[str, set[str]] = {} + for document in _documents(): + text = document.read_text("utf-8") + patterns = list(_HEAD_SENTENCES) + if document.is_relative_to(REPOSITORY / "docs"): + patterns.append(_WARMUP_OK) + for pattern in patterns: + for revision in pattern.findall(text): + named.setdefault(revision, set()).add(str(document.relative_to(REPOSITORY))) + + assert EXPECTED_REVISION in named, "no document names the head any more" + stale = {revision: sorted(where) for revision, where in named.items() + if revision != EXPECTED_REVISION} + assert not stale, f"the head is {EXPECTED_REVISION}, but these say otherwise: {stale}" + + def test_every_revision_is_reachable_from_the_head(): """One chain, no forks. Two heads mean `upgrade head` is ambiguous and picks one, which is a migration silently not applied.""" From 4c1e8c12a9cff972e3aa012db4aa4321bcaa7491 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 12:28:40 +0000 Subject: [PATCH 30/30] Record that 0015, 0016 and 0017 are on production, and where #140 stands before its merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner allowed the migrations on the condition that the code had no known defect; with #165 decided and fixed in e01443d and CI green on it, they went on at 12:26 UTC on 26 September, as one transaction through the Neon connector, before the merge. The database was read first (head 0014, none of the eight columns, no usage_counters, 0 corrections, 0 diary sessions, 1 class) and read back after: head 0017 with one stamp, the eight columns nullable with the declared types, usage_counters keyed (scope, day), and still 0 corrections and 0 sessions — nothing rewritten, nothing destroyed. Every statement came from the revisions rendered offline for PostgreSQL, which matched the models' DDL. HANDOVER's opening, schema chapter, defect table, gates and cheat-sheet say so, with #165 closed by e01443d and the counts from the real runs (server 2024, Android 1408). README, CLAUDE.md, docs/deploy.md and the migrations agent move from «to be applied» to «applied». Until #140 deploys, /api/v1/warmup answers «База впереди кода…», the window the correct order creates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS --- .claude/agents/server-migrations.md | 4 +- CLAUDE.md | 6 +- HANDOVER.md | 130 ++++++++++++++++------------ README.md | 8 +- docs/deploy.md | 10 +-- 5 files changed, 88 insertions(+), 70 deletions(-) diff --git a/.claude/agents/server-migrations.md b/.claude/agents/server-migrations.md index 17b7c700..0d2d7f29 100644 --- a/.claude/agents/server-migrations.md +++ b/.claude/agents/server-migrations.md @@ -4,8 +4,8 @@ description: Alembic revisions and the Neon protocol. Use whenever a model chang tools: Read, Glob, Grep, Bash, Edit, Write --- -You own `server/migrations/`. Head is **`0017`**; production was last read at `0014`, and -`0015`, `0016` and `0017` go on together before #140 merges. +You own `server/migrations/`. Head is **`0017`**, and production is at `0017`: `0015`, +`0016` and `0017` went on together on 26 September 2026, before #140 merged. ## The chain, and what each one did diff --git a/CLAUDE.md b/CLAUDE.md index 360906c5..41058693 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -346,7 +346,7 @@ points Hilt does not inject cleanly. `alembic upgrade head` by hand and this session has no `DATABASE_URL`; the project is the one named `lessons` on the Neon MCP server — the account has two, so read the name rather than guessing an id, and the id itself stays out of the repository — and `0005` through - `0014` were all applied that way. It is not alembic running — it is the revision's DDL executed as one + `0017` were all applied that way. It is not alembic running — it is the revision's DDL executed as one transaction, with `alembic_version` stamped in the same transaction — so three things follow. Take the DDL from the model rather than writing it out: `CreateTable(...).compile( dialect=postgresql.dialect())` prints exactly what `create_all` would build, which is what @@ -354,7 +354,7 @@ points Hilt does not inject cleanly. a half-applied revision cannot claim to be whole. And say what a revision destroys before running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a sentence the owner needs *before* the transaction, not after. -- **Migrations are Alembic and the head is `0017`, which goes on with `0015` and `0016` before this batch's merge.** `0001` is a guarded +- **Migrations are Alembic and the head is `0017`, on production since 26 September 2026 with `0015` and `0016`, before #140's merge.** `0001` is a guarded `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds @@ -409,7 +409,7 @@ points Hilt does not inject cleanly. Petersburg rows are rewritten to `CHILD:petersburg`. Its docstring carries a count per destructive step to read before the transaction, and on PostgreSQL it locks the table against writes first. On this database, with - no correction in it on 26 September, that is nothing, and it goes on with + no correction in it on 26 September, that was nothing, and it went on with `0015` and `0016` **before** the merge. On a deployment that holds corrections it is better applied just **after** the merge — a key rewrite, a third shape beside the column and the constraint: before it, whatever the diff --git a/HANDOVER.md b/HANDOVER.md index a3de272a..04aaaa95 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -14,12 +14,12 @@ fast-forward. **The only thing open is the pull request carrying this paragraph, the owner created that milestone on 25 September and renamed the other nine the same day (the table, with what each was called before, is under «And before that: nothing on a screen is cut off»). Both reviews of its code have finished, and every confirmed finding is -fixed on the branch but one. That one is **#165**, and it is the owner's to decide. Three -things now stand between #140 and the merge, in this order: -1. The owner decides #165, and its fix lands here. -2. `0015` and `0016` go onto the production database. The owner made them conditional on - code with no known defect, and «Schema» below says why they have not run. -3. The `github-pr` skill's checklist passes on the exact head. +fixed on the branch. The last one, **#165**, was a product decision. The owner decided it on +26 September: corrections are shared per child. It is fixed in `e01443d`, with a third +revision, `0017`. With no known defect left, `0015`, `0016` and `0017` went onto the +production database on 26 September 2026 at 12:26 UTC, as the owner's condition allowed. +What stands between #140 and the merge is only the `github-pr` skill's checklist on the +exact head. The SHA of its own merge is for the next close-out to write. @@ -30,11 +30,10 @@ unchanged. The second (#141, from `17c0473`) is the owner's request of 25 Septem run with two ways in — the class code, or the family's own school's diary — on which the password goes from the phone to the diary and never to this server, and a phone that reads only its diary gets a home of its own. Both halves' gates were run rather than quoted: -server **1998** tests, Android **1408**. +server **2024** tests, Android **1408**. -**Once #140 merges, twenty-four issues are meant to close and twenty-five stay open.** Meant to -close: #136–#139, #141, #145–#155 and #157–#164. Staying open: **#165** until the owner -decides it; **#156**, whose fix is in +**Once #140 merges, twenty-five issues are meant to close and twenty-four stay open.** Meant to +close: #136–#139, #141, #145–#155 and #157–#165. Staying open: **#156**, whose fix is in `ce9c749` but which waits for a phone's backup to be read (`needs:device`); **#135**, the owner's decision about the second diary, which the code has now answered but which is theirs to close; **#142**, **#143** and **#144**, this batch's deliberate follow-ups, on no @@ -43,13 +42,14 @@ the owner's alone; and #123–#127, `status:someday`. What a merge closes is dec `Closes` lines in the pull request body and in the commit messages, not by this paragraph — read them against this list before merging. -**The code expects head `0016`; production was read on 25 September at `0014`.** -`EXPECTED_REVISION` in `app/db.py` is `0016`, pinned to the real head by +**The code expects head `0017`, and production is at `0017` since 26 September 2026 at 12:26 UTC.** +`EXPECTED_REVISION` in `app/db.py` is `0017`, pinned to the real head by `tests/test_schema_version.py`. `0015` adds the eight nullable columns the second diary -needs, and `0016` creates `usage_counters`, the anonymous school directory's daily count of -DaData requests. Both are additive and destroy nothing, so both go on through the Neon -connector (the project named `lessons`) **before** the merge; «Schema» in the section on #140 -below says when they did and what the database said. The `0014` chapter still holds: #83's +needs. `0016` creates `usage_counters`, the anonymous school directory's daily count of +DaData requests. `0017` files the diary corrections under the child rather than a login, and +it is data only. All three went on through the Neon connector (the project named `lessons`) +**before** the merge, in one transaction; «Schema» in the section on #140 below says what the +database said. The `0014` chapter still holds: #83's pinned table of the enum column widths fails when a `SAEnum` member's **name** outgrows its `VARCHAR`, which SQLite cannot see and production Postgres finds at the moment somebody marks a day. @@ -60,7 +60,7 @@ answered `{"status":"ok","api_version":1,"schema":"0013"}`. **It has not been re and #83 found out why.** The deployments sit behind Vercel's Deployment Protection and answer a redirect to a login page, so `/api/v1/warmup` cannot be read from a session here at all. It still wants reading, by the owner's browser or with a bypass token (#119). Once #140 -has merged and deployed it should answer `"schema":"0016"`; in the window between the +has merged and deployed it should answer `"schema":"0017"`; in the window between the migrations and the merge it answers `degraded` with «База впереди кода…», which is the window the correct order creates rather than a fault. That single line is the cheapest check that the migrations and the code actually met. @@ -279,14 +279,16 @@ Twenty-one, on top of part one's three (#136–#138): | #162 | Dependabot and the issue templates applied labels the project does not have, so bumps arrived bare and reports outside `type:` and `status:` | `f31e5ed` | | #163 | the join and diary sign-in throttles counted before they recorded, so a burst went past them (24 wrong passwords against a limit of 10) | `6b0878f` | | #164 | the server's checks assumed SQLAlchemy 2.0 while every fresh install resolves 2.1: one test compared SQL without casts, and mypy failed on `main` | `d208251` | -| #165 | a session registered from a phone names its own login, unchecked, and that login keys another family's corrections | **not fixed** — waits for the owner (`needs:owner`) | +| #165 | a session registered from a phone names its own login, unchecked, and that login keys another family's corrections | `e01443d` — corrections are now the child's, by the owner's decision | Twelve more, from an adversarial review of the new Android data layer, were fixed in `9c797a2`, each with a test that failed before its fix. They are listed in that commit's body and have no issues of their own: they were in code this branch adds, and none of it had reached `main`. The same holds for the thirty findings of the second review of the screens (`061a716`, 31 in all, one of them #161) and for twenty of the audit of the server -half (`6b0878f`, 22 in all: #163 fixed, #165 open). +half (`6b0878f`, 22 in all: #163 fixed there, #165 in `e01443d`). The change for #165 had a +review of its own: five lenses, two refuters per finding, 17 of 23 findings confirmed. All 17 +are fixed in the same commit, and its body lists them. **One commit body is wrong, and the code is right.** `6fa1c6e` says rebinding a class to another *school* expires its diary sessions. `services/diary.expire_off_binding` expires them @@ -296,8 +298,8 @@ school. The documents follow the code. ### Schema -`EXPECTED_REVISION` is `0016`; production was at `0014` when this was written, two -revisions behind: +`EXPECTED_REVISION` is `0017`. Production was at `0014`, three revisions behind, until the +transaction below: - **`0015`** (`0015_diary_provider_columns.py`) adds five nullable columns to `diary_sessions` — `provider`, `region`, `kept_alive_at`, `keepalive_attempted_at`, @@ -306,26 +308,39 @@ revisions behind: Its downgrade expires every non-Petersburg session before dropping the columns that tell one apart. - **`0016`** (`0016_usage_counters.py`) creates `usage_counters` and nothing else. - -Both are additive, rewrite no row and destroy none, so both go on **before** the merge, -together, through the Neon connector: the DDL taken from the model, the database's state read -first, and `alembic_version` stamped to `0016` in the same transaction. On 25 September -production read `0014`, with **0** rows in `diary_sessions` and **1** class, so neither -revision had a row to touch. - -**Not applied, and held on purpose, as of 26 September.** The owner allowed both on one -condition: that the code they serve is free of defects. The audit of the server half and of -both revisions has finished since. 22 findings survived two refuters each, and `6b0878f` -fixed 21 of them. The revisions' PostgreSQL DDL came out of that unchanged, and it still -matches the models op by op, which `test_quota` and `test_diary_provider_revision` now pin. -The 22nd finding is **#165**: a session registered from a phone names its own login, and -the family's corrections are filed under it. Its fix is a product decision. The owner first -chose to key corrections on the account the diary vouches for, then stopped that -implementation before it changed a file, so the decision is open (`needs:owner`). Until it -closes, the condition is not met, so the transaction has not run and #140 does not merge; -merging without `0015` and `0016` would take the bot down. Neither revision depends on how -#165 is decided: two of its three answers need no schema, and the third would be an additive -`0017`. When it runs, this paragraph gets the time and what the database said. +- **`0017`** (`0017_corrections_per_child.py`) is data only (#165). It rewrites + `diary_overrides.login` from a login to the child's scope: `CHILD:petersburg`, or + `CHILD:netschool:` and the regional server's host. It deletes the branch-only + «Сетевой город» hash-keyed rows, which could no longer be read. Where two rows corrected + one field of one child, it keeps the newest. On PostgreSQL it takes a lock first. It is a + third shape, «a rewrite of a key»: free where there are no rows, and **after** the merge + where there are, for the reasons its docstring and `docs/deploy.md` give. + +`0015` and `0016` are additive, and rewrite and destroy no row. `0017` would destroy rows +only where there are corrections, and production had none. So all three went on **before** +the merge, together, through the Neon connector. The DDL was taken from the revisions +rendered offline for PostgreSQL, and it matched the models' own DDL statement for statement. +The database's state was read first, and `alembic_version` was stamped in the same +transaction, last. + +**Applied on 26 September 2026 at 12:26 UTC, before the merge, as one transaction through +the Neon connector.** The owner had allowed the migrations on one condition: that the code +they serve has no known defect. That was met once #165 was decided and fixed in `e01443d`, +and CI went green on that commit. The database was read twice first, at 11:22 and at 12:25 +UTC. Both reads showed head `0014`, none of the eight columns, no `usage_counters`, **0** +rows in `diary_overrides` (0 of them legacy «Сетевой город» keys), **0** diary sessions and +**1** class. The transaction ran the eight `ADD COLUMN`s of `0015` and the `CREATE TABLE` of +`0016`. Then `0017` ran its lock, its two deletes and its rewrite, and last came the stamp +`UPDATE alembic_version SET version_num = '0017' WHERE version_num = '0014'`. Every +statement was taken from the revisions rendered offline for PostgreSQL, which matched the +models' DDL. Read back afterwards: head `0017`, one stamp, all eight columns nullable with +the declared types and widths (`VARCHAR(32)`, `BIGINT`, `VARCHAR(300)`, `TIMESTAMP WITHOUT +TIME ZONE`), and `usage_counters` with primary key `(scope, day)`. There were still 0 +corrections, 0 sessions and 1 class, so nothing was rewritten and nothing was destroyed. +Until #140 merges and deploys, the running code is older than the database, and +`/api/v1/warmup` answers «База впереди кода…»: the window the correct order creates. The one +thing the window could lose is a correction typed through the old `/diary/login` before the +deploy, which would be filed under a login. No diary session existed to type one. ### What was deliberately left alone @@ -358,13 +373,15 @@ merging without `0015` and `0016` would take the bot down. Neither revision depe ### Gates -Run, not quoted. The server was run on the branch at `d208251`, against **SQLAlchemy +Run, not quoted. The server was run on the branch at `e01443d`, against **SQLAlchemy 2.1.1**, which is what CI and Vercel install now (#164): `ruff check app tests scripts -migrations` clean; `pytest -q -n auto` **1998** passed (1634 on `main`); `python -m mypy` -**Success** across **100** modules (84 on `main`). The Android tests were run at `061a716`, +migrations` clean; `pytest -q -n auto` **2024** passed (1634 on `main`); `python -m mypy` +**Success** across **100** modules (84 on `main`). The alembic chain from nothing lands on +`0017`. The Android tests were run at `061a716`, and Gradle found every test task up to date against the sources at `f31e5ed`: `./gradlew test` **1408** (968 on `main`), with `:app` 548, `:core:data` 532, `:core:designsystem` 99, -`:core:model` 125 and `:widget` 104. `assembleDebug` and `assembleRelease` were last run +`:core:model` 125 and `:widget` 104; they were rerun with `--rerun` after the texts of +#165's fix changed, with the same counts. `assembleDebug` and `assembleRelease` were last run locally at `061a716`, and CI builds both on every push. A checkout set up before 2.1 was published keeps SQLAlchemy 2.0.54 until it is upgraded. The suite passes on both, and a mypy run on 2.0 does not see what 2.1's typing sees. `b19e6b2` and `c032ff2` report the @@ -2749,7 +2766,7 @@ curl -s https://.vercel.app/api/v1/warmup # {"status":"ok","schema":" A `"degraded"` here would mean the deploy had not arrived; before `0013` was applied, the same request honestly called the database behind, because `EXPECTED_REVISION` was already -`0013`. The head is `0016` today — see the top of this file — and the same request reads it +`0013`. The head is `0017` today — see the top of this file — and the same request reads it the other way round while a revision waits for its merge: the database is *ahead* of the code, and `/warmup` says so in as many words, «База впереди кода…». @@ -2772,7 +2789,7 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 1998 tests, ~4 min (CI runs this) +cd server && pytest -q -n auto # 2024 tests, ~4 min (CI runs this) cd server && python -m mypy # clean, 100 modules cd android && ./gradlew test # 1408 tests across the five modules cd android && ./gradlew assembleDebug assembleRelease # both assembles @@ -2846,12 +2863,13 @@ parity was computed from the ISO week number, which does not alternate in a 53-w from January 2027 the whole denominator of the **current** school year slid by a week, simultaneously in the API, the widget, the digests and the calendar. -**Migrations:** the last revision written is `0016`, and production was read at `0014` on -25 September. `0007`–`0012` were applied **before** their merge through the Neon connector, -`0013` after it (it adds a `UNIQUE`, and a constraint migrates in the opposite direction -from a column), and `0014` before it again. `0015` and `0016`, both written on #140 and both -additive, go on before #140's merge; whether they have is in «Schema» in that batch's section -at the top of this file. What each earlier revision did is in `CLAUDE.md` and in section 7, +**Migrations:** the last revision written is `0017`, and production is at `0017`. +`0007`–`0012` were applied **before** their merge through the Neon connector, `0013` after it +(it adds a `UNIQUE`, and a constraint migrates in the opposite direction from a column), and +`0014` before it again. `0015`, `0016` and `0017`, all written on #140, went on before #140's +merge, in one transaction. `0017` rewrites a key, which on a database holding rows goes on +after the merge; production held none. «Schema» in that batch's section at the top of this +file has what the database said. What each earlier revision did is in `CLAUDE.md` and in section 7, item 1. --- @@ -3304,7 +3322,7 @@ title cannot. - **`/api/v1/warmup` has still not been read, and it is now known to be unreachable from a session rather than merely not done.** The deployments are behind Vercel's Deployment Protection and answer a redirect to a login page, so no `curl` from here can settle - whether the schema — `0016` once #140's revisions are on — and the code that needs it + whether the schema — `0017` once #140 has deployed — and the code that needs it met. It needs the owner's browser or a bypass token; it has been outstanding since #61 and it is in section 7 for that reason. - **`docker compose up` has never been run.** There is no Docker in this environment, so @@ -4178,7 +4196,7 @@ and the code that needs it actually met**, and it is outstanding since #61. It c closed from a session here at any effort: the deployments are behind Vercel's Deployment Protection and answer a redirect to a login page, so this needs the owner's own browser or a bypass token. The answer wanted once #140 has merged and deployed is -`{"status":"ok","api_version":1,"schema":"0016"}`; a +`{"status":"ok","api_version":1,"schema":"0017"}`; a `"degraded"` naming two revisions is the honest report of a migration and a deploy that have not met, and which way round it is, is in the `detail`. @@ -4273,7 +4291,7 @@ and that is the thing to decide rather than the ttl. ~~1a. **Apply `0013` after PR #45 is merged.**~~ Applied: head `0013`, the constraint in place, zero rows deleted (`homework` had none). 1b. **Open `/api/v1/warmup` and make sure the deploy arrived** — once #140 has merged and - deployed that is `{"status":"ok","schema":"0016"}` — and then send the bot `/start`: the + deployed that is `{"status":"ok","schema":"0017"}` — and then send the bot `/start`: the very first message goes through the middleware that reads a class, and that is the fastest check that the schema and the code agree. That is all that is left of item 1; it needs a live service, and since the deployments sit behind Deployment Protection it needs a browser diff --git a/README.md b/README.md index d44ebefd..12ac588b 100644 --- a/README.md +++ b/README.md @@ -452,10 +452,10 @@ one of them is proved by a test rather than by a screen. Robolectric, against a fake. Which of the four a phone shows when pointed at production, nobody has watched. * **`/api/v1/warmup` itself has not been read since #61**, when it answered - `{"status":"ok","api_version":1,"schema":"0013"}`. Production was last recorded at `0014`; - the code on this branch expects `0017`, and `0015`, `0016` and `0017` are to be applied - before #140 merges — production holds no diary corrections, so `0017` has nothing to - rewrite there — after which it should say `0017`. That one request is the cheapest check + `{"status":"ok","api_version":1,"schema":"0013"}`. Production is at `0017` since 26 + September 2026, 12:26 UTC: `0015`, `0016` and `0017` went on together before #140's + merge, and `0017` found no diary correction to rewrite. Once #140 has deployed it should + say `0017`. That one request is the cheapest check of whether the migrations and the code that needs them actually met — but the deployment previews sit behind Vercel's protection, and nobody has made the check against production either. diff --git a/docs/deploy.md b/docs/deploy.md index bb35303b..1efe9b77 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -346,8 +346,8 @@ child, and rewrites the rest of the old Petersburg rows to `CHILD:petersburg`. I docstring carries the two counts to read before the transaction, one per destructive step. On PostgreSQL it first locks the table against writes until it commits, so a correction saved while it runs waits instead of making it roll back. On production, read on 26 -September with no correction in it, that is nothing, and it goes on with `0015` and `0016` -before the merge. On a deployment that holds corrections it is better applied just +September with no correction in it, that was nothing: it went on with `0015` and `0016` +before the merge, at 12:26 UTC that day. On a deployment that holds corrections it is better applied just **after** the merge — see the third shape below. Its downgrade does nothing, on purpose — a login cannot be recovered from a scope, and the old code cannot read or write an upper-case scope under any login — but a revert is not lossless: what older code writes @@ -401,7 +401,7 @@ files it under the child and the value comes back for everyone who sees the chil still the smaller loss, so it is the order for a deployment that holds corrections — with the window kept to minutes, and with `/api/v1/warmup` saying «База отстала от кода» through it, which there is expected. Where there is nothing to rewrite — production, on 26 -September — the order is free, and it goes on with the additive revisions before the merge, +September — the order is free, and it went on with the additive revisions before the merge, which keeps `/api/v1/warmup` level. That the database really has caught up with the code is shown by `alembic current` — it @@ -424,8 +424,8 @@ a ping meant to warm things up would keep waking a sleeping Neon. ### What to apply them with In practice this project's migrations are applied **through the Neon connector** rather than -with the `alembic` command — that is how `0005`–`0014` were applied, and how `0015`, -`0016` and `0017` are to go on before #140 merges. The Neon project is +with the `alembic` command — that is how `0005`–`0017` were applied, the last three +together on 26 September 2026, before #140 merged. The Neon project is called `lessons`; its identifier is not kept in the repository — anybody with access sees it in the Neon console anyway, and in a public repository it is just the address of somebody else's database.