aboutsummaryrefslogtreecommitdiffstats
path: root/api.py
blob: a83bae7d1822c3eca7d52b39e8a6e69ec3da6e84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
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.]+(?![.a-z]))\\b')
            status = self.cmd('status', {})

            # matches
            try:
                tmp = ver_str.findall(status)[0]
            # raise SystemExit code 17 if no status message is received
            except TypeError:
                raise SystemExit(17)

            # return parsed version string
            logging.debug(f"fetch version: {tmp}")
            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 {}