"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4.""" import dataclasses import http.client import json import pathlib import typing import urllib.error import urllib.parse import urllib.request from failure import Failure from project_config.main import located KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT") # Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly. TIMEOUT = 10 # Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] class NoRedirect(urllib.request.HTTPRedirectHandler): """Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https.""" def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None: return None OPENER = urllib.request.build_opener(NoRedirect) @dataclasses.dataclass(frozen=True) class Config: url: str token: str recipient: str def read_config(path: pathlib.Path) -> Config | Failure: """The server, bot token and recipient that path's KEY=value lines hold.""" try: mode = path.stat().st_mode text = path.read_text(encoding="utf-8") except FileNotFoundError: return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}") except (OSError, UnicodeDecodeError) as failure: return Failure(f"cannot read {path}: {failure}") if mode & 0o077: return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}") values = parse_env(text) if missing := [key for key in KEYS if not values.get(key)]: return Failure(f"{path} lacks {' and '.join(missing)}") url, token, recipient = (values[key] for key in KEYS) if not url.startswith("https://"): return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear") return Config(url.rstrip("/"), token, recipient) def parse_env(text: str) -> dict[str, str]: values = {} for line in text.splitlines(): key, equals, value = line.partition("=") if not equals or key.lstrip().startswith("#"): continue value = value.strip() if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": value = value[1:-1] values[key.strip()] = value return values def send(config: Config, message: str, http: Http) -> Failure | None: api = f"{config.url}/api/v4" bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me") if isinstance(bot, Failure): return bot recipient = id_of(http("GET", f"{api}/users/username/{urllib.parse.quote(config.recipient)}", config.token, None), f"GET /api/v4/users/username/{config.recipient}") if isinstance(recipient, Failure): return recipient channel = id_of(http("POST", f"{api}/channels/direct", config.token, [bot, recipient]), "POST /api/v4/channels/direct") if isinstance(channel, Failure): return channel posted = id_of(http("POST", f"{api}/posts", config.token, {"channel_id": channel, "message": message}), "POST /api/v4/posts") return posted if isinstance(posted, Failure) else None def id_of(answer: object, request: str) -> str | Failure: if isinstance(answer, Failure): return answer found = answer.get("id") if isinstance(answer, dict) else None return found if isinstance(found, str) and found else Failure(f"{request} answered without an id") def http_json(method: str, url: str, token: str, body: object) -> object: """The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON.""" request_name = f"{method} {urllib.parse.urlsplit(url).path}" data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method) try: with OPENER.open(request, timeout=TIMEOUT) as response: raw = response.read() except urllib.error.HTTPError as failure: with failure: return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}") except http.client.HTTPException as failure: return Failure(f"{request_name} got a broken answer: {failure!r}") except (OSError, ValueError) as failure: server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", "")) return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}") try: return json.loads(raw) except ValueError: return Failure(f"{request_name} answered with something other than JSON") def error_message(failure: urllib.error.HTTPError) -> str: """Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none.""" try: answer = json.loads(failure.read()) except (http.client.HTTPException, OSError, ValueError): return "" message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else "" def dm(text: str, directory: str | None, home: pathlib.Path, http: Http) -> Failure | None: """Sends text to the recipient that the project's env file names. The project is the one whose checkout holds directory, and its config names the file. The DM is skipped where the config sets no env-file, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no file to read the recipient from.""" project = located(directory, home) if isinstance(project, Failure) or project.env_file is None: return None config = read_config(project.env_file) return config if isinstance(config, Failure) else send(config, text, http) def config_of(directory: str | None, home: pathlib.Path) -> Config | Failure: """The server, token and recipient in the env file that the config of the project holding directory names.""" project = located(directory, home) if isinstance(project, Failure): return project if project.env_file is None: return Failure(f"{project.folder / 'config.toml'} sets no `env-file`; set it to the file that holds {', '.join(KEYS[:-1])} and {KEYS[-1]}") return read_config(project.env_file)