From d44e4021fe879230adb762972b9080d021176146 Mon Sep 17 00:00:00 2001 From: nico Date: Tue, 28 Apr 2020 14:11:49 +0200 Subject: code cleanup * split up api and metrics class * revamped file nameming to better resemble their function * update prometheus and influx files * fixed version regex to not break on - in version string --- api.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 api.py (limited to 'api.py') diff --git a/api.py b/api.py new file mode 100644 index 0000000..ccd63e4 --- /dev/null +++ b/api.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import re + +from packaging import version + + +class EjabberdApi: + """ + class to interact with the ejabberd rest/ xmlrpc api + """ + def __init__(self, url, login=None, api: str = "rpc"): + # api variables + self._login = login + self._url = url + + if api == "rpc": + self.cmd = self._rpc + else: + import requests + + self.session = requests.Session() + self.cmd = self._rest + + @property + def _auth(self) -> (str, None): + if self._login is not None: + return f"{self._login['user']}@{self._login['server']}", self._login['password'] + return None + + @property + def verstring(self): + if self._login is not None: + ver_str = re.compile('([1-9][0-9.]*)') + status = self.cmd('status', {}) + + # matches + tmp = ver_str.findall(status)[0] + + # return parsed version string + return version.parse(tmp) + + return None + + def _rest(self, command: str, data) -> dict: + # add authentication header to the session obj + if self.session.auth is None: + self.session.auth = self._auth + + # post + r = self.session.post('/'.join([self._url, command]), json=data) + + # proceed if response is ok + if r.ok: + return r.json() + + return {} + + def _rpc(self, command: str, data): + from xmlrpc import client + + with client.ServerProxy(self._url) as server: + fn = getattr(server, command) + try: + if self._login is not None: + return fn(self._login, data) + return fn(data) + + except: + # this needs to be more specific + return {} -- cgit v1.2.3-18-g5258