import requests from atlas_client import AtlasClient from . import either class CoreNotificationsClient: def __init__( self, app=None, service_host=None, auth_host=None, client_id=None, client_secret=None, audience=None, ): self.app = app self._service_host = service_host self._api_prefix = "api/v1" self._auth_host = auth_host self._client_id = client_id self._client_secret = client_secret self._audience = audience self._auth = AtlasClient( host=self._auth_host, client_id=self._client_id, client_secret=self._client_secret, audience=self._audience, ) if app is not None: self.init_app(app) def init_app(self, app): self._service_host = self._service_host or app.config.get( "CORE_NOTIFICATIONS_HOST" ) self._auth_host = self._auth_host or app.config.get("M2M_AUTH_HOST") self._client_id = self._client_id or app.config.get( "CORE_NOTIFICATIONS_CLIENT_ID" ) self._client_secret = self._client_secret or app.config.get( "CORE_NOTIFICATIONS_CLIENT_SECRET" ) self._audience = self._audience or app.config.get( "CORE_NOTIFICATIONS_AUDIENCE" ) self._auth = AtlasClient( host=self._auth_host, client_id=self._client_id, client_secret=self._client_secret, audience=self._audience, ) app.extensions["core_notifications"] = self def send_email( self, subject, to, body, attachments, ) -> either.Either: url = "email/send" resp = self._request( url, method="POST", json=[ { "subject": subject, "to": to, "body": body, "attachments": attachments, } ], ) if not resp.ok: return either.Left(resp.text) return either.Right(resp.json()) def check_status(self, task_id: str) -> either.Either: url = f"email/status/{task_id}" resp = self._request(url) if not resp.ok and resp.status_code != 404: return either.Left(resp.text) return either.Right(resp.json()) def _request(self, url: str, method: str = "GET", **kwargs): url = url[1:] if url.startswith("/") else url headers = kwargs.get("headers") or dict() if self._client_id: token = self._auth.get_token() headers.update({"Authorization": f"Bearer {token}"}) return requests.request( url=f"{self.base_url}/{url}", method=method, headers=headers, **kwargs, ) @property def base_url(self): schema = ( "" if self._service_host and any( item in self._service_host for item in ("http://", "https://") ) else "https://" ) return f"{schema}{self._service_host}/{self._api_prefix}"