forked from GetiPlayerAutomator/get-iplayer-automator
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathBBCDownload.m
448 lines (390 loc) · 20.4 KB
/
BBCDownload.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
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
//
// Download.m
// Get_iPlayer GUI
//
// Created by Thomas Willson on 7/14/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "BBCDownload.h"
#import "AppController.h"
@interface BBCDownload ()
- (instancetype)init NS_DESIGNATED_INITIALIZER;
@end
@implementation BBCDownload
+ (void)initFormats
{
NSArray *tvFormatKeys = @[@"Full HD (1080p)", @"HD (720p)", @"SD (540p)", @"Web (396p)", @"Mobile (288p)"];
NSArray *tvFormatObjects = @[@"fhd",@"hd",@"sd",@"web",@"mobile"];
NSArray *radioFormatKeys = @[@"High", @"Standard", @"Medium", @"Low"];
NSArray *radioFormatObjects = @[@"high", @"std", @"med", @"low"];
tvFormats = [[NSDictionary alloc] initWithObjects:tvFormatObjects forKeys:tvFormatKeys];
radioFormats = [[NSDictionary alloc] initWithObjects:radioFormatObjects forKeys:radioFormatKeys];
}
#pragma mark Overridden Methods
- (instancetype)initWithProgramme:(Programme *)p tvFormats:(NSArray *)tvFormatList radioFormats:(NSArray *)radioFormatList proxy:(HTTPProxy *)aProxy
{
if (self = [super init]) {
self.reasonForFailure = nil;
self.proxy = aProxy;
self.show = p;
DDLogInfo(@"Downloading %@", self.show.showName);
//Initialize Formats
if (!tvFormats || !radioFormats) {
[BBCDownload initFormats];
}
NSMutableString *formatArg = [[NSMutableString alloc] initWithString:@"--quality="];
NSMutableArray *formatStrings = [NSMutableArray array];
if (self.show.radio) {
for (RadioFormat *format in radioFormatList) {
[formatStrings addObject:[radioFormats valueForKey:format.format]];
}
} else {
for (TVFormat *format in tvFormatList) {
[formatStrings addObject:[tvFormats valueForKey:format.format]];
}
}
NSString *commaSeparatedFormats = [formatStrings componentsJoinedByString:@","];
[formatArg appendString:commaSeparatedFormats];
//Set Proxy Arguments
NSString *proxyArg = nil;
NSString *partialProxyArg = nil;
if (aProxy)
{
proxyArg = [[NSString alloc] initWithFormat:@"-p%@", aProxy.url];
if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"AlwaysUseProxy"] boolValue])
{
partialProxyArg = @"--partial-proxy";
}
}
//Initialize the rest of the arguments
NSString *noWarningArg = [GetiPlayerArguments sharedController].noWarningArg;
NSString *noPurgeArg = @"--nopurge";
NSString *atomicParsleyArg = [[NSString alloc] initWithFormat:@"--atomicparsley=%@", [[[AppController sharedController] extraBinariesPath] stringByAppendingPathComponent:@"AtomicParsley"]];
NSString *ffmpegArg = [[NSString alloc] initWithFormat:@"--ffmpeg=%@", [[[AppController sharedController] extraBinariesPath] stringByAppendingPathComponent:@"ffmpeg"]];
NSString *downloadPathArg = [[NSString alloc] initWithFormat:@"--output=%@", self.downloadPath];
NSString *subDirArg = @"--subdir";
NSString *progressArg = @"--logprogress";
NSString *getArg = @"--pid";
NSString *searchArg = self.show.pid;
NSString *whitespaceArg = @"--whitespace";
//AudioDescribed & Signed
BOOL needVersions = NO;
NSMutableArray *nonDefaultVersions = [[NSMutableArray alloc] init];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"AudioDescribedNew"] boolValue]) {
[nonDefaultVersions addObject:@"audiodescribed"];
needVersions = YES;
}
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SignedNew"] boolValue]) {
[nonDefaultVersions addObject:@"signed"];
needVersions = YES;
}
//We don't want this to refresh now!
NSString *cacheExpiryArg = [[GetiPlayerArguments sharedController] cacheExpiryArg];
NSString *profileDirArg = [[GetiPlayerArguments sharedController] profileDirArg];
//Add Arguments that can't be NULL
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:
[[AppController sharedController] getiPlayerPath],
profileDirArg,
noWarningArg,
noPurgeArg,
atomicParsleyArg,
cacheExpiryArg,
downloadPathArg,
subDirArg,
progressArg,
formatArg,
getArg,
searchArg,
whitespaceArg,
@"--attempts=5",
@"--thumbsize=640",
ffmpegArg,
@"--log-progress",
nil];
if (proxyArg) {
[args addObject:proxyArg];
}
if (partialProxyArg) {
[args addObject:partialProxyArg];
}
// Only add a --versions parameter for audio described or signed. Otherwise, let get_iplayer figure it out.
if (needVersions) {
[nonDefaultVersions addObject:@"default"];
NSMutableString *versionArg = [NSMutableString stringWithString:@"--versions="];
[versionArg appendString:[nonDefaultVersions componentsJoinedByString:@","]];
[args addObject:versionArg];
}
//Verbose?
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"Verbose"]) {
[args addObject:@"--verbose"];
}
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"DownloadSubtitles"] isEqualTo:@YES]) {
[args addObject:@"--subtitles"];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"EmbedSubtitles"] isEqualTo:@YES]) {
[args addObject:@"--subs-embed"];
}
}
//Naming Convention
if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"XBMC_naming"] boolValue])
{
[args addObject:@"--file-prefix=<name> - <episode> ((<modeshort>))"];
}
else
{
[args addObject:@"--file-prefix=<nameshort><.senum><.episodeshort>"];
[args addObject:@"--subdir-format=<nameshort>"];
}
// 50 FPS frames?
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Use25FPSStreams"] boolValue]) {
[args addObject:@"--tv-lower-bitrate"];
}
//Tagging
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"TagShows"])
[args addObject:@"--no-tag"];
for (NSString *arg in args) {
DDLogVerbose(@"%@", arg);
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"TagRadioAsPodcast"]) {
[args addObject:@"--tag-podcast-radio"];
self.show.podcast = YES;
}
self.task = [NSTask new];
self.pipe = [NSPipe new];
self.errorPipe = [NSPipe new];
self.task.arguments = args;
self.task.launchPath = [[AppController sharedController] perlBinaryPath];
self.task.standardOutput = self.pipe;
self.task.standardError = self.errorPipe;
NSMutableDictionary *envVariableDictionary = [NSMutableDictionary dictionaryWithDictionary:self.task.environment];
envVariableDictionary[@"HOME"] = (@"~").stringByExpandingTildeInPath;
envVariableDictionary[@"PERL_UNICODE"] = @"AS";
envVariableDictionary[@"PATH"] = [[AppController sharedController] perlEnvironmentPath];
self.task.environment = envVariableDictionary;
NSFileHandle *fh = self.pipe.fileHandleForReading;
NSFileHandle *errorFh = self.errorPipe.fileHandleForReading;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(downloadDataNotification:)
name:NSFileHandleReadCompletionNotification
object:fh];
[fh readInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(downloadDataNotification:)
name:NSFileHandleReadCompletionNotification
object:errorFh];
[errorFh readInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(downloadFinished:)
name:NSTaskDidTerminateNotification
object:self.task];
[self.task launch];
//Prepare UI
[self setCurrentProgress:@"Starting download..."];
self.show.status = @"Starting..";
}
return self;
}
- (id)description
{
return [NSString stringWithFormat:@"BBC Download (ID=%@)", self.show.pid];
}
#pragma mark Task Control
- (void)downloadDataNotification:(NSNotification *)n
{
NSData *data = [[n userInfo] valueForKey:NSFileHandleNotificationDataItem];
if (data.length > 0) {
NSString *s = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
[self processGetiPlayerOutput:s];
}
NSFileHandle *fh = (NSFileHandle *)[n object];
[fh readInBackgroundAndNotify];
}
-(void)downloadFinished:(NSNotification *)notification {
if (runDownloads) {
[self completeDownload];
}
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadFinished" object:self.show];
self.task = nil;
self.pipe = nil;
self.errorPipe = nil;
}
- (void)completeDownload {
// If we have a path it was successful. Note that and return.
if (self.show.path.length > 0) {
self.show.complete = YES;
self.show.successful = YES;
self.show.status = @"Download Complete";
return;
}
// Handle all other error cases.
self.show.complete = YES;
self.show.successful = NO;
if (self.reasonForFailure) {
self.show.reasonForFailure = self.reasonForFailure;
}
if ([self.reasonForFailure isEqualToString:@"FileExists"]) {
self.show.status = @"Failed: File already exists";
DDLogError(@"%@ Failed, already exists",self.show.showName);
} else if ([self.reasonForFailure isEqualToString:@"ShowNotFound"]) {
self.show.status = @"Failed: PID not found";
} else if ([self.reasonForFailure isEqualToString:@"proxy"]) {
NSString *proxyOption = [[NSUserDefaults standardUserDefaults] valueForKey:@"Proxy"];
if ([proxyOption isEqualToString:@"None"]) {
self.show.status = @"Failed: See Log";
DDLogError(@"REASON FOR FAILURE: VPN or System Proxy failed. If you are using a VPN or a proxy configured in System Preferences, contact the VPN or proxy provider for assistance.");
self.show.reasonForFailure = @"ShowNotFound";
} else if ([proxyOption isEqualToString:@"Provided"]) {
self.show.status = @"Failed: Bad Proxy";
DDLogError(@"REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences.");
self.show.reasonForFailure = @"Provided_Proxy";
} else if ([proxyOption isEqualToString:@"Custom"]) {
self.show.status = @"Failed: Bad Proxy";
DDLogError(@"REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences.");
DDLogError(@"If outside the UK, please use a different proxy.");
self.show.reasonForFailure = @"Custom_Proxy";
}
DDLogError(@"%@ Failed",self.show.showName);
} else if ([self.reasonForFailure isEqualToString:@"Specified_Modes"]) {
self.show.status = @"Failed: No Specified Modes";
DDLogError(@"REASON FOR FAILURE: None of the modes in your download format list are available for this show.");
DDLogError(@"Try adding more modes.");
DDLogError(@"%@ Failed",self.show.showName);
} else if ([self.reasonForFailure isEqualToString:@"InHistory"]) {
self.show.status = @"Failed: In download history";
DDLogError(@"InHistory");
} else if ([self.reasonForFailure isEqualToString:@"AudioDescribedOnly"]) {
self.show.reasonForFailure = @"AudioDescribedOnly";
} else if ([self.reasonForFailure isEqualToString:@"External_Disconnected"]) {
self.show.status = @"Failed: HDD not Accessible";
DDLogError(@"REASON FOR FAILURE: The specified download directory could not be written to.");
DDLogError(@"Most likely this is because your external hard drive is disconnected but it could also be a permission issue");
DDLogError(@"%@ Failed",self.show.showName);
} else if ([self.reasonForFailure isEqualToString:@"Download_Directory_Permissions"]) {
self.show.status = @"Failed: Download Directory Unwriteable";
DDLogError(@"REASON FOR FAILURE: The specified download directory could not be written to.");
DDLogError(@"Please check the permissions on your download directory.");
DDLogError(@"%@ Failed",self.show.showName);
} else {
// Failed for an unknown reason.
self.show.status = @"Download Failed";
DDLogError(@"%@ Failed",self.show.showName);
}
}
- (void)processGetiPlayerOutput:(NSString *)outp
{
NSArray *array = [outp componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//Parse each line individually.
for (NSString *output in array)
{
if (output.length == 0) {
continue;
}
if ([output hasPrefix:@"DEBUG:"]) {
DDLogDebug(@"%@", output);
} else if ([output hasPrefix:@"WARNING:"]) {
DDLogWarn(@"%@", output);
} else {
DDLogInfo(@"%@", output);
}
if ([output hasPrefix:@"INFO: Downloading subtitles"])
{
NSScanner *scanner = [NSScanner scannerWithString:output];
NSString *srtPath;
[scanner scanString:@"INFO: Downloading Subtitles to \'" intoString:nil];
[scanner scanUpToString:@".srt\'" intoString:&srtPath];
srtPath = [srtPath stringByAppendingPathExtension:@"srt"];
self.show.subtitlePath = srtPath;
}
else if ([output hasPrefix:@"INFO: Wrote file "])
{
NSScanner *scanner = [NSScanner scannerWithString:output];
NSString *path;
[scanner scanString:@"INFO: Wrote file " intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet] intoString:&path];
self.show.path = path;
}
else if ([output hasPrefix:@"INFO: No specified modes"] && [output hasSuffix:@"--quality=)"])
{
self.reasonForFailure = @"Specified_Modes";
NSScanner *modeScanner = [NSScanner scannerWithString:output];
[modeScanner scanUpToString:@"--quality=" intoString:nil];
[modeScanner scanString:@"--quality=" intoString:nil];
NSString *availableModes;
[modeScanner scanUpToString:@")" intoString:&availableModes];
self.show.availableModes = availableModes;
} else if ([output hasSuffix:@"use --force to override"]) {
self.reasonForFailure = @"InHistory";
} else if ([output containsString:@"Permission denied"]) {
if ([output containsString:@"/Volumes"]) { //Most likely disconnected external HDD {
self.reasonForFailure = @"External_Disconnected";
} else {
self.reasonForFailure = @"Download_Directory_Permissions";
}
} else if ([output hasPrefix:@"WARNING: Use --overwrite"]) {
self.reasonForFailure = @"FileExists";
} else if ([output hasPrefix:@"ERROR: Failed to get version pid"]) {
self.reasonForFailure = @"ShowNotFound";
} else if ([output hasPrefix:@"WARNING: If you use a VPN"] || [output hasSuffix:@"blocked by the BBC"]) {
self.reasonForFailure = @"proxy";
} else if ([output hasPrefix:@"WARNING: No programmes are available for this pid with version(s):"] ||
[output hasPrefix:@"INFO: No versions of this programme were selected"]) {
NSScanner *versionScanner = [NSScanner scannerWithString:output];
[versionScanner scanUpToString:@"available versions:" intoString:nil];
[versionScanner scanString:@"available versions:" intoString:nil];
[versionScanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:nil];
NSString *availableVersions;
[versionScanner scanUpToString:@")" intoString:&availableVersions];
if ([availableVersions rangeOfString:@"audiodescribed"].location != NSNotFound ||
[availableVersions rangeOfString:@"signed"].location != NSNotFound)
{
self.reasonForFailure = @"AudioDescribedOnly";
}
} else if ([output hasPrefix:@"INFO: Downloading thumbnail"]) {
self.show.status = @"Downloading Artwork..";
[self setPercentage:102];
[self setCurrentProgress:[NSString stringWithFormat:@"Downloading Artwork.. -- %@", self.show.showName]];
} else if ([output hasPrefix:@"INFO:"] || [output hasPrefix:@"WARNING:"] || [output hasPrefix:@"ERROR:"] ||
[output hasSuffix:@"default"] || [output hasPrefix:self.show.pid]) {
// Do nothing! This ensures we don't process any other info messages
} else if ([output hasSuffix:@"[audio+video]"] || [output hasSuffix:@"[audio]"] || [output hasSuffix:@"[video]"]) {
//Process iPhone/Radio Downloads Status Message
NSScanner *scanner = [NSScanner scannerWithString:output];
NSDecimal percentage, h, m, s;
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&percentage]) percentage = (@0).decimalValue;
[self setPercentage:[NSDecimalNumber decimalNumberWithDecimal:percentage].doubleValue];
// Jump ahead to the ETA field.
[scanner scanUpToString:@"ETA: " intoString:nil];
[scanner scanString:@"ETA: " intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&h]) h = (@0).decimalValue;
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&m]) m = (@0).decimalValue;
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&s]) s = (@0).decimalValue;
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
NSString *eta = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld remaining",
[NSDecimalNumber decimalNumberWithDecimal:h].integerValue,
[NSDecimalNumber decimalNumberWithDecimal:m].integerValue,
[NSDecimalNumber decimalNumberWithDecimal:s].integerValue];
[self setCurrentProgress:eta];
NSString *format = @"Video downloaded: %ld%%";
if ([output hasSuffix:@"[audio+video]"]) {
format = @"Downloaded %ld%%";
} else if ([output hasSuffix:@"[audio]"]) {
format = @"Audio download: %ld%%";
} else if ([output hasSuffix:@"[video]"]) {
format = @"Video download: %ld%%";
}
self.show.status = [NSString stringWithFormat:format,
[NSDecimalNumber decimalNumberWithDecimal:percentage].integerValue];
}
}
}
@end