File: webhooks.py

package info (click to toggle)
nc-py-api 0.19.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,320 kB
  • sloc: python: 12,415; makefile: 238; xml: 100; javascript: 56; sh: 14
file content (224 lines) | stat: -rw-r--r-- 7,769 bytes parent folder | download
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""Nextcloud Webhooks API."""

import dataclasses

from ._misc import clear_from_params_empty  # , require_capabilities
from ._session import AppConfig, AsyncNcSessionBasic, NcSessionBasic


@dataclasses.dataclass
class WebhookInfo:
    """Information about the Webhook."""

    def __init__(self, raw_data: dict):
        self._raw_data = raw_data

    @property
    def webhook_id(self) -> int:
        """`ID` of the webhook."""
        return self._raw_data["id"]

    @property
    def app_id(self) -> str:
        """`ID` of the ExApp that registered webhook."""
        return self._raw_data["appId"] if self._raw_data["appId"] else ""

    @property
    def user_id(self) -> str:
        """`UserID` if webhook was registered in user context."""
        return self._raw_data["userId"] if self._raw_data["userId"] else ""

    @property
    def http_method(self) -> str:
        """HTTP method used to call webhook."""
        return self._raw_data["httpMethod"]

    @property
    def uri(self) -> str:
        """URL address that will be called for this webhook."""
        return self._raw_data["uri"]

    @property
    def event(self) -> str:
        """Nextcloud PHP event that triggers this webhook."""
        return self._raw_data["event"]

    @property
    def event_filter(self):
        """Mongo filter to apply to the serialized data to decide if firing."""
        return self._raw_data["eventFilter"]

    @property
    def user_id_filter(self) -> str:
        """Currently unknown."""
        return self._raw_data["userIdFilter"]

    @property
    def headers(self) -> dict:
        """Headers that should be added to request when calling webhook."""
        return self._raw_data["headers"] if self._raw_data["headers"] else {}

    @property
    def auth_method(self) -> str:
        """Currently unknown."""
        return self._raw_data["authMethod"]

    @property
    def auth_data(self) -> dict:
        """Currently unknown."""
        return self._raw_data["authData"] if self._raw_data["authData"] else {}

    def __repr__(self):
        return f"<{self.__class__.__name__} id={self.webhook_id}, event={self.event}>"


class _WebhooksAPI:
    """The class provides the application management API on the Nextcloud server."""

    _ep_base: str = "/ocs/v1.php/apps/webhook_listeners/api/v1/webhooks"

    def __init__(self, session: NcSessionBasic):
        self._session = session

    def get_list(self, uri_filter: str = "") -> list[WebhookInfo]:
        params = {"uri": uri_filter} if uri_filter else {}
        return [WebhookInfo(i) for i in self._session.ocs("GET", f"{self._ep_base}", params=params)]

    def get_entry(self, webhook_id: int) -> WebhookInfo:
        return WebhookInfo(self._session.ocs("GET", f"{self._ep_base}/{webhook_id}"))

    def register(
        self,
        http_method: str,
        uri: str,
        event: str,
        event_filter: dict | None = None,
        user_id_filter: str = "",
        headers: dict | None = None,
        auth_method: str = "none",
        auth_data: dict | None = None,
    ):
        params = {
            "httpMethod": http_method,
            "uri": uri,
            "event": event,
            "eventFilter": event_filter,
            "userIdFilter": user_id_filter,
            "headers": headers,
            "authMethod": auth_method,
            "authData": auth_data,
        }
        clear_from_params_empty(["eventFilter", "userIdFilter", "headers", "authMethod", "authData"], params)
        return WebhookInfo(self._session.ocs("POST", f"{self._ep_base}", json=params))

    def update(
        self,
        webhook_id: int,
        http_method: str,
        uri: str,
        event: str,
        event_filter: dict | None = None,
        user_id_filter: str = "",
        headers: dict | None = None,
        auth_method: str = "none",
        auth_data: dict | None = None,
    ):
        params = {
            "id": webhook_id,
            "httpMethod": http_method,
            "uri": uri,
            "event": event,
            "eventFilter": event_filter,
            "userIdFilter": user_id_filter,
            "headers": headers,
            "authMethod": auth_method,
            "authData": auth_data,
        }
        clear_from_params_empty(["eventFilter", "userIdFilter", "headers", "authMethod", "authData"], params)
        return WebhookInfo(self._session.ocs("POST", f"{self._ep_base}/{webhook_id}", json=params))

    def unregister(self, webhook_id: int) -> bool:
        return self._session.ocs("DELETE", f"{self._ep_base}/{webhook_id}")

    def unregister_all(self, appid: str = "") -> int:
        if not appid and isinstance(self._session.cfg, AppConfig):
            appid = self._session.cfg.app_name
        else:
            raise ValueError("The `appid` parameter cannot be empty for non-ExApp use.")
        return self._session.ocs("DELETE", f"{self._ep_base}/byappid/{appid}")


class _AsyncWebhooksAPI:
    """The class provides the async application management API on the Nextcloud server."""

    _ep_base: str = "/ocs/v1.php/webhooks"

    def __init__(self, session: AsyncNcSessionBasic):
        self._session = session

    async def get_list(self, uri_filter: str = "") -> list[WebhookInfo]:
        params = {"uri": uri_filter} if uri_filter else {}
        return [WebhookInfo(i) for i in await self._session.ocs("GET", f"{self._ep_base}", params=params)]

    async def get_entry(self, webhook_id: int) -> WebhookInfo:
        return WebhookInfo(await self._session.ocs("GET", f"{self._ep_base}/{webhook_id}"))

    async def register(
        self,
        http_method: str,
        uri: str,
        event: str,
        event_filter: dict | None = None,
        user_id_filter: str = "",
        headers: dict | None = None,
        auth_method: str = "none",
        auth_data: dict | None = None,
    ):
        params = {
            "httpMethod": http_method,
            "uri": uri,
            "event": event,
            "eventFilter": event_filter,
            "userIdFilter": user_id_filter,
            "headers": headers,
            "authMethod": auth_method,
            "authData": auth_data,
        }
        clear_from_params_empty(["eventFilter", "userIdFilter", "headers", "authMethod", "authData"], params)
        return WebhookInfo(await self._session.ocs("POST", f"{self._ep_base}", json=params))

    async def update(
        self,
        webhook_id: int,
        http_method: str,
        uri: str,
        event: str,
        event_filter: dict | None = None,
        user_id_filter: str = "",
        headers: dict | None = None,
        auth_method: str = "none",
        auth_data: dict | None = None,
    ):
        params = {
            "id": webhook_id,
            "httpMethod": http_method,
            "uri": uri,
            "event": event,
            "eventFilter": event_filter,
            "userIdFilter": user_id_filter,
            "headers": headers,
            "authMethod": auth_method,
            "authData": auth_data,
        }
        clear_from_params_empty(["eventFilter", "userIdFilter", "headers", "authMethod", "authData"], params)
        return WebhookInfo(await self._session.ocs("POST", f"{self._ep_base}/{webhook_id}", json=params))

    async def unregister(self, webhook_id: int) -> bool:
        return await self._session.ocs("DELETE", f"{self._ep_base}/{webhook_id}")

    async def unregister_all(self, appid: str = "") -> int:
        if not appid and isinstance(self._session.cfg, AppConfig):
            appid = self._session.cfg.app_name
        else:
            raise ValueError("The `appid` parameter cannot be empty for non-ExApp use.")
        return await self._session.ocs("DELETE", f"{self._ep_base}/byappid/{appid}")