alertiny 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
alertiny/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Client Python de l'API Alertiny."""
2
+
3
+ from .client import AlertinyClient, AlertinyError, AlertinyHTTPError, AlertinyNetworkError
4
+ from .models import JinjaValue, MailRequest, Recipient
5
+
6
+ __all__ = [
7
+ "AlertinyClient",
8
+ "AlertinyError",
9
+ "AlertinyHTTPError",
10
+ "AlertinyNetworkError",
11
+ "JinjaValue",
12
+ "MailRequest",
13
+ "Recipient",
14
+ ]
alertiny/__init__.pyi ADDED
@@ -0,0 +1,16 @@
1
+ """Alertiny SDK Python interface stub."""
2
+ from .client import AlertinyClient as AlertinyClient # pylint: disable=C0414
3
+ from .client import AlertinyError as AlertinyError # pylint: disable=C0414
4
+ from .client import AlertinyHTTPError as AlertinyHTTPError # pylint: disable=C0414
5
+ from .client import AlertinyNetworkError as AlertinyNetworkError # pylint: disable=C0414
6
+ from .models import JinjaValue as JinjaValue, MailRequest as MailRequest, Recipient as Recipient # pylint: disable=C0414
7
+
8
+ __all__ = [
9
+ "AlertinyClient",
10
+ "AlertinyError",
11
+ "AlertinyHTTPError",
12
+ "AlertinyNetworkError",
13
+ "JinjaValue",
14
+ "MailRequest",
15
+ "Recipient",
16
+ ]
alertiny/client.py ADDED
@@ -0,0 +1,151 @@
1
+ """Client HTTP pour les notifications Alertiny."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from dataclasses import asdict
8
+ from typing import Any, Mapping, cast
9
+ from urllib.error import HTTPError
10
+ from urllib.parse import quote, urlsplit
11
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
12
+
13
+ from .models import MailRequest
14
+
15
+ MAIL_PATH = "/api/v1/mails/"
16
+
17
+ class AlertinyError(Exception):
18
+ """Erreur du client Alertiny."""
19
+
20
+
21
+ class AlertinyHTTPError(AlertinyError):
22
+ """Erreur HTTP avec son statut et les détails renvoyés par l'API."""
23
+
24
+ def __init__(self, status: int, detail: Any) -> None:
25
+ super().__init__(f"Alertiny HTTP {status}")
26
+ self.status = status
27
+ self.detail = detail
28
+
29
+
30
+ class AlertinyNetworkError(AlertinyError):
31
+ """Erreur de transport ou réponse JSON invalide."""
32
+
33
+
34
+ class _NoRedirect(HTTPRedirectHandler):
35
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str,
36
+ headers: Any, newurl: str) -> None:
37
+ return None
38
+
39
+
40
+ def _redact(value: Any, token: str) -> Any:
41
+ if isinstance(value, str):
42
+ return value.replace(token, "[REDACTED]")
43
+ if isinstance(value, list):
44
+ return [_redact(item, token) for item in cast(list[Any], value)]
45
+ if isinstance(value, dict):
46
+ return {
47
+ _redact(key, token): _redact(item, token)
48
+ for key, item in cast(dict[Any, Any], value).items()
49
+ }
50
+ return value
51
+
52
+
53
+ class AlertinyClient:
54
+ """Accède à l'API mail V1 sans nouvelles tentatives automatiques.
55
+
56
+ Args:
57
+ base_url: URL du serveur, éventuellement avec un préfixe de chemin.
58
+ token: Jeton Bearer de l'API.
59
+ timeout: Délai réseau en secondes.
60
+ """
61
+
62
+ def __init__(self, base_url: str, token: str, timeout: float = 30.0) -> None:
63
+ parsed = urlsplit(base_url)
64
+ if (parsed.scheme not in ("http", "https") or not parsed.hostname
65
+ or parsed.username is not None or parsed.password is not None
66
+ or parsed.query or parsed.fragment):
67
+ raise ValueError("Invalid Alertiny base URL")
68
+ if not token or "\r" in token or "\n" in token:
69
+ raise ValueError("Invalid Bearer token")
70
+ if not math.isfinite(timeout) or timeout <= 0:
71
+ raise ValueError("Timeout must be positive")
72
+ self._base_url = base_url.rstrip("/")
73
+ self._token = token
74
+ self._timeout = timeout
75
+ self._opener = build_opener(_NoRedirect())
76
+
77
+ def _request(
78
+ self, method: str, path: str, payload: Mapping[str, Any] | None = None,
79
+ *, authenticated: bool = True,
80
+ ) -> Any:
81
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
82
+ headers = {"Accept": "application/json"}
83
+ if authenticated:
84
+ headers["Authorization"] = f"Bearer {self._token}"
85
+ if data is not None:
86
+ headers["Content-Type"] = "application/json"
87
+ request = Request(self._base_url + path, data=data,
88
+ headers=headers, method=method)
89
+ try:
90
+ with self._opener.open(request, timeout=self._timeout) as response:
91
+ return json.loads(response.read())
92
+ except HTTPError as error:
93
+ try:
94
+ body = json.loads(error.read())
95
+ detail = cast(
96
+ dict[str, Any],
97
+ body
98
+ ).get("detail", body) if isinstance(body, dict) else body
99
+ except ValueError:
100
+ detail = None
101
+ raise AlertinyHTTPError(error.code, _redact(detail, self._token)) from None
102
+ except (OSError, ValueError):
103
+ raise AlertinyNetworkError("Alertiny request failed or returned invalid JSON") from None
104
+
105
+ def create_mail(self, payload: Mapping[str, Any] | MailRequest) -> dict[str, Any]:
106
+ """Crée un brouillon et retourne son identifiant, son sujet et son HTML."""
107
+ return self._request(
108
+ "POST",
109
+ MAIL_PATH,
110
+ asdict(payload) if isinstance(payload, MailRequest) else payload,
111
+ )
112
+
113
+ def send_mail(self, payload: Mapping[str, Any] | MailRequest) -> dict[str, Any]:
114
+ """Met directement une notification en file pour son envoi automatique."""
115
+ return self._request(
116
+ "POST",
117
+ "/api/v1/mails/send",
118
+ asdict(payload) if isinstance(payload, MailRequest) else payload,
119
+ )
120
+
121
+ def list_mails(self) -> dict[str, Any]:
122
+ """Retourne les statuts publics des notifications."""
123
+ return self._request("GET", MAIL_PATH)
124
+
125
+ def get_mail(self, mail_id: str) -> dict[str, Any]:
126
+ """Retourne le statut public d'une notification."""
127
+ return self._request("GET", MAIL_PATH + quote(mail_id, safe=""))
128
+
129
+ def retry_mail(self, mail_id: str) -> dict[str, Any]:
130
+ """Remet en file une notification en échec."""
131
+ return self._request("POST", MAIL_PATH + quote(mail_id, safe="") + "/retry")
132
+
133
+ def process_mail(self, mail_id: str) -> dict[str, Any]:
134
+ """Confirme un brouillon et déclenche une tentative immédiate de livraison."""
135
+ return self._request("PUT", "/api/v1/mails/send/" + quote(mail_id, safe=""))
136
+
137
+ def get_config(self) -> dict[str, Any]:
138
+ """Retourne les paramètres mail exposés par l'API."""
139
+ return self._request("GET", "/api/v1/config")
140
+
141
+ def list_templates(self) -> list[dict[str, Any]]:
142
+ """Retourne la liste des templates configurés."""
143
+ return self._request("GET", "/api/v1/config/templates")
144
+
145
+ def get_template(self, name: str) -> dict[str, Any]:
146
+ """Retourne un template configuré par son nom."""
147
+ return self._request("GET", "/api/v1/config/templates/" + quote(name, safe=""))
148
+
149
+ def get_health(self) -> dict[str, Any]:
150
+ """Retourne le diagnostic public de l'application."""
151
+ return self._request("GET", "/health", authenticated=False)
alertiny/client.pyi ADDED
@@ -0,0 +1,53 @@
1
+ """Alertiny SDK Python interface stub."""
2
+ import __future__ as _future
3
+ import json as json # pylint: disable=C0414,W0611
4
+ import math as math # pylint: disable=C0414,W0611
5
+ from typing import Any as Any, Mapping as Mapping, cast as cast # pylint: disable=C0414,W0611
6
+ from urllib.error import HTTPError as HTTPError # pylint: disable=C0414,W0611
7
+ from urllib.parse import quote as quote, urlsplit as urlsplit # pylint: disable=C0414,W0611
8
+ from urllib.request import HTTPRedirectHandler as HTTPRedirectHandler # pylint: disable=C0414,W0611
9
+ from urllib.request import OpenerDirector, Request as Request, build_opener as build_opener # pylint: disable=C0414,W0611
10
+ from .models import MailRequest
11
+
12
+ annotations: _future._Feature # type: ignore
13
+
14
+ class AlertinyError(Exception): ... # pylint: disable=C0115
15
+
16
+ class AlertinyHTTPError(AlertinyError): # pylint: disable=C0115
17
+ status: int
18
+ detail: Any
19
+ def __init__(self, status: int, detail: Any) -> None: ... # pylint: disable=W0613
20
+
21
+ class AlertinyNetworkError(AlertinyError): ... # pylint: disable=C0115
22
+
23
+ class _NoRedirect(HTTPRedirectHandler):
24
+ def redirect_request( # pylint: disable=R0913,R0917
25
+ self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str,
26
+ ) -> None: ...
27
+
28
+ def _redact(value: Any, token: str) -> Any: ... # pylint: disable=W0613
29
+
30
+ class AlertinyClient: # pylint: disable=C0115
31
+ _base_url: str
32
+ _token: str
33
+ _timeout: float
34
+ _opener: OpenerDirector
35
+ def __init__(self, base_url: str, token: str, timeout: float = 30.0) -> None: ... # pylint: disable=W0613
36
+ def _request(
37
+ self,
38
+ method: str, # pylint: disable=W0613
39
+ path: str, # pylint: disable=W0613
40
+ payload: Mapping[str, Any] | None = None, # pylint: disable=W0613
41
+ *,
42
+ authenticated: bool = True, # pylint: disable=W0613
43
+ ) -> Any: ...
44
+ def create_mail(self, payload: Mapping[str, Any] | MailRequest) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
45
+ def send_mail(self, payload: Mapping[str, Any] | MailRequest) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
46
+ def list_mails(self) -> dict[str, Any]: ... # pylint: disable=C0116
47
+ def get_mail(self, mail_id: str) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
48
+ def retry_mail(self, mail_id: str) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
49
+ def process_mail(self, mail_id: str) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
50
+ def get_config(self) -> dict[str, Any]: ... # pylint: disable=C0116
51
+ def list_templates(self) -> list[dict[str, Any]]: ... # pylint: disable=C0116
52
+ def get_template(self, name: str) -> dict[str, Any]: ... # pylint: disable=W0613,C0116
53
+ def get_health(self) -> dict[str, Any]: ... # pylint: disable=C0116
alertiny/models.py ADDED
@@ -0,0 +1,32 @@
1
+ """Objets de requête pour l'API mail Alertiny."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class Recipient:
10
+ """Destinataire d'une notification."""
11
+
12
+ email: str
13
+
14
+
15
+ @dataclass
16
+ class JinjaValue:
17
+ """Valeur d'une variable du template."""
18
+
19
+ key: str
20
+ value: str
21
+
22
+
23
+ @dataclass
24
+ class MailRequest:
25
+ """Données nécessaires à la création ou à l'envoi d'une notification."""
26
+
27
+ sender: str
28
+ template: str
29
+ jinja_values: list[JinjaValue]
30
+ recipient: list[Recipient]
31
+ subject: str | None = None
32
+ attachments: list[str] = field(default_factory=list[str])
alertiny/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Indique que le package fournit des annotations de type.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: alertiny
3
+ Version: 0.1.0
4
+ Summary: Client Python pour l'API Alertiny
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+
9
+ # Alertiny SDK pour Python
10
+
11
+ [![SDK 0.1.0](https://img.shields.io/badge/SDK-0.1.0-blue)](../README.md)
12
+ ![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?logo=python&logoColor=white)
13
+ [![Licence Apache 2.0](https://img.shields.io/badge/Licence-Apache%202.0-blue)](../LICENSE)
14
+ ![Coverage](https://img.shields.io/badge/Coverage_Statement-100%25-yellow)
15
+
16
+ [![Logo](https://raw.githubusercontent.com/remiv1/alertiny/main/docs/logo.png)](https://raw.githubusercontent.com/remiv1/alertiny/main/docs/logo.png)
17
+
18
+ Client Python 3.10+ pour l'API Alertiny V1. Il permet de préparer un brouillon,
19
+ confirmer son envoi, suivre sa livraison et consulter la configuration.
20
+
21
+ ## Installation
22
+
23
+ Depuis la racine du dépôt parent, dans un environnement virtuel :
24
+
25
+ ```bash
26
+ pip install ./sdk/python
27
+ ```
28
+
29
+ ## Préparer et envoyer un mail
30
+
31
+ Renseignez `ALERTINY_URL` et `ALERTINY_TOKEN` dans votre environnement. L'URL
32
+ doit être celle de l'API ; privilégiez HTTPS en production.
33
+
34
+ ```python
35
+ import os
36
+
37
+ from alertiny import (
38
+ AlertinyClient, AlertinyHTTPError, AlertinyNetworkError,
39
+ JinjaValue, MailRequest, Recipient,
40
+ )
41
+
42
+ client = AlertinyClient(os.environ["ALERTINY_URL"], os.environ["ALERTINY_TOKEN"], timeout=30)
43
+ request = MailRequest(
44
+ sender="alerts@example.com",
45
+ template="service_down.html",
46
+ jinja_values=[JinjaValue("service", "API"), JinjaValue("hostname", "host-01")],
47
+ recipient=[Recipient("ops@example.com")],
48
+ )
49
+
50
+ try:
51
+ draft = client.create_mail(request)
52
+ mail_id = draft["id"]
53
+ print(draft["status"], draft["subject"])
54
+ # draft["html"] contient l'aperçu rendu ; il peut contenir des données sensibles.
55
+
56
+ try:
57
+ result = client.process_mail(mail_id)
58
+ except AlertinyNetworkError:
59
+ # La confirmation peut encore être en cours côté serveur.
60
+ result = client.get_mail(mail_id)
61
+
62
+ print(result["status"], result.get("error"), result.get("imap_uid"))
63
+ except AlertinyHTTPError as error:
64
+ print("Erreur API :", error.status)
65
+ except AlertinyNetworkError:
66
+ print("API inaccessible ou délai réseau dépassé")
67
+ ```
68
+
69
+ `create_mail` crée un brouillon `draft` sans l'envoyer. `process_mail` le confirme et
70
+ attend une tentative SMTP et, après succès, la copie IMAP. Une réponse HTTP réussie
71
+ ne garantit pas l'état `sent` : vérifiez `status` et `error`. En cas de délai expiré,
72
+ consultez l'identifiant avec `get_mail` avant toute autre action : l'envoi peut encore
73
+ se poursuivre côté serveur. Les SDK ne relancent pas automatiquement la requête.
74
+
75
+ `imap_uid` peut être `None` si le serveur ne fournit pas d'identifiant ; utilisez
76
+ également `imap_folder` et `imap_uidvalidity` pour l'interpréter. Les réponses de suivi
77
+ ne retournent ni le HTML ni les destinataires. Pour afficher l'aperçu dans une page
78
+ web, isolez-le dans une iframe `sandbox`.
79
+
80
+ ## Envoi direct et configuration
81
+
82
+ Pour mettre un autre mail en file sans étape d'aperçu :
83
+
84
+ ```python
85
+ queued = client.send_mail(request)
86
+ print(queued["id"], queued["status"]) # pending : livraison ultérieure par le scheduler
87
+ ```
88
+
89
+ Pour inspecter la configuration et les templates disponibles :
90
+
91
+ ```python
92
+ health = client.get_health() # route publique, sans jeton Bearer
93
+ config = client.get_config() # ne contient pas les mots de passe
94
+ templates = client.list_templates()
95
+ template = client.get_template("service_down")
96
+ print(health["API"], config["smtp"]["server"], template["variables"])
97
+ ```
98
+
99
+ ## Méthodes de `AlertinyClient`
100
+
101
+ | Méthode | Résultat et comportement |
102
+ | --- | --- |
103
+ | `AlertinyClient(base_url, token, timeout=30)` | Crée un client ; délai en secondes. |
104
+ | `create_mail(payload)` | Crée un brouillon et retourne `id`, `status`, `subject`, `html`. |
105
+ | `send_mail(payload)` | Met directement le mail en file ; retourne `id` et `status`. |
106
+ | `list_mails()` | Retourne les états publics dans `mails`. |
107
+ | `get_mail(mail_id)` | Retourne l'état public d'un mail. |
108
+ | `retry_mail(mail_id)` | Remet en file un mail en échec. |
109
+ | `process_mail(mail_id)` | Confirme un brouillon et retourne l'état après tentative. |
110
+ | `get_config()` | Retourne la configuration mail, sans mots de passe. |
111
+ | `list_templates()` | Retourne la liste des templates et variables déclarés. |
112
+ | `get_template(name)` | Retourne un template par son nom logique. |
113
+ | `get_health()` | Retourne le diagnostic public, sans envoyer le jeton. |
114
+
115
+ Les réponses sont des dictionnaires, sauf `list_templates()` qui retourne une liste.
116
+ `AlertinyHTTPError` expose `status` et `detail` ; `AlertinyNetworkError` signale une
117
+ erreur de transport, un délai expiré ou une réponse JSON invalide.
118
+
119
+ ## Modèles
120
+
121
+ `MailRequest` accepte `sender`, `template`, `jinja_values` et `recipient` ; `subject`
122
+ est facultatif et `attachments` vaut une liste vide par défaut. Les variables utilisent
123
+ `JinjaValue(key, value)` et les destinataires `Recipient(email)`. Un dictionnaire JSON
124
+ équivalent reste accepté par `create_mail` et `send_mail`.
125
+
126
+ L'API valide les adresses et les variables propres au template ; les pièces jointes
127
+ sont refusées en V1. Le champ `sender` est validé, mais l'expéditeur effectif est celui
128
+ configuré sur le serveur. Voir la [documentation commune des SDK](../README.md).
@@ -0,0 +1,10 @@
1
+ alertiny/__init__.py,sha256=yXg8J7GrL_ckBoUTizq6GkMCRg_OhITrvApiodGTwfo,351
2
+ alertiny/__init__.pyi,sha256=1vONso84BbygdSeN1R-xbxxXVAiGJ2Hhl1-07RWNFnM,652
3
+ alertiny/client.py,sha256=2oRaqAkThSExBFudYW9AG6YfF_1nomXSLpr0Jwskk_c,5956
4
+ alertiny/client.pyi,sha256=iyahOK5SzfgjPHLxUwD0ajXvstdBffenW5XrPtID3G0,2749
5
+ alertiny/models.py,sha256=ypIq1uGjEBQHjnPQZId5W4ey1ssBLb2YeVrpGFzV3BQ,631
6
+ alertiny/py.typed,sha256=5UKRW029MaMSEqibp71HDRpSkzQDxN9T9ZqHrvz9uaQ,57
7
+ alertiny-0.1.0.dist-info/METADATA,sha256=0tShRAHPAR4OvIiehCG5WV41odXdnl_B9THIT0cBU0g,5410
8
+ alertiny-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ alertiny-0.1.0.dist-info/top_level.txt,sha256=plnMLX1BoL5A6_7BG5280rC23g_hsiF7Yi9BwhPTlbI,9
10
+ alertiny-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ alertiny