-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathClient.swift
More file actions
851 lines (741 loc) 路 25.8 KB
/
Copy pathClient.swift
File metadata and controls
851 lines (741 loc) 路 25.8 KB
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
import NIO
import NIOCore
#if canImport(NIOFoundationCompat)
import NIOFoundationCompat
#endif
import NIOSSL
import Foundation
import AsyncHTTPClient
@_exported import AppwriteModels
@_exported import JSONCodable
let DASHDASH = "--"
let CRLF = "\r\n"
open class Client {
// MARK: Properties
public static var chunkSize = 5 * 1024 * 1024 // 5MB
public static var maxConcurrentUploads = 8
open var endPoint = "https://cloud.appwrite.io/v1"
open var endPointRealtime: String? = nil
open var headers: [String: String] = [
"content-type": "application/json",
"x-sdk-name": "Apple",
"x-sdk-platform": "client",
"x-sdk-language": "apple",
"x-sdk-version": "18.2.0",
"x-appwrite-response-format": "1.9.5"
]
internal var config: [String: String] = [:]
internal var selfSigned: Bool = false
internal var compression: Bool = true
internal var compressionHeaderInjected: Bool = false
internal var http: 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()
addUserAgentHeader()
addOriginHeader()
}
private static func createHTTP(
selfSigned: Bool = false,
compression: Bool = true,
maxRedirects: Int = 5,
alloweRedirectCycles: Bool = false,
connectTimeout: TimeAmount = .seconds(30),
readTimeout: TimeAmount = .seconds(30)
) -> HTTPClient {
let timeout = HTTPClient.Configuration.Timeout(
connect: connectTimeout,
read: readTimeout
)
let redirect = HTTPClient.Configuration.RedirectConfiguration.follow(
max: 5,
allowCycles: false
)
var tls = TLSConfiguration
.makeClientConfiguration()
if selfSigned {
tls.certificateVerification = .none
}
return HTTPClient(
eventLoopGroupProvider: eventLoopGroupProvider,
configuration: HTTPClient.Configuration(
tlsConfiguration: tls,
redirectConfiguration: redirect,
timeout: timeout,
decompression: compression ? .enabled(limit: .none) : .disabled
)
)
}
deinit {
do {
try http.syncShutdown()
} catch {
print(error)
}
}
///
/// Set Project
///
/// Your project ID
///
/// @param String value
///
/// @return Client
///
open func setProject(_ value: String) -> Client {
config["project"] = value
return self
}
///
/// Set JWT
///
/// Your secret JSON Web Token
///
/// @param String value
///
/// @return Client
///
open func setJWT(_ value: String) -> Client {
config["jwt"] = value
_ = addHeader(key: "X-Appwrite-JWT", value: value)
return self
}
///
/// Set Locale
///
/// @param String value
///
/// @return Client
///
open func setLocale(_ value: String) -> Client {
config["locale"] = value
_ = addHeader(key: "X-Appwrite-Locale", value: value)
return self
}
///
/// Set Session
///
/// The user session to authenticate with
///
/// @param String value
///
/// @return Client
///
open func setSession(_ value: String) -> Client {
config["session"] = value
_ = addHeader(key: "X-Appwrite-Session", value: value)
return self
}
///
/// Set DevKey
///
/// Your secret dev API key
///
/// @param String value
///
/// @return Client
///
open func setDevKey(_ value: String) -> Client {
config["devkey"] = value
_ = addHeader(key: "X-Appwrite-Dev-Key", value: value)
return self
}
///
/// Set Cookie
///
/// The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes.
///
/// @param String value
///
/// @return Client
///
open func setCookie(_ value: String) -> Client {
config["cookie"] = value
_ = addHeader(key: "Cookie", value: value)
return self
}
///
/// Set ImpersonateUserId
///
/// Impersonate a user by ID
///
/// @param String value
///
/// @return Client
///
open func setImpersonateUserId(_ value: String) -> Client {
config["impersonateuserid"] = value
_ = addHeader(key: "X-Appwrite-Impersonate-User-Id", value: value)
return self
}
///
/// Set ImpersonateUserEmail
///
/// Impersonate a user by email
///
/// @param String value
///
/// @return Client
///
open func setImpersonateUserEmail(_ value: String) -> Client {
config["impersonateuseremail"] = value
_ = addHeader(key: "X-Appwrite-Impersonate-User-Email", value: value)
return self
}
///
/// Set ImpersonateUserPhone
///
/// Impersonate a user by phone
///
/// @param String value
///
/// @return Client
///
open func setImpersonateUserPhone(_ value: String) -> Client {
config["impersonateuserphone"] = value
_ = addHeader(key: "X-Appwrite-Impersonate-User-Phone", value: value)
return self
}
///
/// 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, compression: compression)
return self
}
///
/// Enable or disable automatic response decompression.
///
/// When disabled, the client asks the server for an identity response
/// encoding and does not attempt to decompress response bodies. This can
/// be useful when a server or proxy returns compressed responses that the
/// underlying HTTP client cannot decode.
///
/// @param Bool status Whether response decompression should be enabled.
///
/// @return Client The same client instance.
///
open func setCompression(_ status: Bool = true) -> Client {
self.compression = status
if status {
if compressionHeaderInjected && self.headers["accept-encoding"] == "identity" {
self.headers.removeValue(forKey: "accept-encoding")
}
self.compressionHeaderInjected = false
} else {
self.headers["accept-encoding"] = "identity"
self.compressionHeaderInjected = true
}
try! http.syncShutdown()
http = Client.createHTTP(selfSigned: selfSigned, compression: 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
self.endPointRealtime = endPoint
.replacingOccurrences(of: "http://", with: "ws://")
.replacingOccurrences(of: "https://", with: "wss://")
return self
}
///
/// Set realtime endpoint.
///
/// @param String endPoint
///
/// @return Client
///
open func setEndpointRealtime(_ endPoint: String) -> Client {
if !endPoint.hasPrefix("ws://") && !endPoint.hasPrefix("wss://") {
fatalError("Invalid realtime endpoint URL: \(endPoint)")
}
self.endPointRealtime = endPoint
return self
}
///
/// Add header
///
/// @param String key
/// @param String value
///
/// @return Client
///
open func addHeader(key: String, value: String) -> Client {
if key.caseInsensitiveCompare("accept-encoding") == .orderedSame {
self.compressionHeaderInjected = false
}
self.headers[key] = value
return self
}
open func getHeaders() -> [String: String] {
return self.headers
}
///
/// 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
)?.replacingOccurrences(of: "+", with: "%2B") ?? "" // since urlHostAllowed doesn't include +
}
///
/// Send a ping to project as part of onboarding.
///
/// @return String
/// @throws Exception
///
open func ping() async throws -> String {
let apiPath: String = "/ping"
let apiHeaders: [String: String] = [
"X-Appwrite-Project": config["project"] ?? "",
"accept": "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) throws -> T)? = nil
) async throws -> T {
let validParams = params.filter { $0.value != nil }
let queryParameters = method == "GET" && !validParams.isEmpty
? (path.contains("?") ? "&" : "?") + 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 {
return try await execute(request, converter: converter)
}
try buildBody(for: &request, with: validParams)
return try await execute(request, withSink: sink, converter: converter)
}
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,
withSink bufferSink: ((ByteBuffer) -> Void)? = nil,
converter: ((Any) throws -> T)? = nil
) async throws -> T {
let response = try await http.execute(
request,
timeout: .seconds(30)
)
if let warning = response.headers["x-appwrite-warning"].first {
warning.split(separator: ";").forEach { warning in
fputs("Warning: \(warning)\n", stderr)
}
}
var data = try await response.body.collect(upTo: Int.max)
switch response.status.code {
case 0..<400:
if response.headers["Set-Cookie"].count > 0 {
let domain = URL(string: request.url)!.host!
let new = response.headers["Set-Cookie"]
UserDefaults.standard.set(new, forKey: domain)
}
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(data.readableBytesView)) as? [String: Any]
if let converter = converter {
return try converter(dict!)
}
return dict! as! T
}
default:
var message = ""
var type = ""
var responseString = ""
do {
let dict = try JSONSerialization.jsonObject(with: Data(data.readableBytesView)) 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 AppwriteError(
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) throws -> T)? = nil,
onProgress: ((UploadProgress) -> Void)? = nil
) async throws -> T {
let input = params[paramName] as! InputFile
switch(input.sourceType) {
case "path":
input.data = ByteBuffer(bytes: try! Data(contentsOf: URL(fileURLWithPath: input.path)))
case "data":
input.data = ByteBuffer(bytes: 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]()
var uploadId = idParamName != nil ? params[idParamName!] as? String : nil
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
result = map
} catch {
// File does not exist yet, swallow exception
}
}
let totalChunks = Int(ceil(Double(size) / Double(Client.chunkSize)))
var nextChunk = offset / Client.chunkSize
var completedChunks = nextChunk
var uploadedBytes = min(offset, size)
var completedResponse: [String: Any]? = nil
var lastChunkResponse: [String: Any]? = nil
let baseParams = params
let baseHeaders = headers
func isUploadComplete(_ response: [String: Any]) -> Bool {
guard let chunksUploaded = response["chunksUploaded"] as? Int else {
return false
}
let chunksTotal = response["chunksTotal"] as? Int ?? totalChunks
return chunksUploaded >= chunksTotal
}
func uploadChunk(index: Int, uploadId: String?) async throws -> (Int, Int, [String: Any]) {
let chunkOffset = index * Client.chunkSize
let chunkLength = min(Client.chunkSize, size - chunkOffset)
guard let slice = (input.data as! ByteBuffer).getSlice(at: chunkOffset, length: chunkLength) else {
throw AppwriteError(message: "Failed to read upload chunk")
}
var chunkParams = baseParams
var chunkHeaders = baseHeaders
chunkParams[paramName] = InputFile.fromBuffer(slice, filename: input.filename, mimeType: input.mimeType)
chunkHeaders["content-range"] = "bytes \(chunkOffset)-\(chunkOffset + chunkLength - 1)/\(size)"
if let uploadId = uploadId {
chunkHeaders["x-appwrite-id"] = uploadId
}
let chunkResult = try await call(
method: "POST",
path: path,
headers: chunkHeaders,
params: chunkParams,
converter: { return $0 as! [String: Any] }
)
return (index, chunkLength, chunkResult)
}
if nextChunk == 0 {
let first = try await uploadChunk(index: 0, uploadId: uploadId)
result = first.2
uploadId = result["$id"] as? String
nextChunk = 1
completedChunks = 1
uploadedBytes = first.1
onProgress?(UploadProgress(
id: uploadId ?? "",
progress: Double(uploadedBytes)/Double(size) * 100.0,
sizeUploaded: uploadedBytes,
chunksTotal: result["chunksTotal"] as? Int ?? totalChunks,
chunksUploaded: result["chunksUploaded"] as? Int ?? completedChunks
))
}
let maxConcurrency = Client.maxConcurrentUploads
try await withThrowingTaskGroup(of: (Int, Int, [String: Any]).self) { group in
var inFlight = 0
while inFlight < maxConcurrency && nextChunk < totalChunks {
let index = nextChunk
let currentUploadId = uploadId
group.addTask { try await uploadChunk(index: index, uploadId: currentUploadId) }
nextChunk += 1
inFlight += 1
}
while let chunk = try await group.next() {
inFlight -= 1
completedChunks += 1
uploadedBytes += chunk.1
lastChunkResponse = chunk.2
if isUploadComplete(chunk.2) {
completedResponse = chunk.2
}
onProgress?(UploadProgress(
id: uploadId ?? "",
progress: Double(min(uploadedBytes, size))/Double(size) * 100.0,
sizeUploaded: min(uploadedBytes, size),
chunksTotal: chunk.2["chunksTotal"] as? Int ?? totalChunks,
chunksUploaded: chunk.2["chunksUploaded"] as? Int ?? completedChunks
))
while inFlight < maxConcurrency && nextChunk < totalChunks {
let index = nextChunk
let currentUploadId = uploadId
group.addTask { try await uploadChunk(index: index, uploadId: currentUploadId) }
nextChunk += 1
inFlight += 1
}
}
}
result = completedResponse ?? lastChunkResponse ?? result
return try 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: "appwrite-\(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(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
}
}