-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathYouTubePlayerWebView+Evaluate.swift
366 lines (312 loc) · 12.8 KB
/
YouTubePlayerWebView+Evaluate.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
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
import Foundation
// MARK: - YouTubePlayerWebView+JavaScript
extension YouTubePlayerWebView {
/// A JavaScript
struct JavaScript: Codable, Hashable {
// MARK: Properties
/// The raw value of the JavaScript
let rawValue: String
// MARK: Initializer
/// Creates a new instance of `YouTubePlayerWebView.JavaScript`
/// - Parameter rawValue: The JavaScript
init(
_ rawValue: String
) {
self.rawValue = rawValue.last != ";" ? "\(rawValue);" : rawValue
}
}
}
// MARK: - YouTubePlayerWebView+JavaScript+player
extension YouTubePlayerWebView.JavaScript {
/// Bool value if the JavaScript contains a YouTube player usage e.g. function call or property access
var containsPlayerUsage: Bool {
self.rawValue.starts(with: YouTubePlayer.HTML.playerVariableName)
}
/// Create YouTubePlayer JavaScript
/// - Parameter operator: The operator (function, property)
static func player(
_ operator: String
) -> Self {
.init("\(YouTubePlayer.HTML.playerVariableName).\(`operator`)")
}
/// Create YouTubePlayer JavaScript with function
/// - Parameters:
/// - function: The function name
/// - parameters: The parameters.
static func player(
function: String,
parameters: String...
) -> Self {
self.player("\(function)(\(parameters.joined(separator: ", ")))")
}
}
// MARK: - YouTubePlayerWebView+JavaScript+embedInAnonymousFunction
extension YouTubePlayerWebView.JavaScript {
/// Embed JavaScript in an anonymous function
func embedInAnonymousFunction() -> Self {
.init("(function(){\(self.rawValue)})()")
}
}
// MARK: - YouTubePlayerWebView+evaluate
extension YouTubePlayerWebView {
/// Evaluates the given JavaScript and converts the JavaScript result
/// by using the supplied `JavaScriptEvaluationResponseConverter` to the given `Response` type
/// - Parameters:
/// - javaScript: The JavaScript that should be evaluated
/// - converter: The JavaScriptEvaluationResponseConverter
/// - completion: The completion closure when the JavaScript has finished executing
func evaluate<Response>(
javaScript: JavaScript,
converter: JavaScriptEvaluationResponseConverter<Response>,
completion: @escaping (Result<Response, YouTubePlayer.APIError>) -> Void
) {
// Initialize evaluate javascript closure
let evaluateJavaScript = { [weak self] in
// Evaluate JavaScript
self?.evaluateJavaScript(
javaScript.rawValue
) { javaScriptResponse, error in
// Initialize Result
let result: Result<Response, YouTubePlayer.APIError> = {
// Check if an Error is available
if let error = error {
// Return failure with YouTubePlayerAPIError
return .failure(
.init(
javaScript: javaScript.rawValue,
javaScriptResponse: javaScriptResponse,
underlyingError: error,
reason: (error as NSError)
.userInfo["WKJavaScriptExceptionMessage"] as? String
)
)
} else {
// Execute Converter and retrieve Result
return converter(
javaScript,
javaScriptResponse
)
}
}()
// Invoke completion with Result
completion(result)
}
}
// Initialize execute javascript closure
let executeJavaScript = {
// Check if is main thread
if Thread.isMainThread {
// Evaluate javascript
evaluateJavaScript()
} else {
// Dispatch on main queue
DispatchQueue.main.async {
// Evaluate javascript
evaluateJavaScript()
}
}
}
// Check if JavaScript contains player usage
if javaScript.containsPlayerUsage {
// Switch on player state
switch self.player?.state {
case nil, .idle:
// Subscribe to state publisher
self.player?
.statePublisher
// Only include non idle states
.filter { $0.isIdle == false }
// Receive the first state
.first()
.sink { _ in
// Execute the JavaScript
executeJavaScript()
}
.store(in: &self.cancellables)
case .ready, .error:
// Synchronously execute the JavaScript
executeJavaScript()
}
} else {
// Otherwise synchronously execute the JavaScript
executeJavaScript()
}
}
/// Evaluates the given JavaScript
/// - Parameter javaScript: The JavaScript that should be evaluated
func evaluate(
javaScript: JavaScript
) {
// Evaluate JavaScript with `empty` Converter
self.evaluate(
javaScript: javaScript,
converter: .empty,
completion: { _ in }
)
}
}
// MARK: - YouTubePlayerWebView+JavaScriptEvaluationResponseConverter
extension YouTubePlayerWebView {
/// A generic JavaScript evaluation response converter
struct JavaScriptEvaluationResponseConverter<Output> {
// MARK: Typealias
/// The JavaScript Response typealias
typealias JavaScriptResponse = Any?
/// The Convert closure typealias
typealias Convert = (JavaScript, JavaScriptResponse) -> Result<Output, YouTubePlayer.APIError>
// MARK: Properties
/// The Convert closure
private let convert: Convert
// MARK: Initializer
/// Creates a new instance of `JavaScriptEvaluationResponseConverter`
/// - Parameter convert: The Convert closure
init(
convert: @escaping Convert
) {
self.convert = convert
}
// MARK: Call-As-Function
/// Call `JavaScriptEvaluationResponseConverter` as function
/// - Parameters:
/// - javaScript: The JavaScript string
/// - javaScriptResponse: The JavaScriptResponse
/// - Returns: A Result containing the Output or a YouTubePlayerAPIError
func callAsFunction(
_ javaScript: JavaScript,
_ javaScriptResponse: JavaScriptResponse
) -> Result<Output, YouTubePlayer.APIError> {
self.convert(
javaScript,
javaScriptResponse
)
}
}
}
// MARK: - JavaScriptEvaluationResponseConverter+Empty
extension YouTubePlayerWebView.JavaScriptEvaluationResponseConverter where Output == Void {
/// An empty JavaScriptEvaluationResponseConverter
static let empty = Self { _, _ in .success(()) }
}
// MARK: - JavaScriptEvaluationResponseConverter+typeCast
extension YouTubePlayerWebView.JavaScriptEvaluationResponseConverter {
/// Type-Cast the JavaScript Response to a new Output type
/// - Parameters:
/// - newOutputType: The NewOutput Type. Default value `.self`
static func typeCast<NewOutput>(
to newOutputType: NewOutput.Type = NewOutput.self
) -> YouTubePlayerWebView.JavaScriptEvaluationResponseConverter<NewOutput> {
.init { javaScript, javaScriptResponse in
// Verify JavaScript response can be casted to NewOutput type
guard let output = javaScriptResponse as? NewOutput else {
// Otherwise return failure
return .failure(
.init(
javaScript: javaScript.rawValue,
javaScriptResponse: javaScriptResponse,
reason: [
"Type-Cast failed",
"Expected type: \(String(describing: NewOutput.self))",
"But found: \(String(describing: javaScriptResponse))"
]
.joined(separator: ". ")
)
)
}
// Return NewOutput
return .success(output)
}
}
}
// MARK: - JavaScriptEvaluationResponseConverter+rawRepresentable
extension YouTubePlayerWebView.JavaScriptEvaluationResponseConverter {
/// Convert JavaScript Response to a RawRepresentable type
/// - Parameters:
/// - type: The Representable Type. Default value `.self`
func rawRepresentable<Representable: RawRepresentable>(
type: Representable.Type = Representable.self
) -> YouTubePlayerWebView.JavaScriptEvaluationResponseConverter<Representable>
where Output == Representable.RawValue {
.init { javaScript, javaScriptResponse in
// Convert current Converter
self(javaScript, javaScriptResponse)
// FlatMap Result
.flatMap { output in
// Verify Representable can be initialized from output value
guard let representable = Representable(rawValue: output) else {
// Otherwise return failure
return .failure(
.init(
javaScript: javaScript.rawValue,
javaScriptResponse: output,
reason: [
"Unknown",
String(describing: Representable.self),
"RawRepresentable-RawValue:",
"\(output)"
]
.joined(separator: " ")
)
)
}
// Return Representable
return .success(representable)
}
}
}
}
// MARK: - JavaScriptEvaluationResponseConverter+decode
extension YouTubePlayerWebView.JavaScriptEvaluationResponseConverter where Output == [String: Any] {
/// Convert and Decode JavaScript Response to a Decodable type
/// - Parameters:
/// - type: The Decodable Type. Default value `.self`
/// - decoder: The JSONDecoder. Default value `.init()`
func decode<D: Decodable>(
as type: D.Type = D.self,
decoder: @autoclosure @escaping () -> JSONDecoder = .init()
) -> YouTubePlayerWebView.JavaScriptEvaluationResponseConverter<D> {
.init { javaScript, javaScriptResponse in
// Convert current Converter
self(javaScript, javaScriptResponse)
// FlatMap Result
.flatMap { output in
// Declare output Data
let outputData: Data
do {
// Initialize output Data by trying to retrieve JSON Data
outputData = try output.jsonData()
} catch {
// Return failure
return .failure(
.init(
javaScript: javaScript.rawValue,
javaScriptResponse: output,
underlyingError: error,
reason: "Malformed JSON"
)
)
}
// Declare Decodable
let decodable: D
do {
// Try to decode output to Decodable type
decodable = try decoder().decode(
D.self,
from: outputData
)
} catch {
// Return failure
return .failure(
.init(
javaScript: javaScript.rawValue,
javaScriptResponse: output,
underlyingError: error,
reason: "Decoding failed: \(error)"
)
)
}
// Return Decodable
return .success(decodable)
}
}
}
}