FSParsePlaylistRequest.m
9.6 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
/*
* This file is part of the FreeStreamer project,
* (C)Copyright 2011-2018 Matias Muhonen <mmu@iki.fi> 穆马帝
* See the file ''LICENSE'' for using the code.
*
* https://github.com/muhku/FreeStreamer
*/
#import "FSParsePlaylistRequest.h"
#import "FSPlaylistItem.h"
@interface FSParsePlaylistRequest ()
- (void)parsePlaylistFromData:(NSData *)data;
- (void)parsePlaylistM3U:(NSString *)playlist;
- (void)parsePlaylistPLS:(NSString *)playlist;
- (NSURL *)parseLocalFileUrl:(NSString *)fileUrl;
@property (readonly) FSPlaylistFormat format;
@end
@implementation FSParsePlaylistRequest
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
- (void)start
{
if (_task) {
return;
}
NSURLRequest *request = [NSURLRequest requestWithURL:self.url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
@synchronized (self) {
_receivedData = [NSMutableData data];
_task = [session dataTaskWithRequest:request];
_playlistItems = [[NSMutableArray alloc] init];
_format = kFSPlaylistFormatNone;
}
[_task resume];
}
- (void)cancel
{
if (!_task) {
return;
}
@synchronized (self) {
[_task cancel];
_task = nil;
}
}
/*
* =======================================
* Properties
* =======================================
*/
- (NSMutableArray *)playlistItems
{
return [_playlistItems copy];
}
- (FSPlaylistFormat)format
{
return _format;
}
/*
* =======================================
* Private
* =======================================
*/
- (void)parsePlaylistFromData:(NSData *)data
{
NSString *playlistData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
if (_format == kFSPlaylistFormatM3U) {
[self parsePlaylistM3U:playlistData];
if ([_playlistItems count] == 0) {
// If we failed to grab any playlist items, still try
// to parse it in another format; perhaps the server
// mistakingly identified the playlist format
[self parsePlaylistPLS:playlistData];
}
} else if (_format == kFSPlaylistFormatPLS) {
[self parsePlaylistPLS:playlistData];
if ([_playlistItems count] == 0) {
// If we failed to grab any playlist items, still try
// to parse it in another format; perhaps the server
// mistakingly identified the playlist format
[self parsePlaylistM3U:playlistData];
}
}
if ([_playlistItems count] == 0) {
/*
* Fail if we failed to parse any items from the playlist.
*/
self.onFailure();
}
}
- (void)parsePlaylistM3U:(NSString *)playlist
{
[_playlistItems removeAllObjects];
for (NSString *line in [playlist componentsSeparatedByString:@"\n"]) {
if ([line hasPrefix:@"#"]) {
/* metadata, skip */
continue;
}
if ([line hasPrefix:@"http://"] ||
[line hasPrefix:@"https://"]) {
FSPlaylistItem *item = [[FSPlaylistItem alloc] init];
item.url = [NSURL URLWithString:[line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
[_playlistItems addObject:item];
} else if ([line hasPrefix:@"file://"]) {
FSPlaylistItem *item = [[FSPlaylistItem alloc] init];
item.url = [self parseLocalFileUrl:line];
[_playlistItems addObject:item];
}
}
}
- (void)parsePlaylistPLS:(NSString *)playlist
{
[_playlistItems removeAllObjects];
NSMutableDictionary *props = [[NSMutableDictionary alloc] init];
size_t i = 0;
for (NSString *rawLine in [playlist componentsSeparatedByString:@"\n"]) {
NSString *line = [rawLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (i == 0) {
if ([[line lowercaseString] hasPrefix:@"[playlist]"]) {
i++;
continue;
} else {
// Invalid playlist; the first line should indicate that this is a playlist
return;
}
}
// Ignore empty lines
if ([line length] == 0) {
i++;
continue;
}
// Not an empty line; so expect that this is a key/value pair
NSRange r = [line rangeOfString:@"="];
// Invalid format, key/value pair not found
if (r.length == 0) {
return;
}
NSString *key = [[line substringToIndex:r.location] lowercaseString];
NSString *value = [line substringFromIndex:r.location + 1];
props[key] = value;
i++;
}
NSInteger numItems = [[props valueForKey:@"numberofentries"] integerValue];
if (numItems == 0) {
// Invalid playlist; number of playlist items not defined
return;
}
for (i=0; i < numItems; i++) {
FSPlaylistItem *item = [[FSPlaylistItem alloc] init];
NSString *title = [props valueForKey:[NSString stringWithFormat:@"title%lu", (i+1)]];
item.title = title;
NSString *file = [props valueForKey:[NSString stringWithFormat:@"file%lu", (i+1)]];
if ([file hasPrefix:@"http://"] ||
[file hasPrefix:@"https://"]) {
item.url = [NSURL URLWithString:file];
[_playlistItems addObject:item];
} else if ([file hasPrefix:@"file://"]) {
item.url = [self parseLocalFileUrl:file];
[_playlistItems addObject:item];
}
}
}
- (NSURL *)parseLocalFileUrl:(NSString *)fileUrl
{
// Resolve the local bundle URL
NSString *path = [fileUrl substringFromIndex:7];
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];
NSString *fileName = [path substringWithRange:NSMakeRange(0, range.location)];
NSString *suffix = [path substringWithRange:NSMakeRange(range.location + 1, [path length] - [fileName length] - 1)];
return [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:suffix]];
}
/*
* =======================================
* NSURLSessionDelegate
* =======================================
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
_httpStatus = [httpResponse statusCode];
NSString *contentType = response.MIMEType;
NSString *absoluteUrl = [response.URL absoluteString];
_format = kFSPlaylistFormatNone;
if ([contentType isEqualToString:@"audio/x-mpegurl"] ||
[contentType isEqualToString:@"application/x-mpegurl"]) {
_format = kFSPlaylistFormatM3U;
} else if ([contentType isEqualToString:@"audio/x-scpls"] ||
[contentType isEqualToString:@"application/pls+xml"]) {
_format = kFSPlaylistFormatPLS;
} else if ([contentType isEqualToString:@"text/plain"]) {
/* The server did not provide meaningful content type;
last resort: check the file suffix, if there is one */
if ([absoluteUrl hasSuffix:@".m3u"]) {
_format = kFSPlaylistFormatM3U;
} else if ([absoluteUrl hasSuffix:@".pls"]) {
_format = kFSPlaylistFormatPLS;
}
}
if (_format == kFSPlaylistFormatNone) {
#if defined(DEBUG) || (TARGET_IPHONE_SIMULATOR)
NSLog(@"FSParsePlaylistRequest: Unable to determine the type of the playlist for URL: %@", _url);
#endif
self.onFailure();
} else {
completionHandler(NSURLSessionResponseAllow);
}
[_receivedData setLength:0];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{
// Resume the Download Task manually because apparently iOS does not do it automatically?!
[downloadTask resume];
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
if(error) {
@synchronized (self) {
_task = nil;
_receivedData = nil;
}
#if defined(DEBUG) || (TARGET_IPHONE_SIMULATOR)
NSLog(@"FSParsePlaylistRequest: Connection failed for URL: %@, error %@", _url, [error localizedDescription]);
#endif
self.onFailure();
} else {
@synchronized (self) {
_task = nil;
}
if (_httpStatus != 200) {
#if defined(DEBUG) || (TARGET_IPHONE_SIMULATOR)
NSLog(@"FSParsePlaylistRequest: Unable to receive playlist from URL: %@", _url);
#endif
self.onFailure();
return;
}
[self parsePlaylistFromData:_receivedData];
self.onCompletion();
}
}
@end