This repository has been archived by the owner on Jan 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
/
BBCDownload.m
608 lines (575 loc) · 26.6 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//
// Download.m
// Get_iPlayer GUI
//
// Created by Thomas Willson on 7/14/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "BBCDownload.h"
@implementation BBCDownload
+ (void)initFormats
{
NSArray *tvFormatKeys = @[@"Flash - HD",@"Flash - Very High",@"Flash - High",@"Flash - Standard",@"Flash - Low"];
NSArray *tvFormatObjects = @[@"flashhd",@"flashvhigh",@"flashhigh",@"flashstd",@"flashlow"];
NSArray *radioFormatKeys = @[@"Flash AAC - High",@"Flash AAC - Standard",@"Flash AAC - Low"];
NSArray *radioFormatObjects = @[@"flashaachigh",@"flashaacstd",@"flashaaclow"];
tvFormats = [[NSDictionary alloc] initWithObjects:tvFormatObjects forKeys:tvFormatKeys];
radioFormats = [[NSDictionary alloc] initWithObjects:radioFormatObjects forKeys:radioFormatKeys];
}
#pragma mark Overridden Methods
- (id)initWithProgramme:(Programme *)tempShow tvFormats:(NSArray *)tvFormatList radioFormats:(NSArray *)radioFormatList proxy:(HTTPProxy *)aProxy logController:(LogController *)logger
{
if (!(self = [super initWithLogController:logger])) return nil;
runAgain = NO;
running=YES;
foundLastLine=NO;
errorCache = [[NSMutableString alloc] init];
processErrorCache = [NSTimer scheduledTimerWithTimeInterval:.25 target:self selector:@selector(processError) userInfo:nil repeats:YES];
reasonForFailure = @"None";
defaultsPrefix = @"BBC_";
proxy = aProxy;
log = [[NSMutableString alloc] initWithString:@""];
nc = [NSNotificationCenter defaultCenter];
show = tempShow;
[self addToLog:[NSString stringWithFormat:@"Downloading %@", [show showName]]];
noDataCount=0;
//Initialize Paths
NSBundle *bundle = [NSBundle mainBundle];
NSString *getiPlayerPath = [bundle pathForResource:@"get_iplayer" ofType:@"pl"];
downloadPath = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] valueForKey:@"DownloadPath"]];
//Initialize Formats
if (!tvFormats || !radioFormats) {
[BBCDownload initFormats];
}
NSMutableString *temp_Format;
temp_Format = [[NSMutableString alloc] initWithString:@"--modes="];
for (RadioFormat *format in radioFormatList)
[temp_Format appendFormat:@"%@,", [radioFormats valueForKey:[format format]]];
for (TVFormat *format in tvFormatList)
[temp_Format appendFormat:@"%@,",[tvFormats valueForKey:[format format]]];
NSString *formatArg = [NSString stringWithString:temp_Format];
//Set Proxy Arguments
NSString *proxyArg = nil;
NSString *partialProxyArg = nil;
if (proxy)
{
proxyArg = [[NSString alloc] initWithFormat:@"-p%@", [proxy url]];
if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"AlwaysUseProxy"] boolValue])
{
partialProxyArg = @"--partial-proxy";
}
}
//Initialize the rest of the arguments
NSString *executablesPath = [bundle.executablePath stringByDeletingLastPathComponent];
NSString *noWarningArg = @"--nocopyright";
NSString *noPurgeArg = @"--nopurge";
NSString *id3v2Arg = [[NSString alloc] initWithFormat:@"--id3v2=%@", [executablesPath stringByAppendingPathComponent:@"id3v2"]];
NSString *rtmpdumpArg = [[NSString alloc] initWithFormat:@"--rtmpdump=%@", [executablesPath stringByAppendingPathComponent:@"rtmpdump"]];
NSString *atomicParsleyArg = [[NSString alloc] initWithFormat:@"--atomicparsley=%@", [executablesPath stringByAppendingPathComponent:@"AtomicParsley"]];
NSString *ffmpegArg = [[NSString alloc] initWithFormat:@"--ffmpeg=%@", [executablesPath stringByAppendingPathComponent:@"ffmpeg"]];
NSString *downloadPathArg = [[NSString alloc] initWithFormat:@"--output=%@", downloadPath];
NSString *subDirArg = @"--subdir";
NSLog(@"ID3V2: %@", id3v2Arg);
NSString *getArg = @"--pid";
NSString *searchArg = [[NSString alloc] initWithFormat:@"%@", [show pid]];
//AudioDescribed & Signed
NSMutableString *versionArg = [NSMutableString stringWithString:@"--versions="];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"AudioDescribedNew"] boolValue])
[versionArg appendString:@"audiodescribed,"];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SignedNew"] boolValue])
[versionArg appendString:@"signed,"];
[versionArg appendString:@"default"];
//We don't want this to refresh now!
NSString *cacheExpiryArg = @"-e604800000000";
NSString *appSupportFolder = [@"~/Library/Application Support/Get iPlayer Automator/" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: appSupportFolder])
{
[fileManager createDirectoryAtPath:appSupportFolder withIntermediateDirectories:NO attributes:nil error:nil];
}
profileDirArg = [[NSString alloc] initWithFormat:@"--profile-dir=%@", appSupportFolder];
//Add Arguments that can't be NULL
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:getiPlayerPath,profileDirArg,noWarningArg,noPurgeArg,id3v2Arg,rtmpdumpArg,atomicParsleyArg,cacheExpiryArg,downloadPathArg,subDirArg,formatArg,getArg,searchArg,@"--attempts=5",@"--keep-all",@"--fatfilename",@"--thumbsize=6",@"--tag-hdvideo",@"--tag-longdesc",@"--isodate",versionArg,ffmpegArg,proxyArg,partialProxyArg,nil];
//Verbose?
if (verbose)
[args addObject:@"--verbose"];
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"DownloadSubtitles"] isEqualTo:@YES])
[args addObject:@"--subtitles"];
//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>"];
}
//Tagging
if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"TagShows"] boolValue])
[args addObject:@"--no-tag"];
if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"%@TagCNID", defaultsPrefix]]) {
[args addObject:@"--tag-cnid"];
}
task = [[NSTask alloc] init];
pipe = [[NSPipe alloc] init];
errorPipe = [[NSPipe alloc] init];
[task setArguments:args];
[task setLaunchPath:@"/usr/bin/perl"];
[task setStandardOutput:pipe];
[task setStandardError:errorPipe];
NSMutableDictionary *envVariableDictionary = [NSMutableDictionary dictionaryWithDictionary:[task environment]];
envVariableDictionary[@"HOME"] = [@"~" stringByExpandingTildeInPath];
envVariableDictionary[@"PERL_UNICODE"] = @"AS";
[task setEnvironment:envVariableDictionary];
fh = [pipe fileHandleForReading];
errorFh = [errorPipe fileHandleForReading];
[nc addObserver:self
selector:@selector(DownloadDataReady:)
name:NSFileHandleReadCompletionNotification
object:fh];
[nc addObserver:self
selector:@selector(ErrorDataReady:)
name:NSFileHandleReadCompletionNotification
object:errorFh];
[task launch];
[fh readInBackgroundAndNotify];
[errorFh readInBackgroundAndNotify];
//Prepare UI
[self setCurrentProgress:@"Beginning..."];
[show setValue:@"Starting..." forKey:@"status"];
return self;
}
- (id)description
{
return [NSString stringWithFormat:@"BBC Download (ID=%@)", [show pid]];
}
#pragma mark Task Control
- (void)DownloadDataReady:(NSNotification *)note
{
[[pipe fileHandleForReading] readInBackgroundAndNotify];
NSData *d = [[note userInfo] valueForKey:NSFileHandleNotificationDataItem];
if ([d length] > 0) {
NSString *s = [[NSString alloc] initWithData:d
encoding:NSUTF8StringEncoding];
[self processGetiPlayerOutput:s];
}
else
{
noDataCount++;
if (noDataCount>20 && running)
{
running=NO;
//Download Finished Handler
task = nil;
pipe = nil;
if (runDownloads)
{
if (!foundLastLine) {
NSLog(@"Setting Last Line Here...");
NSArray *logComponents =[ log componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
LastLine = [logComponents lastObject];
unsigned int offsetFromEnd=1;
while (!LastLine.length) {
LastLine = [logComponents objectAtIndex:(logComponents.count - offsetFromEnd)];
++offsetFromEnd;
}
}
NSLog(@"Last Line: %@", LastLine);
NSLog(@"Length of Last Line: %lu", (unsigned long)[LastLine length]);
NSScanner *scn = [NSScanner scannerWithString:LastLine];
if ([reasonForFailure isEqualToString:@"unresumable"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
[show setValue:@"Failed: Unresumable File" forKey:@"status"];
[show setReasonForFailure:@"Unresumable_File"];
}
else if ([reasonForFailure isEqualToString:@"FileExists"])
{
show.complete = @YES;
show.successful = @NO;
show.status = @"Failed: File Exists";
show.reasonForFailure = reasonForFailure;
}
else if ([reasonForFailure isEqualToString:@"proxy"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
NSString *proxyOption = [[NSUserDefaults standardUserDefaults] valueForKey:@"Proxy"];
if ([proxyOption isEqualToString:@"None"])
{
[show setValue:@"Failed: See Log" forKey:@"status"];
[self addToLog:@"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." noTag:TRUE];
[self addToLog:@"If outside the UK, you may also disconnect your VPN and enable the provided proxy in Preferences." noTag:TRUE];
[show setReasonForFailure:@"ShowNotFound"];
}
else if ([proxyOption isEqualToString:@"Provided"])
{
[show setValue:@"Failed: Bad Proxy" forKey:@"status"];
[self addToLog:@"REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences." noTag:TRUE];
[self addToLog:@"If outside the UK, please submit a bug report so that the proxy can be updated." noTag:TRUE];
[show setReasonForFailure:@"Provided_Proxy"];
}
else if ([proxyOption isEqualToString:@"Custom"])
{
[show setValue:@"Failed: Bad Proxy" forKey:@"status"];
[self addToLog:@"REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences." noTag:TRUE];
[self addToLog:@"If outside the UK, please use a different proxy." noTag:TRUE];
[show setReasonForFailure:@"Custom_Proxy"];
}
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
}
else if ([reasonForFailure isEqualToString:@"modes"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
[show setValue:@"Failed: No Specified Modes" forKey:@"status"];
[self addToLog:@"REASON FOR FAILURE: None of the modes in your download format list are available for this show." noTag:YES];
[self addToLog:@"Try adding more modes." noTag:YES];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
[show setReasonForFailure:@"Specified_Modes"];
NSLog(@"Set Modes");
}
else if ([[show reasonForFailure] isEqualToString:@"InHistory"])
{
NSLog(@"InHistory");
}
else if ([LastLine containsString:@"Permission denied"])
{
if ([LastLine containsString:@"/Volumes"]) //Most likely disconnected external HDD
{
show.complete = @YES;
show.successful = @NO;
show.status = @"Failed: HDD not Accessible";
[self addToLog:@"REASON FOR FAILURE: The specified download directory could not be written to." noTag:YES];
[self addToLog:@"Most likely this is because your external hard drive is disconnected but it could also be a permission issue"
noTag:YES];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
[show setReasonForFailure:@"External_Disconnected"];
}
else
{
show.complete = @YES;
show.successful = @NO;
show.status = @"Failed: Download Directory Unwriteable";
[self addToLog:@"REASON FOR FAILURE: The specified download directory could not be written to." noTag:YES];
[self addToLog:@"Please check the permissions on your download directory."
noTag:YES];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
[show setReasonForFailure:@"Download_Directory_Permissions"];
}
}
else if ([LastLine hasPrefix:@"INFO: Recorded"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@YES forKey:@"successful"];
[show setValue:@"Download Complete" forKey:@"status"];
NSScanner *scanner = [NSScanner scannerWithString:LastLine];
NSString *path;
[scanner scanString:@"INFO: Recorded" intoString:nil];
if (![scanner scanFloat:nil])
{
[scanner scanUpToString:@"kjkjkjkjk" intoString:&path];
}
else
{
[scanner scanUpToString:@"to" intoString:nil];
[scanner scanString:@"to " intoString:nil];
[scanner scanUpToString:@"kjkfjkj" intoString:&path];
}
[show setPath:path];
[self addToLog:[NSString stringWithFormat:@"%@ Completed Successfully",[show showName]]];
}
else if ([LastLine hasPrefix:@"INFO: All streaming threads completed"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@YES forKey:@"successful"];
[show setValue:@"Download Complete" forKey:@"status"];
[show setPath:@"Unknown"];
}
else if ([scn scanUpToString:@"Already in history" intoString:nil] &&
[scn scanString:@"Already in" intoString:nil])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
[show setValue:@"Failed: Download in History" forKey:@"status"];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
[show setReasonForFailure:@"InHistory"];
}
else
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
[show setValue:@"Download Failed" forKey:@"status"];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
}
}
[nc removeObserver:self];
[nc postNotificationName:@"DownloadFinished" object:show];
}
}
}
- (void)ErrorDataReady:(NSNotification *)note
{
[[errorPipe fileHandleForReading] readInBackgroundAndNotify];
NSData *d = [[note userInfo] valueForKey:NSFileHandleNotificationDataItem];
if ([d length] > 0)
{
[errorCache appendString:[[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]];
}
else
{
noDataCount++;
if (noDataCount>20)
{
//Close the error pipe when it is empty.
errorPipe = nil;
[processErrorCache invalidate];
}
}
}
- (void)processError
{
if (running)
{
NSString *outp = [errorCache copy];
errorCache = [NSMutableString stringWithString:@""];
if ([outp length] > 0) {
NSArray *array = [outp componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *message in array)
{
NSString *shortStatus=nil;
NSScanner *scanner = [NSScanner scannerWithString:message];
if ([message length] == 0){
continue;
}
else if ([scanner scanFloat:nil]) //RTMPDump
{
[self processFLVStreamerMessage:message];
continue;
}
else if ([message hasPrefix:@"frame="]) shortStatus= @"Converting..."; //FFMpeg
else if ([message hasPrefix:@" Progress"]) shortStatus= @"Processing Download..."; //Download Artwork
else if ([message hasPrefix:@"ERROR:"] || [message hasPrefix:@"\rERROR:"] || [message hasPrefix:@"\nERROR:"]) //Could be unresumable.
{
BOOL isUnresumable = NO;
if ([scanner scanUpToString:@"corrupt file!" intoString:nil] && [scanner scanString:@"corrupt file!" intoString:nil])
{
isUnresumable = YES;
}
if (!isUnresumable) {
[scanner setScanLocation:0];
if ([scanner scanUpToString:@"Couldn't find the seeked keyframe in this chunk!" intoString:nil] && [scanner scanString:@"Couldn't find the seeked keyframe in this chunk!" intoString:nil])
{
isUnresumable = YES;
}
}
if (isUnresumable)
{
[self addToLog:@"Unresumable file, please delete the partial file and try again." noTag:NO];
[task interrupt];
reasonForFailure=@"unresumable";
[show setReasonForFailure:@"Unresumable_File"];
}
}
else //Other
{
shortStatus = [NSString stringWithFormat:@"Initialising... -- %@", [show valueForKey:@"showName"]];
[self addToLog:message noTag:YES];
}
if (shortStatus != nil)
{
[self setCurrentProgress:[NSString stringWithFormat:@"%@ -- %@",shortStatus,[show valueForKey:@"showName"]]];
[self setPercentage:102];
[show setValue:shortStatus forKey:@"status"];
}
}
}
}
}
- (void)cancelDownload:(id)sender
{
//Some basic cleanup.
[task interrupt];
[nc removeObserver:self name:NSFileHandleReadCompletionNotification object:fh];
[nc removeObserver:self name:NSFileHandleReadCompletionNotification object:errorFh];
[show setValue:@"Cancelled" forKey:@"status"];
[self addToLog:@"Download Cancelled"];
[processErrorCache invalidate];
}
- (void)processGetiPlayerOutput:(NSString *)outp
{
NSArray *array = [outp componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//Parse each line individually.
for (NSString *output in array)
{
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"];
[show setSubtitlePath:srtPath];
}
else if ([output hasSuffix:@"already exists"])
{
reasonForFailure=@"FileExists";
[self addToLog:output noTag:YES];
}
else if ([output hasPrefix:@"INFO: Recorded"])
{
LastLine = [NSString stringWithString:output];
foundLastLine=YES;
}
else if ([output hasPrefix:@"INFO: No specified modes"] && [output hasSuffix:@"--modes=)"])
{
reasonForFailure=@"proxy";
[self addToLog:output noTag:YES];
}
else if ([output hasPrefix:@"INFO: No specified modes"])
{
reasonForFailure=@"modes";
[show setReasonForFailure:@"Specified_Modes"];
[self addToLog:output noTag:YES];
NSScanner *modeScanner = [NSScanner scannerWithString:output];
[modeScanner scanUpToString:@"--modes=" intoString:nil];
[modeScanner scanString:@"--modes=" intoString:nil];
NSString *availableModes;
[modeScanner scanUpToString:@")" intoString:&availableModes];
[show setAvailableModes:availableModes];
}
else if ([output hasSuffix:@"use --force to override"])
{
[show setValue:@YES forKey:@"complete"];
[show setValue:@NO forKey:@"successful"];
[show setValue:@"Failed: Download in History" forKey:@"status"];
[self addToLog:[NSString stringWithFormat:@"%@ Failed",[show showName]]];
[show setReasonForFailure:@"InHistory"];
foundLastLine=YES;
}
else if ([output hasPrefix:@"ERROR: Failed to get version pid"])
{
[show setReasonForFailure:@"ShowNotFound"];
[self addToLog:output noTag:YES];
}
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)
{
[show setReasonForFailure:@"AudioDescribedOnly"];
}
[self addToLog:output noTag:YES];
}
else if ([output hasPrefix:@"INFO:"] || [output hasPrefix:@"WARNING:"] || [output hasPrefix:@"ERROR:"] ||
[output hasSuffix:@"default"] || [output hasPrefix:[show pid]])
{
//Add Status Message to Log
[self addToLog:output noTag:YES];
}
else if ([output hasPrefix:@" Progress"])
{
[self setPercentage:102];
[self setCurrentProgress:[NSString stringWithFormat:@"Processing Download... - %@", [show valueForKey:@"showName"]]];
[self setValue:@"Processing Download..." forKey:@"status"];
}
else if ([output hasPrefix:@"Threads:"])
{
//If it is an MPlayer (ITV) status message:
NSScanner *scanner = [NSScanner scannerWithString:output];
NSString *threadRecieved;
[scanner scanUpToString:@"recorded" intoString:&threadRecieved];
NSScanner *threadRecievedScanner = [NSScanner scannerWithString:threadRecieved];
double downloaded=0;
while ([threadRecievedScanner scanUpToString:@")" intoString:nil])
{
[threadRecievedScanner scanString:@") " intoString:nil];
double thread;
[threadRecievedScanner scanDouble:&thread];
downloaded = downloaded + thread;
}
NSInteger speed;
[scanner scanUpToString:@"(" intoString:nil];
[scanner scanString:@"(" intoString:nil];
[scanner scanInteger:&speed];
[self setCurrentProgress:[NSString stringWithFormat:@"Unknown%% (%3.2fMB/Unknown) - %5.1fKB/s -- %@",
downloaded,
[[NSDecimalNumber numberWithInteger:speed] doubleValue]/8,
[show showName]]];
[show setValue:@"Downloading..." forKey:@"status"];
[self setPercentage:102];
}
else if ([output hasPrefix:@" Progress"])
{
[show setValue:@"Downloading Artwork..." forKey:@"status"];
[self setPercentage:102];
[self setCurrentProgress:[NSString stringWithFormat:@"Downloading Artwork... -- %@", [show showName]]];
}
else
{
//Process iPhone/Radio Downloads Status Message
NSScanner *scanner = [NSScanner scannerWithString:output];
NSDecimal recieved, total, percentage;
NSInteger speed=0;
NSString *timeRemaining;
if(![scanner scanDecimal:&recieved]) recieved = [@0 decimalValue];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&total]) total = [@0 decimalValue];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanInteger:&speed]) speed = [@0 integerValue];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanDecimal:&percentage]) percentage = [@0 decimalValue];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
intoString:nil];
if(![scanner scanUpToString:@"rem" intoString:&timeRemaining]) timeRemaining=@"Unknown";
double adjustedSpeed = [@(speed) doubleValue]/8;
[self setPercentage:[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue]];
if ([[NSDecimalNumber decimalNumberWithDecimal:total] doubleValue] < 5.00 && [[NSDecimalNumber decimalNumberWithDecimal:recieved] doubleValue] > 0)
{
[self setCurrentProgress:[NSString stringWithFormat:@"%3.1f%% (%3.2fMB/%3.2fMB) - %5.1fKB/s -- Getting MOV atom.",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:recieved] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:total] doubleValue],
adjustedSpeed]];
[show setValue:[NSString stringWithFormat:@"Getting MOV atom: %3.1f%%",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue]]
forKey:@"status"];
}
else if ([[NSDecimalNumber decimalNumberWithDecimal:total] doubleValue] == 0)
{
[self setCurrentProgress:[NSString stringWithFormat:@"%3.1f%% (%3.2fMB/%3.2fMB) - %5.1fKB/s -- Initializing...",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:recieved] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:total] doubleValue],
adjustedSpeed]];
[show setValue:[NSString stringWithFormat:@"Initializing: %3.1f%%",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue]]
forKey:@"status"];
}
else
{
[self setCurrentProgress:[NSString stringWithFormat:@"%3.1f%% (%3.2fMB/%3.2fMB) - %.1fKB/s - %@ Remaining -- %@",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:recieved] doubleValue],
[[NSDecimalNumber decimalNumberWithDecimal:total] doubleValue],
adjustedSpeed,timeRemaining,[show showName]]];
[show setValue:[NSString stringWithFormat:@"Downloading: %3.1f%%",
[[NSDecimalNumber decimalNumberWithDecimal:percentage] doubleValue]]
forKey:@"status"];
}
}
}
}
@end