-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathClient.swift.twig
658 lines (566 loc) · 19.9 KB
/
Client.swift.twig
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
import NIO
import NIOCore
import NIOFoundationCompat
import NIOSSL
import Foundation
import AsyncHTTPClient
@_exported import {{spec.title | caseUcfirst}}Models
let DASHDASH = "--"
let CRLF = "\r\n"
open class Client {
// MARK: Properties
public static var chunkSize = 5 * 1024 * 1024 // 5MB
open var endPoint = "{{spec.endpoint}}"
open var headers: [String: String] = [
"content-type": "application/json",
"x-sdk-name": "{{ sdk.name }}",
"x-sdk-platform": "{{ sdk.platform }}",
"x-sdk-language": "{{ language.name | caseLower }}",
"x-sdk-version": "{{ sdk.version }}"{% if spec.global.defaultHeaders | length > 0 %},{% endif %}
{%~ for key,header in spec.global.defaultHeaders %}
"{{key | caseLower }}": "{{header}}"{% if not loop.last %},{% endif %}
{%~ endfor %}
]
internal var config: [String: String] = [:]
internal var selfSigned: Bool = false
internal var http: HTTPClient
internal var httpForRedirect: HTTPClient
private static let boundaryChars = "abcdefghijklmnopqrstuvwxyz1234567890"
private static let boundary = randomBoundary()
private static var eventLoopGroupProvider = HTTPClient.EventLoopGroupProvider.singleton
// MARK: Methods
public init() {
http = Client.createHTTP()
httpForRedirect = Client.createHTTP(redirectConfiguration: .disallow)
addUserAgentHeader()
addOriginHeader()
}
private static func createHTTP(
selfSigned: Bool = false,
redirectConfiguration: HTTPClient.Configuration.RedirectConfiguration = .follow(max: 5, allowCycles: false),
connectTimeout: TimeAmount = .seconds(30),
readTimeout: TimeAmount = .seconds(30)
) -> HTTPClient {
let timeout = HTTPClient.Configuration.Timeout(
connect: connectTimeout,
read: readTimeout
)
var tls = TLSConfiguration
.makeClientConfiguration()
if selfSigned {
tls.certificateVerification = .none
}
return HTTPClient(
eventLoopGroupProvider: eventLoopGroupProvider,
configuration: HTTPClient.Configuration(
tlsConfiguration: tls,
redirectConfiguration: redirectConfiguration,
timeout: timeout,
decompression: .enabled(limit: .none)
)
)
}
deinit {
do {
try http.syncShutdown()
try httpForRedirect.syncShutdown()
} catch {
print(error)
}
}
{%~ for header in spec.global.headers %}
///
/// Set {{header.key | caseUcfirst}}
///
{%~ if header.description %}
/// {{header.description}}
///
{%~ endif %}
/// @param String value
///
/// @return Client
///
open func set{{ header.key | caseUcfirst }}(_ value: String) -> Client {
config["{{ header.key | caseLower }}"] = value
_ = addHeader(key: "{{header.name}}", value: value)
return self
}
{%~ endfor %}
///
/// Set self signed
///
/// @param Bool status
///
/// @return Client
///
open func setSelfSigned(_ status: Bool = true) -> Client {
self.selfSigned = status
try! http.syncShutdown()
http = Client.createHTTP(selfSigned: status)
return self
}
///
/// Set endpoint
///
/// @param String endPoint
///
/// @return Client
///
open func setEndpoint(_ endPoint: String) -> Client {
if !endPoint.hasPrefix("http://") && !endPoint.hasPrefix("https://") {
fatalError("Invalid endpoint URL: \(endPoint)")
}
self.endPoint = endPoint
return self
}
///
/// Add header
///
/// @param String key
/// @param String value
///
/// @return Client
///
open func addHeader(key: String, value: String) -> Client {
self.headers[key] = value
return self
}
///
/// Builds a query string from parameters
///
/// @param Dictionary<String, Any?> params
/// @param String prefix
///
/// @return String
///
open func parametersToQueryString(params: [String: Any?]) -> String {
var output: String = ""
func appendWhenNotLast(_ index: Int, ofTotal count: Int, outerIndex: Int? = nil, outerCount: Int? = nil) {
if (index != count - 1 || (outerIndex != nil
&& outerCount != nil
&& index == count - 1
&& outerIndex! != outerCount! - 1)) {
output += "&"
}
}
for (parameterIndex, element) in params.enumerated() {
switch element.value {
case nil:
break
case is Array<Any?>:
let list = element.value as! Array<Any?>
for (nestedIndex, item) in list.enumerated() {
output += "\(element.key)[]=\(item!)"
appendWhenNotLast(nestedIndex, ofTotal: list.count, outerIndex: parameterIndex, outerCount: params.count)
}
appendWhenNotLast(parameterIndex, ofTotal: params.count)
default:
output += "\(element.key)=\(element.value!)"
appendWhenNotLast(parameterIndex, ofTotal: params.count)
}
}
return output.addingPercentEncoding(
withAllowedCharacters: .urlHostAllowed
) ?? ""
}
///
/// Sends a "ping" request to Appwrite to verify connectivity.
///
/// @return String
/// @throws Exception
///
open func ping() async throws -> String {
let apiPath: String = "/ping"
let apiHeaders: [String: String] = [
"content-type": "application/json"
]
return try await call(
method: "GET",
path: apiPath,
headers: apiHeaders
)
}
///
/// Make an API call
///
/// @param String method
/// @param String path
/// @param Dictionary<String, Any?> params
/// @param Dictionary<String, String> headers
/// @return Response
/// @throws Exception
///
open func call<T>(
method: String,
path: String = "",
headers: [String: String] = [:],
params: [String: Any?] = [:],
sink: ((ByteBuffer) -> Void)? = nil,
converter: ((Any) -> T)? = nil
) async throws -> T {
let request = try prepareRequest(
method: method,
path: path,
headers: headers,
params: params
)
return try await execute(request, converter: converter)
}
///
/// Make an redirect API call
///
/// @param String method
/// @param String path
/// @param Dictionary<String, Any?> params
/// @param Dictionary<String, String> headers
/// @return String
/// @throws Exception
///
open func redirect(
method: String,
path: String = "",
headers: [String: String] = [:],
params: [String: Any?] = [:]
) async throws -> String? {
let request = try prepareRequest(
method: method,
path: path,
headers: headers,
params: params
)
let response = try await httpForRedirect.execute(
request,
timeout: .seconds(30)
)
if response.status.code >= 400 {
var message = ""
var data = try await response.body.collect(upTo: Int.max)
var type = ""
var responseString = ""
do {
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
message = dict?["message"] as? String ?? response.status.reasonPhrase
type = dict?["type"] as? String ?? ""
responseString = String(decoding: data.readableBytesView, as: UTF8.self)
} catch {
message = data.readString(length: data.readableBytes)!
responseString = message
}
throw {{ spec.title | caseUcfirst }}Error(
message: message,
code: Int(response.status.code),
type: type,
response: responseString
)
}
return response.headers["location"].first
}
private func prepareRequest(
method: String,
path: String = "",
headers: [String: String] = [:],
params: [String: Any?] = [:]
) throws -> HTTPClientRequest {
let validParams = params.filter { $0.value != nil }
let queryParameters = method == "GET" && !validParams.isEmpty
? "?" + parametersToQueryString(params: validParams)
: ""
var request = HTTPClientRequest(url: endPoint + path + queryParameters)
request.method = .RAW(value: method)
for (key, value) in self.headers.merging(headers, uniquingKeysWith: { $1 }) {
request.headers.add(name: key, value: value)
}
request.addDomainCookies()
if "GET" != method {
try buildBody(for: &request, with: validParams)
}
return request
}
private func buildBody(
for request: inout HTTPClientRequest,
with params: [String: Any?]
) throws {
if request.headers["content-type"][0] == "multipart/form-data" {
buildMultipart(&request, with: params, chunked: !request.headers["content-range"].isEmpty)
} else {
try buildJSON(&request, with: params)
}
}
private func execute<T>(
_ request: HTTPClientRequest,
converter: ((Any) -> T)? = nil
) async throws -> T {
let response = try await http.execute(
request,
timeout: .seconds(30)
)
if let warning = response.headers["x-{{ spec.title | lower }}-warning"].first {
warning.split(separator: ";").forEach { warning in
print("Warning: \(warning)")
}
}
var data = try await response.body.collect(upTo: Int.max)
switch response.status.code {
case 0..<400:
switch T.self {
case is Bool.Type:
return true as! T
case is String.Type:
return (data.readString(length: data.readableBytes) ?? "") as! T
case is ByteBuffer.Type:
return data as! T
default:
if data.readableBytes == 0 {
return true as! T
}
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
return converter?(dict!) ?? dict! as! T
}
default:
var message = ""
var type = ""
var responseString = ""
do {
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
message = dict?["message"] as? String ?? response.status.reasonPhrase
type = dict?["type"] as? String ?? ""
responseString = String(decoding: data.readableBytesView, as: UTF8.self)
} catch {
message = data.readString(length: data.readableBytes)!
responseString = message
}
throw {{ spec.title | caseUcfirst }}Error(
message: message,
code: Int(response.status.code),
type: type,
response: responseString
)
}
}
func chunkedUpload<T>(
path: String,
headers: inout [String: String],
params: inout [String: Any?],
paramName: String,
idParamName: String? = nil,
converter: ((Any) -> T)? = nil,
onProgress: ((UploadProgress) -> Void)? = nil
) async throws -> T {
let input = params[paramName] as! InputFile
switch(input.sourceType) {
case "path":
input.data = ByteBuffer(data: try! Data(contentsOf: URL(fileURLWithPath: input.path)))
case "data":
input.data = ByteBuffer(data: input.data as! Data)
default:
break
}
let size = (input.data as! ByteBuffer).readableBytes
if size < Client.chunkSize {
params[paramName] = input
return try await call(
method: "POST",
path: path,
headers: headers,
params: params,
converter: converter
)
}
var offset = 0
var result = [String:Any]()
if idParamName != nil {
// Make a request to check if a file already exists
do {
let map = try await call(
method: "GET",
path: path + "/" + (params[idParamName!] as! String),
headers: headers,
params: [:],
converter: { return $0 as! [String: Any] }
)
let chunksUploaded = map["chunksUploaded"] as! Int
offset = chunksUploaded * Client.chunkSize
} catch {
// File does not exist yet, swallow exception
}
}
while offset < size {
let slice = (input.data as! ByteBuffer).getSlice(at: offset, length: Client.chunkSize)
?? (input.data as! ByteBuffer).getSlice(at: offset, length: Int(size - offset))
params[paramName] = InputFile.fromBuffer(slice!, filename: input.filename, mimeType: input.mimeType)
headers["content-range"] = "bytes \(offset)-\(min((offset + Client.chunkSize) - 1, size - 1))/\(size)"
result = try await call(
method: "POST",
path: path,
headers: headers,
params: params,
converter: { return $0 as! [String: Any] }
)
offset += Client.chunkSize
headers["x-{{ spec.title | caseLower }}-id"] = result["$id"] as? String
onProgress?(UploadProgress(
id: result["$id"] as? String ?? "",
progress: Double(min(offset, size))/Double(size) * 100.0,
sizeUploaded: min(offset, size),
chunksTotal: result["chunksTotal"] as? Int ?? -1,
chunksUploaded: result["chunksUploaded"] as? Int ?? -1
))
}
return converter!(result)
}
private static func randomBoundary() -> String {
var string = ""
for _ in 0..<16 {
string.append(Client.boundaryChars.randomElement()!)
}
return string
}
private func buildJSON(
_ request: inout HTTPClientRequest,
with params: [String: Any?] = [:]
) throws {
var encodedParams = [String:Any]()
for (key, param) in params {
if param is String
|| param is Int
|| param is Float
|| param is Double
|| param is Bool
|| param is [String]
|| param is [Int]
|| param is [Float]
|| param is [Double]
|| param is [Bool]
|| param is [String: Any]
|| param is [Int: Any]
|| param is [Float: Any]
|| param is [Double: Any]
|| param is [Bool: Any] {
encodedParams[key] = param
} else if let encodable = param as? Encodable {
encodedParams[key] = try encodable.toJson()
} else if let param = param {
encodedParams[key] = String(describing: param)
}
}
let json = try JSONSerialization.data(withJSONObject: encodedParams, options: [])
request.body = .bytes(json)
}
private func buildMultipart(
_ request: inout HTTPClientRequest,
with params: [String: Any?] = [:],
chunked: Bool = false
) {
func addPart(name: String, value: Any) {
bodyBuffer.writeString(DASHDASH)
bodyBuffer.writeString(Client.boundary)
bodyBuffer.writeString(CRLF)
bodyBuffer.writeString("Content-Disposition: form-data; name=\"\(name)\"")
if let file = value as? InputFile {
bodyBuffer.writeString("; filename=\"\(file.filename)\"")
bodyBuffer.writeString(CRLF)
bodyBuffer.writeString("Content-Length: \(bodyBuffer.readableBytes)")
bodyBuffer.writeString(CRLF+CRLF)
var buffer = file.data! as! ByteBuffer
bodyBuffer.writeBuffer(&buffer)
bodyBuffer.writeString(CRLF)
return
}
let string = String(describing: value)
bodyBuffer.writeString(CRLF)
bodyBuffer.writeString("Content-Length: \(string.count)")
bodyBuffer.writeString(CRLF+CRLF)
bodyBuffer.writeString(string)
bodyBuffer.writeString(CRLF)
}
var bodyBuffer = ByteBuffer()
for (key, value) in params {
switch key {
case "file":
addPart(name: key, value: value!)
default:
if let list = value as? [Any] {
for listValue in list {
addPart(name: "\(key)[]", value: listValue)
}
continue
}
addPart(name: key, value: value!)
}
}
bodyBuffer.writeString(DASHDASH)
bodyBuffer.writeString(Client.boundary)
bodyBuffer.writeString(DASHDASH)
bodyBuffer.writeString(CRLF)
request.headers.remove(name: "content-type")
if !chunked {
request.headers.add(name: "Content-Length", value: bodyBuffer.readableBytes.description)
}
request.headers.add(name: "Content-Type", value: "multipart/form-data;boundary=\"\(Client.boundary)\"")
request.body = .bytes(bodyBuffer)
}
private func addUserAgentHeader() {
let packageInfo = OSPackageInfo.get()
let device = Client.getDevice()
#if !os(Linux) && !os(Windows)
_ = addHeader(
key: "user-agent",
value: "\(packageInfo.packageName)/\(packageInfo.version) \(device)"
)
#endif
}
private func addOriginHeader() {
let packageInfo = OSPackageInfo.get()
let operatingSystem = Client.getOperatingSystem()
_ = addHeader(
key: "origin",
value: "{{ spec.title | caseLower }}-\(operatingSystem)://\(packageInfo.packageName)"
)
}
}
extension Client {
private static func getOperatingSystem() -> String {
#if os(iOS)
return "ios"
#elseif os(watchOS)
return "watchos"
#elseif os(tvOS)
return "tvos"
#elseif os(macOS)
return "macos"
#elseif os(visionOS)
return "visionos"
#elseif os(Linux)
return "linux"
#elseif os(Windows)
return "windows"
#endif
}
private static func getDevice() -> String {
let deviceInfo = OSDeviceInfo()
var device = ""
#if os(iOS)
let info = deviceInfo.iOSInfo
device = "\(info!.modelIdentifier) iOS/\(info!.systemVersion)"
#elseif os(watchOS)
let info = deviceInfo.watchOSInfo
device = "\(info!.modelIdentifier) watchOS/\(info!.systemVersion)"
#elseif os(tvOS)
let info = deviceInfo.iOSInfo
device = "\(info!.modelIdentifier) tvOS/\(info!.systemVersion)"
#elseif os(macOS)
let info = deviceInfo.macOSInfo
device = "(Macintosh; \(info!.model))"
#elseif os(visionOS)
let info = deviceInfo.iOSInfo
device = "\(info!.modelIdentifier) visionOS/\(info!.systemVersion)"
#elseif os(Linux)
let info = deviceInfo.linuxInfo
device = "(Linux; U; \(info!.id) \(info!.version))"
#elseif os(Windows)
let info = deviceInfo.windowsInfo
device = "(Windows NT; \(info!.computerName))"
#endif
return device
}
}