-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtincwebui.py
executable file
·252 lines (210 loc) · 7.38 KB
/
tincwebui.py
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from aiohttp import client
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
class EndpointKind(Enum):
LOCAL = "local"
PUBLIC = "public"
def to_json(self) -> str:
return self.value
@staticmethod
def from_json(payload: str) -> 'EndpointKind':
return EndpointKind(payload)
@dataclass
class Endpoint:
host: 'str'
port: 'int'
kind: 'EndpointKind'
def to_json(self) -> dict:
return {
"host": self.host,
"port": self.port,
"kind": self.kind.to_json(),
}
@staticmethod
def from_json(payload: dict) -> 'Endpoint':
return Endpoint(
host=payload['host'],
port=payload['port'],
kind=EndpointKind.from_json(payload['kind']),
)
@dataclass
class Config:
binding: 'str'
def to_json(self) -> dict:
return {
"binding": self.binding,
}
@staticmethod
def from_json(payload: dict) -> 'Config':
return Config(
binding=payload['binding'],
)
class TincWebUIError(RuntimeError):
def __init__(self, method: str, code: int, message: str, data: Any):
super().__init__('{}: {}: {} - {}'.format(method, code, message, data))
self.code = code
self.message = message
self.data = data
@staticmethod
def from_json(method: str, payload: dict) -> 'TincWebUIError':
return TincWebUIError(
method=method,
code=payload['code'],
message=payload['message'],
data=payload.get('data')
)
class TincWebUIClient:
"""
Operations with tinc-web-boot related to UI
"""
def __init__(self, base_url: str = 'http://127.0.0.1:8686/api/', session: Optional[client.ClientSession] = None):
self.__url = base_url
self.__id = 1
self.__request = session.request if session is not None else client.request
def __next_id(self):
self.__id += 1
return self.__id
async def issue_access_token(self, valid_days: int) -> str:
"""
Issue and sign token
"""
response = await self._invoke({
"jsonrpc": "2.0",
"method": "TincWebUI.IssueAccessToken",
"id": self.__next_id(),
"params": [valid_days, ]
})
assert response.status // 100 == 2, str(response.status) + " " + str(response.reason)
payload = await response.json()
if 'error' in payload:
raise TincWebUIError.from_json('issue_access_token', payload['error'])
return payload['result']
async def notify(self, title: str, message: str) -> bool:
"""
Make desktop notification if system supports it
"""
response = await self._invoke({
"jsonrpc": "2.0",
"method": "TincWebUI.Notify",
"id": self.__next_id(),
"params": [title, message, ]
})
assert response.status // 100 == 2, str(response.status) + " " + str(response.reason)
payload = await response.json()
if 'error' in payload:
raise TincWebUIError.from_json('notify', payload['error'])
return payload['result']
async def endpoints(self) -> List[Endpoint]:
"""
Endpoints list to access web UI
"""
response = await self._invoke({
"jsonrpc": "2.0",
"method": "TincWebUI.Endpoints",
"id": self.__next_id(),
"params": []
})
assert response.status // 100 == 2, str(response.status) + " " + str(response.reason)
payload = await response.json()
if 'error' in payload:
raise TincWebUIError.from_json('endpoints', payload['error'])
return [Endpoint.from_json(x) for x in (payload['result'] or [])]
async def configuration(self) -> Config:
"""
Configuration defined for the instance
"""
response = await self._invoke({
"jsonrpc": "2.0",
"method": "TincWebUI.Configuration",
"id": self.__next_id(),
"params": []
})
assert response.status // 100 == 2, str(response.status) + " " + str(response.reason)
payload = await response.json()
if 'error' in payload:
raise TincWebUIError.from_json('configuration', payload['error'])
return Config.from_json(payload['result'])
async def _invoke(self, request):
return await self.__request('POST', self.__url, json=request)
class TincWebUIBatch:
"""
Operations with tinc-web-boot related to UI
"""
def __init__(self, client: TincWebUIClient, size: int = 10):
self.__id = 1
self.__client = client
self.__requests = []
self.__batch = {}
self.__batch_size = size
def __next_id(self):
self.__id += 1
return self.__id
def issue_access_token(self, valid_days: int):
"""
Issue and sign token
"""
params = [valid_days, ]
method = "TincWebUI.IssueAccessToken"
self.__add_request(method, params, lambda payload: payload)
def notify(self, title: str, message: str):
"""
Make desktop notification if system supports it
"""
params = [title, message, ]
method = "TincWebUI.Notify"
self.__add_request(method, params, lambda payload: payload)
def endpoints(self):
"""
Endpoints list to access web UI
"""
params = []
method = "TincWebUI.Endpoints"
self.__add_request(method, params, lambda payload: [Endpoint.from_json(x) for x in (payload or [])])
def configuration(self):
"""
Configuration defined for the instance
"""
params = []
method = "TincWebUI.Configuration"
self.__add_request(method, params, lambda payload: Config.from_json(payload))
def __add_request(self, method: str, params, factory):
request_id = self.__next_id()
request = {
"jsonrpc": "2.0",
"method": method,
"id": request_id,
"params": params
}
self.__requests.append(request)
self.__batch[request_id] = (request, factory)
async def __aenter__(self):
self.__batch = {}
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self()
async def __call__(self) -> list:
offset = 0
num = len(self.__requests)
results = []
while offset < num:
next_offset = offset + self.__batch_size
batch = self.__requests[offset:min(num, next_offset)]
offset = next_offset
responses = await self.__post_batch(batch)
results = results + responses
self.__batch = {}
self.__requests = []
return results
async def __post_batch(self, batch: list) -> list:
response = await self.__client._invoke(batch)
assert response.status // 100 == 2, str(response.status) + " " + str(response.reason)
results = await response.json()
ans = []
for payload in results:
request, factory = self.__batch[payload['id']]
if 'error' in payload:
raise TincWebUIError.from_json(request['method'], payload['error'])
else:
ans.append(factory(payload['result']))
return ans