-
Notifications
You must be signed in to change notification settings - Fork 33
/
ServiceModel.swift
256 lines (196 loc) · 8.88 KB
/
ServiceModel.swift
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
//
// ServiceModel.swift
// Soundscape
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
import Foundation
class ServiceModel {
enum StaticHTTPHeader {
case version
var name: String {
switch self {
case .version: return "App-Version"
}
}
var value: String {
switch self {
case .version: return AppContext.appVersion
}
}
}
/// Maximum amount of time (in seconds) to let a request live before timing it out
static let requestTimeout = 20.0
/// String for identifying errors that originate from Soundscape services
static let errorDomain = "GDAHTTPErrorDomain"
/// String for identifying errors that originate from Realm
static let errorRealm = "GDAHTTPErrorRealm"
private static let productionServicesHostName = "https://soundscape-production.yourservicesdomain.com"
private static let productionAssestsHostName = "https://yourstaticblobstore"
// Do not change `productionVoicesHostName`!
private static let productionVoicesHostName = "https://yourstaticblobstore"
static var learningResourcesWebpage: URL {
return URL(string: productionAssestsHostName + "/externalcontent/soundscape_learning_resources.html")!
}
static var servicesHostName: String {
if FeatureFlag.isEnabled(.developerTools), let debugHostName = DebugSettingsContext.shared.servicesHostName, debugHostName.isEmpty == false {
return debugHostName
}
return productionServicesHostName
}
static var assetsHostName: String {
if FeatureFlag.isEnabled(.developerTools), let debugHostName = DebugSettingsContext.shared.assetsHostName, debugHostName.isEmpty == false {
return debugHostName
}
return productionAssestsHostName
}
static var voicesHostName: String {
if FeatureFlag.isEnabled(.developerTools), let debugHostName = DebugSettingsContext.shared.assetsHostName, debugHostName.isEmpty == false {
return debugHostName
}
return productionVoicesHostName
}
static func validateResponse(request: URLRequest, response: URLResponse?, data: Data?, error: Error?, callback: @escaping (HTTPStatusCode, Error?) -> Void) -> HTTPStatusCode? {
// Some more housekeeping
ServiceModel.logNetworkResponse(response, request: request, error: error)
// Do we have an error?
guard error == nil else {
DispatchQueue.main.async {
callback(.unknown, error!)
}
return nil
}
// Is the response of the proper type? (it always should be...)
guard let httpResponse = response as? HTTPURLResponse else {
GDLogNetworkError("Response error: response object is not an HTTPURLResponse")
DispatchQueue.main.async {
callback(.unknown, NSError(domain: ServiceModel.errorDomain, code: NSURLErrorBadServerResponse, userInfo: nil))
}
return nil
}
let status = HTTPStatusCode(rawValue: httpResponse.statusCode) ?? .unknown
// Make sure we have a known status
guard status != .unknown else {
DispatchQueue.main.async {
callback(status, NSError(domain: ServiceModel.errorDomain, code: status.rawValue, userInfo: nil))
}
return nil
}
// Check the ETag (if the request returned a 304, then there is nothing to do because the data hasn't changed)
guard status != .notModified else {
DispatchQueue.main.async {
callback(status, nil)
}
return nil
}
// If we get this far, then the data property should not be nil
guard data != nil else {
DispatchQueue.main.async {
callback(status, nil)
}
return nil
}
return status
}
static func validateJsonResponse(request: URLRequest, response: URLResponse?, data: Data?, error: Error?) -> [String: Any]? {
guard error == nil else {
return nil
}
guard let httpResponse = response as? HTTPURLResponse else {
return nil
}
guard let status = HTTPStatusCode(rawValue: httpResponse.statusCode), status == .success else {
return nil
}
guard let data = data else {
return nil
}
guard let json = try? JSONSerialization.jsonObject(with: data) else {
return nil
}
return json as? [String: Any]
}
static func validateJsonResponse(request: URLRequest, response: URLResponse?, data: Data?, error: Error?, callback: @escaping (HTTPStatusCode, Error?) -> Void) -> (HTTPStatusCode, String, [String: Any])? {
// Some more housekeeping
ServiceModel.logNetworkResponse(response, request: request, error: error)
// Do we have an error?
guard error == nil else {
DispatchQueue.main.async {
callback(.unknown, error!)
}
return nil
}
// Is the response of the proper type? (it always should be...)
guard let httpResponse = response as? HTTPURLResponse else {
GDLogNetworkError("Response error: response object is not an HTTPURLResponse")
DispatchQueue.main.async {
callback(.unknown, NSError(domain: ServiceModel.errorDomain, code: NSURLErrorBadServerResponse, userInfo: nil))
}
return nil
}
let newEtag = httpResponse.allHeaderFields[HTTPHeader.eTag.rawValue] as? String ?? NSUUID().uuidString
let status = HTTPStatusCode(rawValue: httpResponse.statusCode) ?? .unknown
// Make sure we have a known status
guard status != .unknown else {
DispatchQueue.main.async {
callback(status, NSError(domain: ServiceModel.errorDomain, code: status.rawValue, userInfo: nil))
}
return nil
}
// Check the ETag (if the request returned a 304, then there is nothing to do because the data hasn't changed)
guard status != .notModified else {
DispatchQueue.main.async {
callback(status, nil)
}
return nil
}
// If we get this far, then the data property should not be nil, and it should be valid JSON
guard let data = data, let parsed = try? JSONSerialization.jsonObject(with: data), let json = parsed as? [String: Any] else {
DispatchQueue.main.async {
callback(status, ServiceError.jsonParseFailed)
}
return nil
}
return (status, newEtag, json)
}
static func logNetworkRequest(_ request: URLRequest) {
guard let httpMethod = request.httpMethod else {
return
}
let method = httpMethod.count > 2 ? httpMethod.substring(to: 3)! : httpMethod
GDLogNetworkVerbose("Request (\(method)) \(request.url?.absoluteString ?? "unknown")")
}
static func logNetworkResponse(_ response: URLResponse?, request: URLRequest, error: Error?) {
guard let response = response else {
GDLogNetworkError("Response error: response object is nil")
return
}
let responseStatus: HTTPStatusCode
if let res = response as? HTTPURLResponse {
responseStatus = HTTPStatusCode(rawValue: res.statusCode) ?? .unknown
} else {
responseStatus = .unknown
}
guard let httpMethod = request.httpMethod else {
return
}
let method = httpMethod.count > 2 ? httpMethod.substring(to: 3)! : httpMethod
if error != nil {
GDLogNetworkError("Response error (\(method)) \(responseStatus.rawValue) '\(request.url?.absoluteString ?? "unknown")': \(error.debugDescription)")
} else {
GDLogNetworkVerbose("Response (\(method)) \(responseStatus.rawValue) '\(request.url?.absoluteString ?? "unknown")'")
}
}
}
extension URLRequest {
mutating func setAppVersionHeader() {
self.setValue(ServiceModel.StaticHTTPHeader.version.value, forHTTPHeaderField: ServiceModel.StaticHTTPHeader.version.name)
}
mutating func setETagHeader(_ etag: String?) {
guard let etag = etag else {
return
}
self.setValue(etag, forHTTPHeaderField: HTTPHeader.ifNoneMatch.rawValue)
}
}