1"""
2Library for interacting with Mattermost Incoming Webhooks
3:configuration: This module can be used by specifying the name of a
4    configuration profile in the minion config, minion pillar, or master
5    config.
6    For example:
7    .. code-block:: yaml
8
9        mattermost:
10          hook: 3tdgo8restnxiykdx88wqtxryr
11          api_url: https://example.com
12"""
13
14import http.client
15import logging
16import urllib.parse
17
18import salt.utils.http
19from salt.version import __version__
20
21log = logging.getLogger(__name__)
22
23
24def query(hook=None, api_url=None, data=None):
25    """
26    Mattermost object method function to construct and execute on the API URL.
27    :param api_url:     The Mattermost API URL
28    :param hook:        The Mattermost hook.
29    :param data:        The data to be sent for POST method.
30    :return:            The json response from the API call or False.
31    """
32    method = "POST"
33
34    ret = {"message": "", "res": True}
35
36    base_url = urllib.parse.urljoin(api_url, "/hooks/")
37    url = urllib.parse.urljoin(base_url, str(hook))
38
39    result = salt.utils.http.query(url, method, data=data, decode=True, status=True)
40
41    if result.get("status", None) == http.client.OK:
42        ret["message"] = "Message posted {} correctly".format(data)
43        return ret
44    elif result.get("status", None) == http.client.NO_CONTENT:
45        return True
46    else:
47        log.debug(url)
48        log.debug(data)
49        log.debug(result)
50        if "dict" in result:
51            _result = result["dict"]
52            if "error" in _result:
53                ret["message"] = result["error"]
54                ret["res"] = False
55                return ret
56            ret["message"] = "Message not posted"
57        else:
58            ret["message"] = "invalid_auth"
59            ret["res"] = False
60    return ret
61