diff --git a/orchestrator/kvb_orchestrator/accounts_io.py b/orchestrator/kvb_orchestrator/accounts_io.py new file mode 100644 index 0000000..85d9524 --- /dev/null +++ b/orchestrator/kvb_orchestrator/accounts_io.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +import base64 +import binascii +import csv +import datetime +import hashlib +import io +import json +import re + +from .accounts import KEYS, valid_account +from .errors import Conflict, ToolError +from .fields import decode +from .ledger import Ledger +from .settings import section + +FORMATS = {"csv": (",", "text/csv; charset=utf-8"), "tsv": ("\t", "text/tab-separated-values; charset=utf-8")} +SEPARATORS = (",", ";", "\t") +HEADER = ("provider", "email", "renewal_day", "renewal_time", "reset_day", "reset_time", "resubscribe", "autorenew", "limit", "note") +MAPPED = ("provider", "email", "renewal", "renewal_day", "renewal_time", "reset", "reset_day", "reset_time", "resubscribe", "autorenew", "limit", "note") +LABELS = {"provider": "Provider", "email": "Email", "renewal": "Renewal", "reset": "Next reset", "resubscribe": "Resubscribe", "autorenew": "Autorenew", "limit": "Weekly token limit", "note": "Note"} +MOMENTS = ("renewal", "reset") +REQUIRED = ("provider", "email", *MOMENTS) +SHORT_DAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") +DAY_WORDS = ( + ("sun", "sunday", "so", "sonntag"), + ("mon", "monday", "mo", "montag"), + ("tue", "tuesday", "di", "dienstag"), + ("wed", "wednesday", "mi", "mittwoch"), + ("thu", "thursday", "do", "donnerstag"), + ("fri", "friday", "fr", "freitag"), + ("sat", "saturday", "sa", "samstag"), +) +WEEKDAYS = {word: index for index, words in enumerate(DAY_WORDS) for word in (*words, str(index))} +YES = ("yes", "true", "1", "ja") +NO = ("no", "false", "0", "nein", "") +CLOCK = re.compile(r"([0-9]{1,2}):([0-5][0-9])") +WHOLE = re.compile(r"[0-9]{1,16}") +INJECTION = ("=", "+", "-", "@", "\t", "\r") +GUARD = "'" +FILE_LIMIT = 256 << 10 +ROW_LIMIT = 500 +CHOICES = ("overwrite", "keep") +PREVIEW_KEYS = ("file", "separator", "mapping", "choices") +APPLY_KEYS = (*PREVIEW_KEYS, "digest") +DIGEST_LENGTH = 32 + + +def guarded(value: str) -> str: + return f"{GUARD}{value}" if value.startswith(INJECTION) else value + + +def unguarded(value: str) -> str: + return value[1:] if value.startswith(GUARD) and value[1:].startswith(INJECTION) else value + + +def exported_row(account: dict) -> list[str]: + limit = "" if account["limit"] is None else str(account["limit"]) + cells = [account["provider"], account["email"]] + for name in MOMENTS: + cells += [SHORT_DAYS[account[name]["day"]], account[name]["time"]] + cells += [account["resubscribe"], "yes" if account["autorenew"] else "no", limit, account["note"]] + return [guarded(cell) for cell in cells] + + +def export(accounts: list[dict], fmt: str) -> tuple[str, bytes]: + """Args: + accounts: the stored accounts in table order. + fmt: csv or tsv; anything else raises ToolError. + + Returns: + (content type, file bytes): HEADER and one line per account, every + cell starting with a formula character prefixed with a quote. + """ + if fmt not in FORMATS: + raise ToolError(f"format must be one of {', '.join(FORMATS)}") + separator, content_type = FORMATS[fmt] + out = io.StringIO() + writer = csv.writer(out, delimiter=separator, lineterminator="\r\n") + writer.writerow(HEADER) + writer.writerows(exported_row(account) for account in accounts) + return content_type, out.getvalue().encode("utf-8") + + +def file_text(encoded: object) -> str: + """Returns: + The file's text without a leading byte order mark; a file that is no + base64, over FILE_LIMIT or not UTF-8 raises ToolError. + """ + if not isinstance(encoded, str): + raise ToolError("file must be the file's bytes in base64") + try: + data = base64.b64decode(encoded, validate=True) + except (binascii.Error, ValueError): + raise ToolError("file must be the file's bytes in base64") from None + if len(data) > FILE_LIMIT: + raise ToolError(f"the file is larger than {FILE_LIMIT >> 10} KiB") + try: + return data.decode("utf-8-sig") + except UnicodeDecodeError: + raise ToolError("the file is not UTF-8 text") from None + + +def detected(text: str) -> str: + first = text.split("\n", 1)[0] + counts = {separator: first.count(separator) for separator in SEPARATORS} + best = max(SEPARATORS, key=lambda separator: counts[separator]) + return best if counts[best] else "," + + +def separator_of(requested: object, text: str) -> str: + if requested == "": + return detected(text) + if requested not in SEPARATORS: + raise ToolError("separator must be empty, a comma, a semicolon or a tab") + return requested + + +def table(text: str, separator: str) -> tuple[list[str], list[list[str]]]: + """Returns: + (header, rows): the first line and every non-empty line after it; + more than ROW_LIMIT rows or broken quoting raises ToolError. + """ + try: + lines = [row for row in csv.reader(io.StringIO(text, newline=""), delimiter=separator) if any(cell.strip() for cell in row)] + except csv.Error as error: + raise ToolError(f"the file is no valid table: {error}") from None + if not lines: + raise ToolError("the file has no header line") + if len(lines) - 1 > ROW_LIMIT: + raise ToolError(f"the file has more than {ROW_LIMIT} rows") + return [cell.strip() for cell in lines[0]], lines[1:] + + +def proposed(columns: list[str]) -> dict[str, int | None]: + """Returns: + Per field of MAPPED the first column whose header equals the field + name or its table label, ignoring case, else None. + """ + lowered = [column.lower() for column in columns] + found: dict[str, int | None] = {} + for name in MAPPED: + names = {name, LABELS.get(name, name).lower()} + found[name] = next((index for index, column in enumerate(lowered) if column in names), None) + return found + + +def requested_mapping(raw: object, columns: list[str]) -> dict[str, int | None]: + if raw is None: + return proposed(columns) + data = section(raw, "mapping", MAPPED) + for name, index in data.items(): + if index is not None and (isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < len(columns)): + raise ToolError(f"mapping.{name} must be a column number from 0 to {len(columns) - 1} or null") + return data + + +def missing(mapping: dict[str, int | None]) -> list[str]: + absent = [name for name in ("provider", "email") if mapping[name] is None] + split = [name for name in MOMENTS if mapping[name] is None and None in (mapping[f"{name}_day"], mapping[f"{name}_time"])] + return [name for name in REQUIRED if name in absent or name in split] + + +def cell(row: list[str], index: int | None) -> str | None: + if index is None: + return None + return unguarded(row[index].strip()) if index < len(row) else "" + + +def weekday(value: str, column: str) -> int: + day = WEEKDAYS.get(value.strip().lower()) + if day is None: + raise ToolError(f"column {column}: no weekday from 0 (Sunday) to 6 or a day name") + return day + + +def clock(value: str, column: str) -> str: + match = CLOCK.fullmatch(value.strip()) + if match is None or int(match.group(1)) > 23: + raise ToolError(f"column {column}: no time HH:MM") + return f"{int(match.group(1)):02d}:{match.group(2)}" + + +def moment_of(row: list[str], mapping: dict[str, int | None], columns: list[str], name: str) -> dict: + day_index, time_index = mapping[f"{name}_day"], mapping[f"{name}_time"] + if day_index is not None and time_index is not None: + return {"day": weekday(cell(row, day_index), columns[day_index]), "time": clock(cell(row, time_index), columns[time_index])} + index = mapping[name] + parts = cell(row, index).rsplit(None, 1) + if len(parts) != 2: + raise ToolError(f"column {columns[index]}: no weekday and time like Mon 09:00") + return {"day": weekday(parts[0], columns[index]), "time": clock(parts[1], columns[index])} + + +def autorenew_of(value: str | None, column: str) -> bool: + lowered = (value or "").lower() + if lowered in YES: + return True + if lowered in NO: + return False + raise ToolError(f"column {column}: no yes/no, true/false, 1/0 or ja/nein") + + +def limit_of(value: str | None, column: str) -> int | None: + if not value: + return None + if not WHOLE.fullmatch(value): + raise ToolError(f"column {column}: no whole number of tokens") + return int(value) + + +def column_name(columns: list[str], index: int | None) -> str: + return "-" if index is None else columns[index] + + +def account_of(row: list[str], mapping: dict[str, int | None], columns: list[str]) -> dict: + """Returns: + The row as valid_account() accepts it, absent optional fields empty; + a cell that cannot be read raises ToolError naming its column. + """ + raw = {name: cell(row, mapping[name]) or "" for name in ("provider", "email", "resubscribe", "note")} + raw["renewal"], raw["reset"] = (moment_of(row, mapping, columns, name) for name in MOMENTS) + raw["autorenew"] = autorenew_of(cell(row, mapping["autorenew"]), column_name(columns, mapping["autorenew"])) + raw["limit"] = limit_of(cell(row, mapping["limit"]), column_name(columns, mapping["limit"])) + return valid_account(raw) + + +def parsed(rows: list[list[str]], mapping: dict[str, int | None], columns: list[str]) -> list[dict]: + found = [] + for number, row in enumerate(rows, start=2): + try: + found.append({"line": number, "account": account_of(row, mapping, columns), "error": None}) + except ToolError as error: + found.append({"line": number, "account": None, "error": str(error)}) + return found + + +def stored(account: dict) -> dict: + return {name: account[name] for name in KEYS} + + +def digest(accounts: list[dict]) -> str: + """Returns: + The digest of the stored accounts with their ids, for apply to + refuse a ledger that changed since the preview. + """ + canonical = json.dumps([{**stored(account), "id": account["id"]} for account in accounts], sort_keys=True) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:DIGEST_LENGTH] + + +def duplicates(found: list[dict]) -> None: + lines: dict[str, list[int]] = {} + for entry in found: + if entry["account"] is not None: + lines.setdefault(entry["account"]["email"].lower(), []).append(entry["line"]) + for entry in found: + twins = lines.get(entry["account"]["email"].lower(), []) if entry["account"] is not None else [] + if len(twins) > 1: + entry.update(account=None, error=f"email appears in lines {', '.join(map(str, twins))}") + + +def choices_of(raw: object) -> dict[str, str]: + if not isinstance(raw, dict) or any(not isinstance(email, str) or choice not in CHOICES for email, choice in raw.items()): + raise ToolError(f"choices must map an email to one of {', '.join(CHOICES)}") + return {email.lower(): choice for email, choice in raw.items()} + + +def classified(entry: dict, known: dict[str, dict], choices: dict[str, str]) -> dict: + if entry["error"] is not None: + return {"line": entry["line"], "status": "error", "error": entry["error"]} + account = entry["account"] + email = account["email"].lower() + existing = known.get(email) + if existing is None: + return {"line": entry["line"], "status": "new", "account": account} + changed = [name for name in KEYS if stored(existing)[name] != account[name]] + if not changed: + return {"line": entry["line"], "status": "unchanged", "account": account, "id": existing["id"]} + return {"line": entry["line"], "status": "update", "account": account, "id": existing["id"], "changed": changed, "choice": choices.get(email, "overwrite")} + + +def preview(body: dict, accounts: list[dict]) -> dict: + """Args: + body: {file, separator, mapping, choices}: file the bytes in base64, + separator "" to detect it, mapping null for the proposal else + a column number or null per field of MAPPED, choices overwrite + or keep per conflicting email. + accounts: the stored accounts. + + Returns: + {separator, columns, mapping, missing, rows, errors, digest}: each + row {line, status new|update|unchanged|error, account?, id?, + changed?, choice?, error?}; rows stay empty while a required field + is missing. + """ + text = file_text(body["file"]) + separator = separator_of(body["separator"], text) + columns, rows = table(text, separator) + mapping = requested_mapping(body["mapping"], columns) + choices = choices_of(body["choices"]) + absent = missing(mapping) + found = [] if absent else parsed(rows, mapping, columns) + duplicates(found) + known = {account["email"].lower(): account for account in accounts} + classes = [classified(entry, known, choices) for entry in found] + errors = sum(entry["status"] == "error" for entry in classes) + return {"separator": separator, "columns": columns, "mapping": mapping, "missing": absent, "rows": classes, "errors": errors, "digest": digest(accounts)} + + +def planned(result: dict) -> tuple[dict[str, dict], list[dict], dict]: + """Returns: + (changes by id, additions, counts): the overwrite updates, the new + accounts and how many rows were added, updated, kept and unchanged; + a missing field or an error row raises ToolError. + """ + if result["missing"] or result["errors"]: + raise ToolError("the import has missing fields or error rows; fix them in the preview first") + rows = result["rows"] + changes = {row["id"]: row["account"] for row in rows if row["status"] == "update" and row["choice"] == "overwrite"} + additions = [row["account"] for row in rows if row["status"] == "new"] + kept = sum(row["status"] == "update" and row["choice"] == "keep" for row in rows) + unchanged = sum(row["status"] == "unchanged" for row in rows) + return changes, additions, {"added": len(additions), "updated": len(changes), "kept": kept, "unchanged": unchanged} + + +class Transfer: + def __init__(self, ledger: Ledger) -> None: + self.ledger = ledger + + def exported(self, fmt: str, today: datetime.date) -> tuple[str, bytes, str]: + """Returns: + (content type, file bytes, file name accounts-.). + """ + content_type, data = export(self.ledger.listed(), fmt) + return content_type, data, f"accounts-{today.isoformat()}.{fmt}" + + def preview(self, body: bytes) -> dict: + return preview(section(decode(body), "body", PREVIEW_KEYS), self.ledger.listed()) + + def apply(self, body: bytes) -> dict: + """Args: + body: the preview's body plus digest, the preview's ledger digest. + + Returns: + The counts of planned(); the rows land in one ledger write, or + none: an error row raises ToolError, a ledger changed since the + preview raises Conflict. + """ + data = section(decode(body), "body", APPLY_KEYS) + accounts = self.ledger.listed() + changes, additions, counts = planned(preview(data, accounts)) + + def unchanged(current: list[dict]) -> None: + if digest(current) != data["digest"]: + raise Conflict({"reason": "the accounts changed since the preview", "digest": digest(current)}) + + self.ledger.batch(unchanged, changes, additions) + return counts diff --git a/orchestrator/kvb_orchestrator/handler.py b/orchestrator/kvb_orchestrator/handler.py index 22277dd..0af9a2d 100644 --- a/orchestrator/kvb_orchestrator/handler.py +++ b/orchestrator/kvb_orchestrator/handler.py @@ -1,5 +1,6 @@ from __future__ import annotations +import datetime import re import secrets import time @@ -7,9 +8,11 @@ from collections.abc import Callable from http import HTTPStatus from urllib.parse import urlsplit +from .accounts_io import Transfer from .diffs import DIFF_BODY_LIMIT from .engines import INPUT_LIMIT, STT_LIMIT from .exchange import PLAIN_CSP, Exchange +from .fields import single from .rates import rated from .resources import RESOURCES, sampled from .scores import scored @@ -82,8 +85,10 @@ FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPSta WAV_POSTS = (STT_ROUTE, VOICE_ROUTE) ACCOUNTS_ROUTE = "/api/accounts" ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete") +ACCOUNTS_EXPORT = "/api/accounts/export" +ACCOUNTS_IMPORT = {"/api/accounts/import/preview": "preview", "/api/accounts/import/apply": "apply"} SCHEDULES_ROUTE = "/api/schedules" -ACTION_POSTS = (ACCOUNTS_ROUTE, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS) +ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS) class Handler(Exchange): @@ -95,6 +100,14 @@ class Handler(Exchange): def hear(self, body: bytes) -> None: self.answer(lambda: self.server.hub.speech.transcribe(body), HTTPStatus.OK) + def export_accounts(self) -> None: + transfer = Transfer(self.server.hub.accounts.ledger) + self.attempt(lambda: transfer.exported(single(self.query(), "format") or "", datetime.date.today()), self.send_file) + + def send_file(self, exported: tuple[str, bytes, str]) -> None: + content_type, data, name = exported + self.send(HTTPStatus.OK, content_type, data, {"Content-Security-Policy": PLAIN_CSP, "Content-Disposition": f'attachment; filename="{name}"'}) + def replay_voice(self, note_id: str) -> None: headers = {"Content-Security-Policy": PLAIN_CSP} self.attempt(lambda: self.server.hub.voice_notes.audio(note_id), lambda wav: self.send(HTTPStatus.OK, WAV_TYPE, wav, headers)) @@ -148,6 +161,8 @@ class Handler(Exchange): self.answer(hub.match_cards, HTTPStatus.OK) elif path == ACCOUNTS_ROUTE: self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK) + elif path == ACCOUNTS_EXPORT: + self.export_accounts() elif path == "/api/resources": self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK) elif path == "/api/scores": @@ -194,6 +209,9 @@ class Handler(Exchange): drop = ACCOUNT_DROP.fullmatch(path) if path == ACCOUNTS_ROUTE: return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK) + if path in ACCOUNTS_IMPORT: + method = getattr(Transfer(hub.accounts.ledger), ACCOUNTS_IMPORT[path]) + return lambda body: self.answer(lambda: method(body), HTTPStatus.OK) if drop: return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK) if path == SCHEDULES_ROUTE: diff --git a/orchestrator/kvb_orchestrator/ledger.py b/orchestrator/kvb_orchestrator/ledger.py index 855ceca..aeddc83 100644 --- a/orchestrator/kvb_orchestrator/ledger.py +++ b/orchestrator/kvb_orchestrator/ledger.py @@ -10,6 +10,13 @@ from .diffs import SEALED_SUFFIX from .records import read_json, stamp, write_atomic +def unused(items: dict[str, dict]) -> str: + item_id = secrets.token_hex(8) + while item_id in items: + item_id = secrets.token_hex(8) + return item_id + + class Ledger: def __init__(self, file: Path) -> None: self.file = file @@ -20,10 +27,24 @@ class Ledger: def fresh(self) -> str: with self.changed: - item_id = secrets.token_hex(8) - while item_id in self.items: - item_id = secrets.token_hex(8) - return item_id + return unused(self.items) + + def batch(self, check: Callable[[list[dict]], None], changes: dict[str, dict], added: list[dict]) -> None: + """Args: + check: raises to refuse the whole batch; it sees every record + under the lock the write holds. + changes: fields merged into the record of each id, which keeps + its id and created stamp. + added: new records, each under a fresh id. + """ + with self.changed: + check(self.listed()) + items = {**self.items, **{item_id: {**self.items[item_id], **fields} for item_id, fields in changes.items()}} + created = stamp() + for fields in added: + item_id = unused(items) + items[item_id] = {**fields, "id": item_id, "created": created} + self.write(items) def write(self, items: dict[str, dict]) -> None: write_atomic(self.file, json.dumps(items, indent=1, sort_keys=True).encode("utf-8")) diff --git a/orchestrator/templates/page-accounts.js b/orchestrator/templates/page-accounts.js index c0b4d73..7e757ed 100644 --- a/orchestrator/templates/page-accounts.js +++ b/orchestrator/templates/page-accounts.js @@ -8,10 +8,38 @@ accountsView.body = body; const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only"); const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"}, - h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body); + h("div", {class: "res-head", "data-legend-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), + accountsExportMenu(), accountsImportButton(), add), body); return {panel, body}; } + function accountsExportMenu() { + const link = (format, label) => h("a", {class: "menu-item", href: `/api/accounts/export?format=${format}`, download: "", "data-export": format, ...named(label, `${label}: download every stored account; the hub keeps no copy`)}, label); + return h("details", {class: "menu acc-export"}, h("summary", {class: "btn small soft icon-only", ...named("Export accounts", "Export: download the accounts as CSV or TSV")}, icon("bi-download")), + h("div", {class: "menu-box end", role: "group", "aria-label": "Export format"}, link("csv", "CSV"), link("tsv", "TSV"))); + } + + function accountsImportButton() { + const picker = h("input", {type: "file", accept: ".csv,.tsv,.txt,text/csv,text/tab-separated-values", hidden: true, "aria-label": "Import file", "data-import-file": ""}); + picker.addEventListener("change", async () => { + const file = picker.files[0]; + picker.value = ""; + if (file) { + accountImportSheet(file.name, bytesBase64(await file.arrayBuffer())); + } + }); + return h("span", {class: "acc-import"}, picker, iconBtn("bi-upload", "Import accounts", "btn small soft", () => picker.click(), "Import: a CSV or TSV file, mapped to the fields and previewed before anything is saved")); + } + + function bytesBase64(buffer) { + const bytes = new Uint8Array(buffer); + let binary = ""; + for (let start = 0; start < bytes.length; start += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(start, start + 0x8000)); + } + return btoa(binary); + } + async function fetchAccounts() { if (accountsView.busy) { return; @@ -87,6 +115,101 @@ return h("div", {class: "acc-body"}, accountsContent(accountsView.data)); } + const IMPORT_FIELDS = [ + ["provider", "Provider"], ["email", "Email"], ["renewal", "Renewal (day and time)"], ["renewal_day", "Renewal day"], ["renewal_time", "Renewal time"], + ["reset", "Next reset (day and time)"], ["reset_day", "Reset day"], ["reset_time", "Reset time"], ["resubscribe", "Resubscribe"], ["autorenew", "Autorenew"], + ["limit", "Weekly token limit"], ["note", "Note"], + ]; + const IMPORT_SEPARATORS = [["", "Detect"], [",", "Comma"], [";", "Semicolon"], ["\t", "Tab"]]; + + function accountImportSheet(name, file) { + const state = {file, separator: "", mapping: null, choices: {}, result: null}; + const box = h("div", {class: "acc-import-body"}, h("p", {class: "muted"}, "…")); + const run = async () => { + const result = await sendJson("/api/accounts/import/preview", {file: state.file, separator: state.separator, mapping: state.mapping, choices: state.choices}); + if (!result.ok) { + box.replaceChildren(h("p", {class: "muted", "data-import-refused": ""}, fail(result)[0])); + return; + } + state.result = result.data; + box.replaceChildren(...importContent(state, run)); + }; + openSheet(`Import accounts: ${name}`, [h("p", {class: "muted"}, "Nothing is saved before Apply; accounts not in the file stay."), box], true); + run(); + } + + function importMapping(state, run) { + const {columns, mapping} = state.result; + const select = (field, label) => h("label", {class: "acc-field"}, h("span", {}, label), h("select", {class: "field", "aria-label": `${label} column`, "data-map": field, on: {change: (event) => { + state.mapping = {...state.result.mapping, [field]: event.target.value === "" ? null : Number(event.target.value)}; + run(); + }}}, h("option", {value: ""}, "not in file"), columns.map((column, index) => h("option", {value: String(index), ...(mapping[field] === index ? {selected: true} : {})}, column || `column ${index + 1}`)))); + const separator = h("label", {class: "acc-field"}, h("span", {}, "Separator"), h("select", {class: "field", "aria-label": "Separator", "data-separator": "", on: {change: (event) => { + state.separator = event.target.value; + state.mapping = null; + run(); + }}}, IMPORT_SEPARATORS.map(([value, label]) => h("option", {value, ...(state.separator === value ? {selected: true} : {})}, label)))); + return h("div", {class: "acc-form"}, separator, IMPORT_FIELDS.map(([field, label]) => select(field, label))); + } + + function importChoice(state, row, run) { + if (row.status !== "update") { + return null; + } + const email = row.account.email; + return h("select", {class: "field", "aria-label": `Conflict ${email}`, "data-choice": email, on: {change: (event) => { + state.choices = {...state.choices, [email]: event.target.value}; + run(); + }}}, ["overwrite", "keep"].map((choice) => h("option", {value: choice, ...(row.choice === choice ? {selected: true} : {})}, choice))); + } + + function importRow(state, row, run) { + const detail = row.status === "error" ? row.error : row.status === "update" ? row.changed.join(", ") : ""; + const who = row.account ? `${row.account.provider} · ${row.account.email}` : "–"; + return h("tr", {"data-import-row": row.status}, h("td", {}, String(row.line)), h("td", {}, h("span", {class: "pill", "data-tone": row.status === "error" ? "bad" : "ok"}, row.status)), + h("td", {}, who), h("td", {}, detail), h("td", {}, importChoice(state, row, run))); + } + + function importAll(state, run) { + const updates = state.result.rows.filter((row) => row.status === "update"); + if (!updates.length) { + return null; + } + const all = (choice) => btn(`All ${choice}`, "btn small ghost", () => { + state.choices = Object.fromEntries(updates.map((row) => [row.account.email, choice])); + run(); + }); + return h("div", {class: "actions", role: "group", "aria-label": "Every conflict"}, all("overwrite"), all("keep")); + } + + function importContent(state, run) { + const {rows, missing, errors} = state.result; + const blocked = missing.length > 0 || errors > 0 || rows.length === 0; + const apply = h("button", {type: "button", class: "btn primary", "data-import-apply": "", ...(blocked ? {disabled: true} : {})}, icon("bi-check-lg"), "Apply"); + apply.addEventListener("click", () => applyImport(state, run)); + const notice = missing.length ? h("p", {class: "muted", "data-import-missing": ""}, `Missing: ${missing.join(", ")}`) : null; + const table = rows.length ? h("div", {class: "acc-scroll"}, h("table", {class: "acc-table"}, + h("thead", {}, h("tr", {}, ["Line", "Status", "Account", "Changes or error", "Conflict"].map((label) => h("th", {scope: "col"}, label)))), + h("tbody", {}, rows.map((row) => importRow(state, row, run))))) : null; + return [importMapping(state, run), notice, importAll(state, run), table, h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), apply)]; + } + + async function applyImport(state, run) { + const result = await sendJson("/api/accounts/import/apply", {file: state.file, separator: state.separator, mapping: state.result.mapping, choices: state.choices, digest: state.result.digest}); + if (result.status === 409) { + toast("Import: the accounts changed meanwhile", ["The preview was refreshed; check it and apply again."], false); + run(); + return; + } + if (!result.ok) { + toast("Import: not applied", fail(result), false); + return; + } + closeSheet(); + fetchAccounts(); + toast("Import applied", [`${result.data.added} added, ${result.data.updated} updated, ${result.data.kept} kept, ${result.data.unchanged} unchanged`], true); + } + function momentFields(label, moment) { const day = h("select", {class: "field", "aria-label": `${label} weekday`}, ACCOUNT_DAYS.map((name, index) => h("option", {value: String(index), ...(moment && moment.day === index ? {selected: true} : {})}, name))); const time = h("input", {type: "time", class: "field", "aria-label": `${label} time`, value: moment ? moment.time : "00:00"}); diff --git a/tests/e2e/test_accounts_import_e2e.py b/tests/e2e/test_accounts_import_e2e.py new file mode 100644 index 0000000..f3f1b66 --- /dev/null +++ b/tests/e2e/test_accounts_import_e2e.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import hub_e2e_kit as base +import test_resources_accounts_e2e as acc +import test_resources_view_e2e as res +import test_workbench_w4_e2e as w4 +from hub_case import HubCase + +OUT = acc.OUT +EMAIL = acc.EMAIL +ADDED = "two@example.org" +STORED = {"provider": "Anthropic", "email": EMAIL, "renewal": {"day": 1, "time": "09:00"}, "reset": {"day": 4, "time": "18:30"}, "resubscribe": "", "autorenew": True, "limit": None, "note": "old"} +FILE = f"provider,Contact,renewal,reset,note\nAnthropic,{EMAIL},Mon 09:00,Thu 18:30,new note\nOpenAI,{ADDED},Tue 10:00,Fri 12:00,fresh\n" +IMPORT = """(async () => {@HELPERS@@READ@@KIT@ + const apply = () => sheet().querySelector("[data-import-apply]"); + const choice = () => sheet().querySelector('[data-choice="@EMAIL@"]'); + const changed = (node, value) => { + node.value = value; + node.dispatchEvent(new Event("change", {bubbles: true})); + }; + if (!(await until(() => box() && rows().length === 2, 15000))) { + return {error: text(box()) || text(document.getElementById("main"))}; + } + const links = all("#main .res-accounts a[data-export]").map((link) => [link.dataset.export, link.getAttribute("href"), link.hasAttribute("download")]); + const exported = await (await fetch(links[0][1], {cache: "no-store"})).text(); + const picker = box().querySelector("[data-import-file]"); + const data = new DataTransfer(); + data.items.add(new File([@FILE@], "accounts.csv", {type: "text/csv"})); + picker.files = data.files; + picker.dispatchEvent(new Event("change", {bubbles: true})); + await until(() => !sheet().hidden && apply(), 5000); + const blocked = {disabled: apply().disabled, missing: text(sheet().querySelector("[data-import-missing]"))}; + changed(sheet().querySelector('[data-map="email"]'), "1"); + await until(() => choice(), 5000); + const statuses = all("[data-import-row]", sheet()).map((row) => row.dataset.importRow); + changed(choice(), "keep"); + await until(() => choice() && choice().value === "keep", 5000); + const ready = !apply().disabled; + let applied = null; + if (@APPLY@) { + apply().click(); + applied = Boolean(await until(() => sheet().hidden && rows().length === 3, 5000)); + } + return {links, exported, blocked, statuses, ready, applied, page: wide(), violations: window.e2eViolations || null}; +})()""" + + +def probe(apply: bool) -> str: + names = {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": acc.KIT, "@EMAIL@": EMAIL, "@FILE@": json.dumps(FILE), "@APPLY@": "true" if apply else "false"} + template = IMPORT + for key, value in names.items(): + template = template.replace(key, value) + return template + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestAccountsImport(HubCase): + drive = base.OrchestratorE2ECase.drive + sample = w4.TestWorkbenchResources.sample + + def setUp(self): + acc.TestResourcesAccounts.setUp(self) + status, _, answer = self.post_json("/api/accounts", {"id": "", "account": STORED}, self.guard(self.host)) + self.assertEqual(status, 200, answer) + + def steps(self, browser: str) -> list[dict]: + last = len(base.WIDTHS) - 1 + return [ + {"width": width, "height": height, "url": f"{self.base}?{width}#resources", "wait": 1200, "probe": probe(index == last), "shot": f"{OUT / f'{browser}-{width}'}-accounts-import.png"} + for index, (width, height) in enumerate(base.WIDTHS) + ] + + def check(self, data: dict, browser: str) -> None: + last = len(base.WIDTHS) - 1 + for index, ((width, _), found) in enumerate(zip(base.WIDTHS, data["results"], strict=True)): + with self.subTest(browser=browser, width=width): + self.assertNotIn("error", found, found) + self.assertEqual(found["links"], [["csv", "/api/accounts/export?format=csv", True], ["tsv", "/api/accounts/export?format=tsv", True]]) + self.assertTrue(found["exported"].startswith("provider,email,"), found["exported"]) + self.assertIn(EMAIL, found["exported"]) + self.assertEqual(found["blocked"], {"disabled": True, "missing": "Missing: email"}) + self.assertEqual(found["statuses"], ["update", "new"]) + self.assertTrue(found["ready"]) + self.assertEqual(found["applied"], True if index == last else None) + self.assertEqual(found["page"], {"wide": False}) + self.assertEqual(w4.quiet(found["violations"]), []) + stored = {account["email"]: account for account in self.httpd.hub.accounts.ledger.listed()} + self.assertEqual(sorted(stored), [EMAIL, ADDED]) + self.assertEqual(stored[EMAIL]["note"], "old") + self.assertEqual((stored[ADDED]["provider"], stored[ADDED]["note"]), ("OpenAI", "fresh")) + + def test_chromium_exports_and_imports_with_one_mapped_column_and_one_kept_conflict(self): + data = self.drive(self.steps("chromium"), None, init=w4.GUARD) + (OUT / "chromium-accounts-import.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_exports_and_imports_with_one_mapped_column_and_one_kept_conflict(self): + data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD) + (OUT / "firefox-accounts-import.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check(data, "firefox") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_accounts_io.py b/tests/test_hub_accounts_io.py new file mode 100644 index 0000000..0824653 --- /dev/null +++ b/tests/test_hub_accounts_io.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import base64 +import json +import stat +import unittest + +from hub_case import HubCase +from kvb_orchestrator import accounts, accounts_io +from kvb_orchestrator.errors import ToolError + +ONE = { + "id": "a" * 16, "created": "2026-11-27T08:00:00+00:00", "provider": "Anthropic", "email": "a@example.org", + "renewal": {"day": 1, "time": "09:00"}, "reset": {"day": 3, "time": "18:30"}, "resubscribe": "", "autorenew": True, "limit": None, + "note": '=HYPERLINK("x")', +} +TWO = {**ONE, "id": "b" * 16, "email": "b@example.org", "autorenew": False, "limit": 5000, "note": "team seat"} +MINIMAL = "provider,email,renewal,reset\n" + + +def encoded(text: str) -> str: + return base64.b64encode(text.encode("utf-8")).decode() + + +def body(text: str, mapping: dict | None, separator: str, choices: dict) -> dict: + return {"file": encoded(text), "separator": separator, "mapping": mapping, "choices": choices} + + +def previewed(text: str, stored: list[dict]) -> dict: + return accounts_io.preview(body(text, None, "", {}), stored) + + +class TestExport(unittest.TestCase): + def test_csv_and_tsv_hold_the_header_one_line_per_account_and_guard_formulas(self): + for fmt, separator in (("csv", ","), ("tsv", "\t")): + with self.subTest(fmt=fmt): + kind, data = accounts_io.export([ONE, TWO], fmt) + lines = data.decode("utf-8").split("\r\n") + self.assertEqual(kind, accounts_io.FORMATS[fmt][1]) + self.assertEqual(lines[0], separator.join(accounts_io.HEADER)) + self.assertEqual(len([line for line in lines if line]), 3) + self.assertIn("Mon", lines[1]) + self.assertIn("'=HYPERLINK", lines[1]) + with self.assertRaises(ToolError): + accounts_io.export([ONE], "xlsx") + + def test_an_exported_file_previews_every_row_unchanged_and_the_formula_comes_back_bare(self): + for fmt in accounts_io.FORMATS: + with self.subTest(fmt=fmt): + result = previewed(accounts_io.export([ONE, TWO], fmt)[1].decode(), [ONE, TWO]) + self.assertEqual([row["status"] for row in result["rows"]], ["unchanged", "unchanged"]) + self.assertEqual(result["rows"][0]["account"]["note"], '=HYPERLINK("x")') + + +class TestMapping(unittest.TestCase): + def test_the_table_labels_map_without_a_choice_and_unknown_headers_name_every_required_field(self): + mapping = accounts_io.proposed(["Provider", "Email", "Renewal", "Next reset"]) + self.assertEqual([mapping[name] for name in ("provider", "email", "renewal", "reset")], [0, 1, 2, 3]) + result = previewed("foo,bar\n1,2\n", []) + self.assertEqual((result["missing"], result["rows"]), (["provider", "email", "renewal", "reset"], [])) + + def test_each_separator_is_detected_and_a_requested_one_wins(self): + for separator in accounts_io.SEPARATORS: + with self.subTest(separator=repr(separator)): + self.assertEqual(previewed(f"a{separator}b\n", [])["separator"], separator) + self.assertEqual(accounts_io.preview(body("a,b;c\n", None, ";", {}), [])["separator"], ";") + with self.assertRaises(ToolError): + accounts_io.preview(body("a,b\n", None, "|", {}), []) + + def test_weekday_spellings_one_or_two_columns_and_bad_days_name_their_column(self): + self.assertEqual({accounts_io.weekday(word, "c") for word in ("0", "Sun", "Sunday", "So", "Sonntag")}, {0}) + one = previewed(f"{MINIMAL}X,c@example.org,Mon 09:00,Mon 10:00\n", [])["rows"][0]["account"] + two = previewed("provider,email,renewal_day,renewal_time,reset\nX,c@example.org,Mon,9:00,Mon 10:00\n", [])["rows"][0]["account"] + self.assertEqual(one["renewal"], two["renewal"]) + for bad in ("7 09:00", "Funday 09:00"): + with self.subTest(bad=bad): + row = previewed(f"{MINIMAL}X,c@example.org,{bad},Mon 10:00\n", [])["rows"][0] + self.assertEqual(row["status"], "error") + self.assertIn("column renewal", row["error"]) + + def test_absent_optional_columns_take_their_empty_values(self): + account = previewed(f"{MINIMAL}X,c@example.org,Mon 09:00,Mon 10:00\n", [])["rows"][0]["account"] + self.assertEqual((account["resubscribe"], account["autorenew"], account["limit"], account["note"]), ("", False, None, "")) + self.assertTrue(accounts_io.autorenew_of("ja", "c")) + with self.assertRaises(ToolError): + accounts_io.autorenew_of("maybe", "c") + + def test_an_oversized_long_or_non_utf8_file_parses_nothing(self): + big = MINIMAL + "x" * (accounts_io.FILE_LIMIT + 1) + long = MINIMAL + "X,c@example.org,Mon 09:00,Mon 10:00\n" * (accounts_io.ROW_LIMIT + 1) + for raw in (encoded(big), encoded(long), base64.b64encode(b"provider\n\xff\xfe\n").decode(), "not base64!"): + with self.subTest(raw=raw[:20]), self.assertRaises(ToolError): + accounts_io.preview({"file": raw, "separator": "", "mapping": None, "choices": {}}, []) + self.assertEqual(accounts_io.file_text(encoded(chr(0xFEFF) + "a,b")), "a,b") + + +class TestConflicts(unittest.TestCase): + def test_a_changed_known_email_is_an_update_with_its_fields_and_a_new_one_is_new(self): + text = f"{MINIMAL}Anthropic,a@example.org,Tue 09:00,Wed 18:30\nX,b@example.org,Mon 09:00,Mon 10:00\n" + rows = previewed(text, [ONE])["rows"] + self.assertEqual((rows[0]["status"], rows[0]["choice"], rows[0]["id"]), ("update", "overwrite", ONE["id"])) + self.assertIn("renewal", rows[0]["changed"]) + self.assertEqual(rows[1]["status"], "new") + + def test_two_rows_with_one_email_are_both_errors(self): + result = previewed(f"{MINIMAL}X,c@example.org,Mon 09:00,Mon 10:00\nY,C@example.org,Mon 09:00,Mon 10:00\n", []) + self.assertEqual(([row["status"] for row in result["rows"]], result["errors"]), (["error", "error"], 2)) + + def test_the_digest_follows_every_stored_field_and_id(self): + self.assertEqual(accounts_io.digest([ONE]), accounts_io.digest([dict(ONE)])) + self.assertNotEqual(accounts_io.digest([ONE]), accounts_io.digest([{**ONE, "note": "x"}])) + self.assertNotEqual(accounts_io.digest([ONE]), accounts_io.digest([{**ONE, "id": "c" * 16}])) + + +class TestTransferApi(HubCase): + def post(self, path: str, payload: object) -> tuple[int, bytes]: + status, _, answer = self.post_json(path, payload, self.guard(self.host)) + return status, answer + + def stored(self) -> list[dict]: + status, answer = self.post("/api/accounts", {"id": "", "account": {key: ONE[key] for key in accounts.KEYS}}) + self.assertEqual(status, 200, answer) + return [json.loads(answer)] + + def test_export_answers_an_attachment_without_writing_a_file(self): + self.stored() + before = sorted(path.name for path in self.state.iterdir()) + status, headers, data = self.get("/api/accounts/export?format=csv") + self.assertEqual(status, 200, data) + self.assertEqual(headers["content-type"], "text/csv; charset=utf-8") + self.assertRegex(headers["content-disposition"], r'attachment; filename="accounts-[0-9]{4}-[0-9]{2}-[0-9]{2}\.csv"') + self.assertEqual(headers["cache-control"], "no-store") + self.assertEqual(self.get("/api/accounts/export?format=tsv")[1]["content-type"], "text/tab-separated-values; charset=utf-8") + self.assertEqual(self.get("/api/accounts/export?format=xls")[0], 400) + self.assertEqual(sorted(path.name for path in self.state.iterdir()), before) + + def test_keep_and_overwrite_apply_in_one_write_and_unlisted_accounts_stay(self): + account = self.stored()[0] + self.post("/api/accounts", {"id": "", "account": {**{key: TWO[key] for key in accounts.KEYS}, "email": "z@example.org"}}) + text = f"{MINIMAL}Changed,a@example.org,Tue 09:00,Wed 18:30\nNew,b@example.org,Mon 09:00,Mon 10:00\n" + for choice, provider in (("keep", "Anthropic"), ("overwrite", "Changed")): + with self.subTest(choice=choice): + status, answer = self.post("/api/accounts/import/preview", body(text, None, "", {"a@example.org": choice})) + self.assertEqual(status, 200, answer) + status, answer = self.post("/api/accounts/import/apply", {**body(text, None, "", {"a@example.org": choice}), "digest": json.loads(answer)["digest"]}) + self.assertEqual(status, 200, answer) + listed = {row["email"]: row for row in json.loads(self.get("/api/accounts")[2])["accounts"]} + self.assertEqual((listed["a@example.org"]["provider"], listed["a@example.org"]["id"]), (provider, account["id"])) + self.assertIn("z@example.org", listed) + self.assertEqual(stat.S_IMODE((self.state / accounts.ACCOUNTS).stat().st_mode), 0o600) + + def test_an_error_row_or_a_stale_digest_leaves_the_file_byte_identical(self): + self.stored() + file = self.state / accounts.ACCOUNTS + before = file.read_bytes() + bad = body(f"{MINIMAL}X,c@example.org,Funday 09:00,Mon 10:00\n", None, "", {}) + self.assertEqual(self.post("/api/accounts/import/apply", {**bad, "digest": ""})[0], 400) + good = body(f"{MINIMAL}X,c@example.org,Mon 09:00,Mon 10:00\n", None, "", {}) + status, answer = self.post("/api/accounts/import/apply", {**good, "digest": "0" * accounts_io.DIGEST_LENGTH}) + self.assertEqual((status, json.loads(answer)["reason"]), (409, "the accounts changed since the preview")) + self.assertEqual(file.read_bytes(), before) + + +if __name__ == "__main__": + unittest.main()