/
DMPlayerViewController.m
359 lines (298 loc) · 11.9 KB
/
DMPlayerViewController.m
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
// DailymotionPlayerController.m
//
// Created by Olivier Poitrey on 26/09/11.
// Copyright 2011 Dailymotion. All rights reserved.
#import "DMPlayerViewController.h"
static NSString *const DMAPIVersion = @"2.9.3";
@interface DMPlayerViewController () <UIAlertViewDelegate>
@property (nonatomic, readwrite) BOOL autoplay;
@property (nonatomic, readwrite) float bufferedTime;
@property (nonatomic, readwrite) float duration;
@property (nonatomic, readwrite) BOOL seeking;
@property (nonatomic, readwrite) BOOL paused;
@property (nonatomic, readwrite) BOOL ended;
@property (nonatomic, readwrite) BOOL started;
@property (nonatomic, readwrite) NSError *error;
@property (nonatomic, assign) BOOL inited;
@property (nonatomic, strong) NSDictionary *params;
#pragma mark Open In Safari
@property (nonatomic, strong) NSURL *safariURL;
- (void)openURLInSafari:(NSURL *)URL;
@end
@implementation DMPlayerViewController
- (void)dealloc {
UIWebView *webView = (UIWebView *)self.view;
webView.delegate = nil;
[webView stopLoading];
}
- (void)setup {
// See https://developer.dailymotion.com/player#player-parameters for available parameters
_params = @{};
_autoplay = [self.params[@"autoplay"] boolValue];
_currentTime = 0;
_bufferedTime = 0;
_duration = NAN;
_seeking = NO;
_error = nil;
_started = NO;
_ended = NO;
_muted = NO;
_volume = 1;
_paused = true;
_fullscreen = NO;
_webBaseURLString = @"http://www.dailymotion.com";
_autoOpenExternalURLs = NO;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (id)init {
if (self = [super init]) {
[self setup];
}
return self;
}
- (id)initWithParams:(NSDictionary *)params {
if (self = [self init]) {
_params = params;
}
return self;
}
- (id)initWithVideo:(NSString *)video params:(NSDictionary *)params {
if (self = [self initWithParams:params]) {
[self load:video];
}
return self;
}
- (id)initWithVideo:(NSString *)aVideo {
return [self initWithVideo:aVideo params:nil];
}
- (void)initPlayerWithVideo:(NSString *)video {
if (self.inited) return;
self.inited = YES;
UIWebView *webview = [[UIWebView alloc] init];
webview.delegate = self;
// Remote white default background
webview.opaque = NO;
webview.backgroundColor = [UIColor clearColor];
// Allows autoplay (iOS 4+)
if ([webview respondsToSelector:@selector(setMediaPlaybackRequiresUserAction:)]) {
webview.mediaPlaybackRequiresUserAction = NO;
}
if ([webview respondsToSelector:@selector(setAllowsInlineMediaPlayback:)] && self.params[@"webkit-playsinline"]) {
webview.allowsInlineMediaPlayback = YES;
}
if ([self.params[@"fullscreen-state"] isEqualToString:@"fullscreen"]) {
_fullscreen = YES;
}
// Autoresize by default
webview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Hack: prevent vertical bouncing
for (id subview in webview.subviews) {
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
((UIScrollView *)subview).bounces = NO;
((UIScrollView *)subview).scrollEnabled = NO;
}
}
NSMutableString *url = [NSMutableString stringWithFormat:@"%@/embed/video/%@?api=location&objc_sdk_version=%@", self.webBaseURLString, video, DMAPIVersion];
for (NSString *param in [self.params keyEnumerator]) {
id value = self.params[param];
if ([value isKindOfClass:NSString.class]) {
value = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
[url appendFormat:@"&%@=%@", param, value];
}
NSString *appName = NSBundle.mainBundle.bundleIdentifier;
[url appendFormat:@"&app=%@", [appName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
self.view = webview;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
BOOL isFrame = ![[[request URL] absoluteString] isEqualToString:[[request mainDocumentURL] absoluteString]];
if (isFrame) return YES;
if ([request.URL.scheme isEqualToString:@"dmevent"]) {
NSString *eventName = nil;
NSMutableDictionary *data = [NSMutableDictionary dictionary];
// Use reverse order so that the first occurrence of a key replaces those subsequent.
for (NSString *component in [[request.URL.query componentsSeparatedByString:@"&"] reverseObjectEnumerator]) {
if ([component length] == 0) continue;
NSUInteger pos = [component rangeOfString:@"="].location;
if (pos == NSNotFound) pos = component.length - 1;
NSString *key = [component substringToIndex:pos];
NSString *val = [component substringFromIndex:pos + 1];
val = [[val stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:@"+" withString:@" "];
if ([key isEqualToString:@"event"]) {
eventName = val;
}
else {
// stringByReplacingPercentEscapesUsingEncoding may return nil on malformed UTF8 sequence
if (!val) val = @"";
data[key] = val;
}
}
if (eventName.length) {
if ([eventName isEqualToString:@"timeupdate"]) {
[self willChangeValueForKey:@"currentTime"];
_currentTime = [data[@"time"] floatValue];
[self didChangeValueForKey:@"currentTime"];
}
else if ([eventName isEqualToString:@"progress"]) {
self.bufferedTime = [data[@"time"] floatValue];
}
else if ([eventName isEqualToString:@"durationchange"]) {
self.duration = [data[@"duration"] floatValue];
}
else if ([eventName isEqualToString:@"fullscreenchange"]) {
[self willChangeValueForKey:@"fullscreen"];
_fullscreen = [data[@"fullscreen"] boolValue];
[self didChangeValueForKey:@"fullscreen"];
}
else if ([eventName isEqualToString:@"volumechange"]) {
self.volume = [data[@"volume"] floatValue];
}
else if ([eventName isEqualToString:@"play"] || [eventName isEqualToString:@"playing"]) {
self.paused = NO;
}
else if ([eventName isEqualToString:@"start"]) {
self.started = YES;
}
else if ([eventName isEqualToString:@"end"]) {
self.ended = YES;
}
else if ([eventName isEqualToString:@"end"] || [eventName isEqualToString:@"pause"]) {
self.paused = YES;
}
else if ([eventName isEqualToString:@"seeking"]) {
self.seeking = YES;
_currentTime = [data[@"time"] floatValue];
}
else if ([eventName isEqualToString:@"seeked"]) {
self.seeking = NO;
_currentTime = [data[@"time"] floatValue];
}
else if ([eventName isEqualToString:@"error"]) {
NSDictionary *userInfo =
@{
@"code" : @([data[@"code"] intValue]) ?: @0,
@"title" : data[@"title"] ?: @"",
@"message" : data[@"message"] ?: @"",
NSLocalizedDescriptionKey : data[@"message"] ?: @"",
};
self.error = [NSError errorWithDomain:@"DailymotionPlayer"
code:[data[@"code"] integerValue]
userInfo:userInfo];
}
if ([self.delegate respondsToSelector:@selector(dailymotionPlayer:didReceiveEvent:)]) {
[self.delegate dailymotionPlayer:self didReceiveEvent:eventName];
}
}
return NO;
}
else if ([request.URL.path hasPrefix:@"/embed/video/"]) {
return YES;
}
else {
[self openURLInSafari:request.URL];
return NO;
}
}
- (void)setFullscreen:(BOOL)newFullscreen {
[self api:@"fullscreen" arg:newFullscreen ? @"1" : @"0"];
_fullscreen = newFullscreen;
}
- (void)setCurrentTime:(float)newTime {
[self api:@"seek" arg:[NSString stringWithFormat:@"%f", newTime]];
_currentTime = newTime;
}
- (void)play {
[self api:@"play"];
}
- (void)togglePlay {
[self api:@"toggle-play"];
}
- (void)pause {
[self api:@"pause"];
}
- (void)notifyFullscreenChange {
[self api:@"notifyFullscreenChanged"];
}
- (void)load:(NSString *)aVideo {
if (!aVideo) {
NSLog(@"Called DMPlayerViewController load: with a nil video id");
return;
}
if (self.inited) {
[self api:@"load" arg:aVideo];
}
else {
[self initPlayerWithVideo:aVideo];
}
}
- (void)loadVideo:(NSString *)videoId withParams:(NSDictionary *)params {
self.params = params;
[self load:videoId];
}
- (void)api:(NSString *)method arg:(NSString *)arg {
if (!self.inited) return;
if (!method) return;
NSString *warnMessage = [self APIReadyWarnMessageForMethod:method];
if (!self.started && warnMessage) {
NSLog(@"%@", warnMessage);
}
UIWebView *webview = (UIWebView *)self.view;
NSString *jsMethod = [NSString stringWithFormat:@"\"%@\"", method];
NSString *jsArg = arg ? [NSString stringWithFormat:@"\"%@\"", [arg stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]] : @"null";
[webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"player.api(%@, %@)", jsMethod, jsArg]];
}
- (void)api:(NSString *)method {
[self api:method arg:nil];
}
- (NSString *) APIReadyWarnMessageForMethod:(NSString *)method {
NSString * param = @{
@"play" : @"autoplay",
@"toggle-play" : @"autoplay",
@"seek" : @"start",
@"quality" : @"quality",
@"muted" : @"muted",
@"toggle-muted" : @"muted"
}[method];
if (param) {
return [NSString stringWithFormat:@"Warning [DMPlayerViewController]: \n"
"\tCalling `%@` method right after `apiready` event is not recommended.\n"
"\tAre you sure you don\'t want to use the `%@` parameter instead?\n"
"\tFor more information, see: https://developer.dailymotion.com/player#player-parameters", method, param];
}
else {
return nil;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#pragma mark - Open In Safari
- (void)openURLInSafari:(NSURL *)URL {
if (self.autoOpenExternalURLs) {
[[UIApplication sharedApplication] openURL:URL];
}
else {
self.safariURL = URL;
NSString *safariAlertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are about to leave %@", nil), [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"]];
NSString *safariAlertMessage = [NSString stringWithFormat:NSLocalizedString(@"Do you want to open %@ in Safari?", nil), URL.host];
UIAlertView *safariAlertView = [[UIAlertView alloc] initWithTitle:safariAlertTitle
message:safariAlertMessage
delegate:self
cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
otherButtonTitles:NSLocalizedString(@"Open", nil), nil];
[safariAlertView show];
}
}
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != alertView.cancelButtonIndex) {
[[UIApplication sharedApplication] openURL:self.safariURL];
}
self.safariURL = nil;
}
@end