-
Notifications
You must be signed in to change notification settings - Fork 7
/
client.dart
741 lines (653 loc) · 21.6 KB
/
client.dart
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import 'dart:async';
import 'dart:typed_data';
import 'dart:io';
import 'dart:convert';
import './servicestack.dart';
export './servicestack.dart';
typedef void RequestFilter(HttpClientRequest req);
typedef void ResponseFilter(HttpClientResponse res);
typedef void ResponseExceptionFilter(HttpClientResponse? res, Exception e);
class ClientFactory {
static IServiceClient create(
[String baseUrl = "/", ClientOptions? options = null]) {
var client = JsonServiceClient(baseUrl);
if (ClientConfig.initClient != null) {
ClientConfig.initClient!(client);
}
return client;
}
static IServiceClient api(
[String baseUrl = "/", ClientOptions? options = null]) {
var client = JsonServiceClient.api(baseUrl);
if (ClientConfig.initClient != null) {
ClientConfig.initClient!(client);
}
return client;
}
static IServiceClient legacy(
[String baseUrl = "/", ClientOptions? options = null]) {
var client = JsonServiceClient.legacy(baseUrl);
if (ClientConfig.initClient != null) {
ClientConfig.initClient!(client);
}
return client;
}
static IServiceClient createWith(ClientOptions options) {
var client = create(options.baseUrl);
if (client is JsonServiceClient) {
if (options.ignoreCertificatesFor.isNotEmpty) {
var ignoreCerts = toHostsMap(options.ignoreCertificatesFor);
client.client.badCertificateCallback = (cert, host, port) {
if (ignoreCerts.containsKey(host)) {
var ignorePort = ignoreCerts[host];
return ignorePort == null || ignorePort == port;
}
return false;
};
}
}
return client;
}
static IServiceClient apiWith(ClientOptions options) {
var client = api(options.baseUrl);
if (client is JsonServiceClient) {
if (options.ignoreCertificatesFor.isNotEmpty) {
var ignoreCerts = toHostsMap(options.ignoreCertificatesFor);
client.client.badCertificateCallback = (cert, host, port) {
if (ignoreCerts.containsKey(host)) {
var ignorePort = ignoreCerts[host];
return ignorePort == null || ignorePort == port;
}
return false;
};
}
}
return client;
}
}
class SendContext {
String method;
dynamic request;
dynamic body;
Map<String, dynamic>? args;
String? url;
Uri? uri;
RequestFilter? requestFilter;
ResponseFilter? responseFilter;
dynamic responseAs;
String assertUrl() {
if (this.url != null) return this.url!;
if (this.uri != null) return this.uri!.toString();
throw StateError('no url');
}
SendContext(
{this.method = 'GET',
this.request,
this.body,
this.args,
this.url,
this.uri,
this.responseAs,
this.requestFilter,
this.responseFilter});
}
class HttpResponseException implements Exception {
HttpClientResponse response;
HttpResponseException(this.response);
ResponseStatus getResponseStatus() {
return ResponseStatus();
}
}
class JsonServiceClient implements IServiceClient {
String? baseUrl;
String? replyBaseUrl;
String? oneWayBaseUrl;
late Map<String, String> headers;
String? bearerToken;
String? refreshToken;
String? refreshTokenUri;
late bool useTokenCookie;
String? userName;
String? password;
HttpClient? _client;
List<Cookie>? cookies;
RequestFilter? requestFilter;
ResponseFilter? responseFilter;
static RequestFilter? globalRequestFilter;
static ResponseFilter? globalResponseFilter;
UrlFilter? urlFilter;
ResponseExceptionFilter? exceptionFilter;
static ResponseExceptionFilter? globalExceptionFilter;
AsyncCallbackFunction? onAuthenticationRequired;
late int maxRetries;
void set client(HttpClient client) => _client = client;
HttpClient get client => _client ??= HttpClient();
String? getTokenCookie() {
return cookies?.firstWhereOrNull((x) => x.name == 'ss-tok')?.value;
}
String? getRefreshTokenCookie() {
return cookies?.firstWhereOrNull((x) => x.name == 'ss-reftok')?.value;
}
void set connectionTimeout(Duration? duration) =>
client.connectionTimeout = duration;
Duration? get connectionTimeout => client.connectionTimeout;
JsonServiceClient([this.baseUrl = "/"]) {
basePath = "api";
headers = {
HttpHeaders.acceptHeader: "application/json",
};
cookies = <Cookie>[];
maxRetries = 5;
useTokenCookie = false;
}
JsonServiceClient.api([this.baseUrl = "/"]) {
basePath = "api";
headers = {
HttpHeaders.acceptHeader: "application/json",
};
cookies = <Cookie>[];
maxRetries = 5;
useTokenCookie = false;
}
JsonServiceClient.legacy([this.baseUrl = "/"]) {
basePath = null;
headers = {};
cookies = <Cookie>[];
maxRetries = 5;
useTokenCookie = false;
}
void set basePath(String? path) {
if (path == null) {
replyBaseUrl = combinePaths([baseUrl, "json", "reply"]) + "/";
oneWayBaseUrl = combinePaths([baseUrl, "json", "oneway"]) + "/";
} else {
replyBaseUrl = combinePaths([baseUrl, path]) + "/";
oneWayBaseUrl = combinePaths([baseUrl, path]) + "/";
}
}
void clearCookies() {
this.cookies?.clear();
}
@override
Future<ApiResult<T>> api<T>(IReturn<T> request,
{Map<String, dynamic>? args, String? method}) async {
try {
var result =
await fetch<T>(method ?? resolveHttpMethod(request), request, args);
return ApiResult<T>(response: result);
} on Exception catch (e) {
return new ApiResult<T>(error: getResponseStatus(e));
}
}
@override
Future<ApiResult<EmptyResponse>> apiVoid(IReturnVoid request,
{Map<String, dynamic>? args, String? method}) async {
try {
var result = await this.fetch<EmptyResponse>(
method ?? resolveHttpMethod(request), request, args);
return ApiResult<EmptyResponse>(response: result);
} on Exception catch (e) {
return ApiResult<EmptyResponse>(error: getResponseStatus(e));
}
}
Future<T> fetch<T>(String method, dynamic request,
[Map<String, dynamic>? args, String? url]) {
return this.sendRequest<T>(SendContext(
method: method,
request: request,
args: args,
url: url,
));
}
Future<T> get<T>(IReturn<T> request, {Map<String, dynamic>? args}) {
return send<T>(request, method: "GET", args: args);
}
Future<Map<String, dynamic>> getUrl(String path,
{Map<String, dynamic>? args}) {
return sendRequest<Map<String, dynamic>>(
SendContext(method: "GET", url: toAbsoluteUrl(path), args: args));
}
Future<T> getAs<T>(String path,
{Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
method: "GET",
url: toAbsoluteUrl(path),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> post<T>(IReturn<T> request,
{dynamic body, Map<String, dynamic>? args}) {
return send<T>(request, method: "POST", body: body, args: args);
}
Future<Map<String, dynamic>> postToUrl(String path, dynamic body,
{Map<String, dynamic>? args}) {
return sendRequest<Map<String, dynamic>>(SendContext(
method: "POST", body: body, url: toAbsoluteUrl(path), args: args));
}
Future<T> postAs<T>(String path, dynamic body,
{Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
method: "POST",
body: body,
url: toAbsoluteUrl(path),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> delete<T>(IReturn<T> request, {Map<String, dynamic>? args}) {
return send<T>(request, method: "DELETE", args: args);
}
Future<Map<String, dynamic>> deleteUrl(String path,
{Map<String, dynamic>? args}) {
return sendRequest<Map<String, dynamic>>(
SendContext(method: "DELETE", url: toAbsoluteUrl(path), args: args));
}
Future<T> deleteAs<T>(String path,
{Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
method: "DELETE",
url: toAbsoluteUrl(path),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> put<T>(IReturn<T> request,
{dynamic body, Map<String, dynamic>? args}) {
return send<T>(request, method: "PUT", body: body, args: args);
}
Future<Map<String, dynamic>> putToUrl(String path, dynamic body,
{Map<String, dynamic>? args}) {
return sendRequest<Map<String, dynamic>>(SendContext(
method: "PUT", body: body, url: toAbsoluteUrl(path), args: args));
}
Future<T> putAs<T>(String path, dynamic body,
{Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
method: "PUT",
body: body,
url: toAbsoluteUrl(path),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> patch<T>(IReturn<T> request,
{dynamic body, Map<String, dynamic>? args}) {
return send<T>(request, method: "PATCH", body: body, args: args);
}
Future<Map<String, dynamic>> patchToUrl(String path, dynamic body,
{Map<String, dynamic>? args}) {
return sendRequest<Map<String, dynamic>>(SendContext(
method: "PATCH", body: body, url: toAbsoluteUrl(path), args: args));
}
Future<T> patchAs<T>(String path, dynamic body,
{Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
method: "PATCH",
body: body,
url: toAbsoluteUrl(path),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<List<T>> sendAll<T>(Iterable<IReturn<T>> requests,
{RequestFilter? requestFilter, ResponseFilter? responseFilter}) async {
if (requests.length == 0) return <T>[];
var url = combinePaths([replyBaseUrl, nameOf(requests.first)! + "[]"]);
return this.sendRequest<List<T>>(SendContext(
method: "POST",
request: requests.toList(),
uri: createUri(url),
responseAs: <T>[],
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<void> sendAllOneWay<T>(Iterable<IReturn<T>> requests,
{RequestFilter? requestFilter, ResponseFilter? responseFilter}) async {
if (requests.length == 0) return;
var url = combinePaths([oneWayBaseUrl, nameOf(requests.first)! + "[]"]);
await this.sendRequest<List<T>>(SendContext(
method: "POST",
request: requests.toList(),
uri: createUri(url),
responseAs: <T>[],
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> send<T>(IReturn<T> request,
{String? method,
dynamic body,
Map<String, dynamic>? args,
T? responseAs,
RequestFilter? requestFilter,
ResponseFilter? responseFilter}) {
return sendRequest<T>(SendContext(
request: request,
body: body,
method: method ?? resolveHttpMethod(request),
args: args,
responseAs: responseAs,
requestFilter: requestFilter,
responseFilter: responseFilter));
}
Future<T> _resendRequest<T>(info) async {
HttpClientResponse res;
try {
var req = await createRequest(info);
if (urlFilter != null) {
urlFilter!(req.uri.toString());
}
res = await req.close();
} on Exception catch (e) {
Log.debug("_resendRequest() createRequest: $e");
return await handleError(null, e);
}
try {
var response = await createResponse(res, info);
return response;
} on Exception catch (e) {
Log.debug("_resendRequest() createResponse: $e");
return await handleError(res, e);
}
}
Future<T> sendRequest<T>(SendContext info) async {
int statusCode = -1;
HttpClientResponse res;
try {
var req = await createRequest(info);
if (urlFilter != null) {
urlFilter!(req.uri.toString());
}
res = await req.close();
statusCode = res.statusCode;
} on Exception catch (e) {
Log.debug("sendRequest() createRequest: $e");
return await handleError(null, e);
}
try {
var response = await createResponse(res, info);
return response;
} on Exception catch (e) {
var debug = Log.isDebugEnabled();
if (debug) Log.debug("sendRequest(): statusCode:$statusCode, $e");
if (statusCode == 401) {
var hasRefreshTokenCookie = cookies!.any((x) => x.name == "ss-reftok");
if (refreshToken != null || useTokenCookie || hasRefreshTokenCookie) {
var jwtRequest = GetAccessToken(refreshToken: this.refreshToken);
var url = refreshTokenUri ?? createUrlFromDto("POST", jwtRequest);
var jwtInfo = SendContext(
method: "POST", request: jwtRequest, args: null, url: url);
try {
var jwtReq = await createRequest(jwtInfo);
var jwtRes = await jwtReq.close();
var jwtResponse =
await createResponse<GetAccessTokenResponse>(jwtRes, jwtInfo);
bearerToken = jwtResponse!.accessToken;
if (debug) Log.debug("sendRequest(): bearerToken refreshed");
return await _resendRequest<T>(info);
} on Exception catch (jwtEx) {
if (debug) Log.debug("sendRequest(): jwtEx: $jwtEx");
return await handleError(
res, jwtEx, WebServiceExceptionType.RefreshTokenException);
}
}
if (onAuthenticationRequired != null) {
await onAuthenticationRequired!();
return await _resendRequest<T>(info);
}
}
return await handleError(res, e);
}
}
raiseError(HttpClientResponse? res, Exception error) {
if (exceptionFilter != null) {
exceptionFilter!(res, error);
}
if (globalExceptionFilter != null) {
globalExceptionFilter!(res, error);
}
return error;
}
Future<HttpClientRequest> createRequest(SendContext info) async {
var url = info.url ?? info.uri?.toString();
var method = info.method;
var request = info.request;
var body = info.body ?? request;
var args = info.args;
if (url == null || url == '') {
var bodyNotRequestDto = info.request != null && info.body != null;
if (bodyNotRequestDto) {
url = combinePaths([this.replyBaseUrl, nameOf(request)]);
url = appendQueryString(url, toMap(request));
} else {
url = createUrlFromDto(method, request);
}
}
if (url == null) throw ArgumentError.notNull('url');
if (args != null) url = appendQueryString(url, args);
String? bodyStr;
if (hasRequestBody(method)) {
if (body is String) {
bodyStr = body;
} else {
bodyStr = json.encode(body);
}
}
HttpClientRequest? req;
Exception? firstEx;
var uri = info.uri ?? createUri(url);
for (var attempt = 0; attempt < maxRetries; attempt++) {
try {
req = await client.openUrl(method, uri!);
break;
} on Exception catch (e, trace) {
Log.debug("createRequest(): $e\n$trace");
if (firstEx == null) {
firstEx = e;
}
}
}
if (req == null) throw firstEx!;
if (bearerToken != null)
req.headers
.add(HttpHeaders.authorizationHeader, 'Bearer ' + bearerToken!);
else if (userName != null)
req.headers.add(HttpHeaders.authorizationHeader,
'Basic ' + base64.encode(utf8.encode('$userName:$password')));
req.cookies.addAll(this.cookies!);
req.headers.chunkedTransferEncoding = false;
headers.forEach((key, val) {
if (key == HttpHeaders.contentTypeHeader) {
var parts = val.split("/");
req!.headers.contentType = ContentType(parts[0], parts[1]);
} else {
req!.headers.add(key, val);
}
});
if (bodyStr != null) {
req.headers.contentType = ContentType.json;
// var bodyBytes = bodyStr != null ? utf8.encode(bodyStr) : null;
req.contentLength = utf8.encode(bodyStr).length;
}
if (info.requestFilter != null) {
info.requestFilter!(req);
}
if (requestFilter != null) {
requestFilter!(req);
}
if (globalRequestFilter != null) {
globalRequestFilter!(req);
}
if (bodyStr != null) {
req.write(bodyStr);
}
return req;
}
Future<T?> createResponse<T>(HttpClientResponse res, SendContext info) async {
if (res.statusCode >= 300) throw HttpResponseException(res);
try {
mergeCookies(res.cookies);
} on RangeError catch (e) {
Log.debug("[RangeError] createResponse(): " + e.toString());
//ignore https://github.com/dart-lang/sdk/issues/34220
}
if (info.responseFilter != null) {
info.responseFilter!(res);
}
if (responseFilter != null) {
responseFilter!(res);
}
if (globalResponseFilter != null) {
globalResponseFilter!(res);
}
var request = info.request;
var responseAs =
info.responseAs ?? (request != null ? request.createResponse() : null);
res.headers.forEach((key, value) {
if (key.toLowerCase() == "x-cookies") {
if (value.any((v) => v.split(',').indexOf('ss-reftok') >= 0)) {
useTokenCookie = true;
}
}
});
if (res.contentLength == 1) {
return responseAs;
}
if (responseAs is String) {
var bodyStr = await readFully(res);
return bodyStr as T;
}
if (responseAs is Uint8List) {
return (await readFullyAsBytes(res)) as T;
}
var contentType = res.headers.contentType.toString();
var isJson = contentType.indexOf("application/json") != -1;
if (isJson) {
var jsonStr = await readFully(res);
var jsonObj = json.decode(jsonStr);
if (responseAs == null) {
return jsonObj is T ? jsonObj : null;
}
try {
var ret = convertTo(request, responseAs, jsonObj);
return ret;
} on Exception catch (e, trace) {
Log.error("createResponse(): $e\n$trace", e);
raiseError(res, e);
return jsonObj;
}
}
if (res.headers.contentLength == 0 || !isJson) {
return responseAs is T ? responseAs : null;
}
if (res.statusCode == 204 || res.contentLength == 0) {
//No Content
return null;
}
return json.decode(await readFully(res));
}
handleError(HttpClientResponse? holdRes, Exception e,
[WebServiceExceptionType? type]) async {
if (e is WebServiceException) throw raiseError(holdRes, e);
var res = e is HttpResponseException ? e.response : holdRes;
// if (res.bodyUsed)
// throw this.raiseError(res, createErrorResponse(res.status, res.statusText, type));
if (res == null)
throw raiseError(
null,
WebServiceException()
..innerException = e
..statusCode = 500
..statusDescription = e.toString());
var webEx = WebServiceException()
..statusCode = res.statusCode
..statusDescription = res.reasonPhrase
..type = type;
try {
String str = await readFully(res);
if (!isJsonObject(str)) {
webEx.responseStatus = createErrorResponse(
res.statusCode.toString(), res.reasonPhrase, type)
.responseStatus;
} else {
var jsonObj = json.decode(str);
webEx.responseStatus = createResponseStatus(jsonObj);
}
} on Exception catch (e, trace) {
Log.warn("handleError(): $e\n$trace");
webEx.innerException = e;
}
throw raiseError(res, webEx);
}
void mergeCookies(List<Cookie> cookies) {
for (var cookie in cookies) {
this.cookies!.removeWhere((x) => x.name == cookie.name);
this.cookies!.add(cookie);
}
}
@override
void close({bool force = false}) {
if (_client == null) return;
_client!.close(force: force);
_client = null;
}
}
Future<String> readFully(HttpClientResponse response) async {
String body = await response.transform(utf8.decoder).join();
return body;
}
//https://docs.flutter.io/flutter/foundation/consolidateHttpClientResponseBytes.html
Future<Uint8List> readFullyAsBytes(HttpClientResponse response) {
final Completer<Uint8List> completer = Completer<Uint8List>.sync();
if (response.contentLength == -1) {
final List<List<int>> chunks = <List<int>>[];
int contentLength = 0;
response.listen((List<int> chunk) {
chunks.add(chunk);
contentLength += chunk.length;
}, onDone: () {
final Uint8List bytes = Uint8List(contentLength);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
completer.complete(bytes);
}, onError: completer.completeError, cancelOnError: true);
} else {
// If the response has a content length, then allocate a buffer of the correct size.
final Uint8List bytes = Uint8List(response.contentLength);
int offset = 0;
response.listen(
(List<int> chunk) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
},
onError: completer.completeError,
onDone: () {
completer.complete(bytes);
},
cancelOnError: true);
}
return completer.future;
}