-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.py
232 lines (161 loc) · 6.83 KB
/
client.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
#!/usr/bin/env python3
import time
import json
import dataclasses
from typing import Self, Dict, Any
import gornilo.http_clients
import model
MAX_BODY_SIZE = 1 << 20 # 1 MiB
CHUNK_SIZE = 1 << 10 # 1 KiB
TOKEN_HEADER_NAME = 'X-Token'
@dataclasses.dataclass
class Response:
code: int
content: Dict[str, Any]
class Api:
def __init__(self: Self, hostname: str, port: int) -> None:
self.url = f'http://{hostname}:{port}'
self.token: str | None = None
def user_get(self: Self, username: str) -> model.User | None:
url = self.url + f'/users/profile/{username}'
response = self.http_request('GET', url)
if isinstance(response, Response) and response.code == 200:
return model.User.parse(response.content)
if isinstance(response, model.ServiceError) and response.name == 'UserNotFoundError':
return None
raise model.ProtocolError('invalid response on user/profile')
def user_register(self: Self, username: str, password: str) -> bool:
url = self.url + '/users/register'
body = {
'name': username,
'password': password,
}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name == 'AlreadyExistsError':
return False
raise model.ProtocolError('invalid response on user/register')
def user_login(self: Self, username: str, password: str) -> bool:
url = self.url + '/users/login'
body = {
'name': username,
'password': password,
}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name == 'InvalidCredentialsError':
return False
raise model.ProtocolError('invalid response on user/login')
def user_logout(self: Self) -> bool:
url = self.url + '/users/logout'
body = {}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
raise model.ProtocolError('invalid response on user/logout')
def note_get(self: Self, title: str) -> model.Note | None:
url = self.url + f'/notes/{title}'
response = self.http_request('GET', url)
if isinstance(response, Response) and response.code == 200:
return model.Note.parse(response.content)
if isinstance(response, model.ServiceError) and response.name == 'NoteNotFoundError':
return None
raise model.ProtocolError('invalid response on note/get')
def note_create(self: Self, title: str, visible: bool, content: str) -> bool:
url = self.url + '/notes'
body = {
'title': title,
'visible': visible,
'content': content,
}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name == 'AlreadyExistsError':
return False
raise model.ProtocolError('invalid response on note/create')
def note_share(self: Self, title: str, viewer: str) -> bool:
url = self.url + f'/notes/{title}/share'
body = {
'viewer': viewer,
}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name in ('OwnerMismatchError', 'UserNotFoundError'):
return False
raise model.ProtocolError('invalid response on note/share')
def note_deny(self: Self, title: str, viewer: str) -> bool:
url = self.url + f'/notes/{title}/deny'
body = {
'viewer': viewer,
}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name in ('OwnerMismatchError', 'UserNotFoundError'):
return False
raise model.ProtocolError('invalid response on note/deny')
def note_destroy(self: Self, title: str) -> bool:
url = self.url + f'/notes/{title}/destroy'
body = {}
response = self.http_request('POST', url, body)
if isinstance(response, Response) and response.code == 200:
return True
if isinstance(response, model.ServiceError) and response.name in ('OwnerMismatchError'):
return False
raise model.ProtocolError('invalid response on note/destroy')
def http_request(
self: Self, method: str, url: str, body: Dict[str, Any] = {},
) -> Response | model.ServiceError:
session = gornilo.http_clients.requests_with_retries(
status_forcelist = (),
)
retry_count = 5
retry_timeout = 2
last_exc = None
for _ in range(retry_count):
try:
response = session.request(
method = method,
url = url,
json = body,
allow_redirects = False,
stream = True,
headers = {
TOKEN_HEADER_NAME: self.token,
},
)
break
except Exception as e:
last_exc = e
time.sleep(retry_timeout)
else:
raise last_exc
self.token = response.headers.get(TOKEN_HEADER_NAME)
try:
content_length = int(response.headers.get('Content-Length', '0'))
except Exception:
raise model.ProtocolError('invalid http headers')
if content_length > MAX_BODY_SIZE:
raise model.ProtocolError('body size is too big')
chunks = []
total_length = 0
for chunk in response.iter_content(CHUNK_SIZE, decode_unicode = False):
chunks.append(chunk)
total_length += len(chunk)
if total_length > MAX_BODY_SIZE:
raise model.ProtocolError('body size is too big')
data = b''.join(chunks)
try:
content = json.loads(data)
except Exception:
raise model.ProtocolError('failed to parse json response')
if 'error' in content:
error = content['error']
if not isinstance(error, dict):
raise model.ProtocolError('failed to parse error')
return model.ServiceError.parse(error)
return Response(response.status_code, content)