forked from GetiPlayerAutomator/get-iplayer-automator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppController.m
2058 lines (1912 loc) · 88.7 KB
/
AppController.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// AppController.m
// Get_iPlayer GUI
//
// Created by Thomas Willson on 7/10/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "AppController.h"
#import "HTTPProxy.h"
#import "Programme.h"
#import "Safari.h"
#import "iTunes.h"
#import "Growl.framework/Headers/GrowlApplicationBridge.h"
#import "Sparkle.framework/Headers/Sparkle.h"
#import "JRFeedbackController.h"
#import "LiveTVChannel.h"
#import "ReasonForFailure.h"
#import "Chrome.h"
#import "ASIHTTPRequest.h"
static AppController *sharedController;
bool runDownloads=NO;
bool runUpdate=NO;
NSDictionary *tvFormats;
NSDictionary *radioFormats;
@implementation AppController
#pragma mark Overriden Methods
- (id)description
{
return @"AppController";
}
- (id)init {
//Initialization
if (!(self = [super init])) return nil;
sharedController = self;
NSNotificationCenter *nc;
nc = [NSNotificationCenter defaultCenter];
//Initialize Arrays for Controllers
searchResultsArray = [NSMutableArray array];
pvrSearchResultsArray = [NSMutableArray array];
pvrQueueArray = [NSMutableArray array];
queueArray = [NSMutableArray array];
//Look for Start notifications for ASS
[nc addObserver:self selector:@selector(applescriptStartDownloads) name:@"StartDownloads" object:nil];
//Register Default Preferences
NSMutableDictionary *defaultValues = [[NSMutableDictionary alloc] init];
NSString *defaultDownloadDirectory = @"~/Movies/TV Shows";
defaultValues[@"DownloadPath"] = [defaultDownloadDirectory stringByExpandingTildeInPath];
defaultValues[@"Proxy"] = @"Provided";
defaultValues[@"CustomProxy"] = @"";
defaultValues[@"AutoRetryFailed"] = @YES;
defaultValues[@"AutoRetryTime"] = @"30";
defaultValues[@"AddCompletedToiTunes"] = @YES;
defaultValues[@"DefaultBrowser"] = @"Safari";
defaultValues[@"DefaultFormat"] = @"iPhone";
defaultValues[@"AlternateFormat"] = @"Flash - Standard";
defaultValues[@"CacheBBC_TV"] = @YES;
defaultValues[@"CacheITV_TV"] = @YES;
defaultValues[@"CacheBBC_Radio"] = @NO;
defaultValues[@"CacheBBC_Podcasts"] = @NO;
defaultValues[@"CacheExpiryTime"] = @"4";
defaultValues[@"Verbose"] = @NO;
defaultValues[@"SeriesLinkStartup"] = @YES;
defaultValues[@"DownloadSubtitles"] = @NO;
defaultValues[@"AlwaysUseProxy"] = @NO;
defaultValues[@"XBMC_naming"] = @NO;
defaultValues[@"KeepSeriesFor"] = @"30";
defaultValues[@"RemoveOldSeries"] = @NO;
defaultValues[@"QuickCache"] = @YES;
defaultValues[@"TagShows"] = @YES;
// TODO: remove 4oD
// set 4oD off by default
defaultValues[@"Cache4oD_TV"] = @NO;
defaultValues[@"TestProxy"] = @YES;
defaultValues[@"ShowDownloadedInSearch"] = @YES;
defaultValues[@"AudioDescribedNew"] = @NO;
defaultValues[@"SignedNew"] = @NO;
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
defaultValues = nil;
//Migrate old AudioDescribed option
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"AudioDescribed"]) {
[[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"AudioDescribedNew"];
[[NSUserDefaults standardUserDefaults] setObject:@YES forKey:@"SignedNew"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AudioDescribed"];
}
//Make sure Application Support folder exists
NSString *folder = @"~/Library/Application Support/Get iPlayer Automator/";
folder = [folder stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folder])
{
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:nil];
}
[fileManager changeCurrentDirectoryPath:folder];
//Install Plugins If Needed
NSString *pluginPath = [folder stringByAppendingPathComponent:@"plugins"];
if (/*![fileManager fileExistsAtPath:pluginPath]*/TRUE)
{
[logger addToLog:@"Installing/Updating Get_iPlayer Plugins..." :self];
NSString *providedPath = [[NSBundle mainBundle] bundlePath];
if ([fileManager fileExistsAtPath:pluginPath]) [fileManager removeItemAtPath:pluginPath error:NULL];
providedPath = [providedPath stringByAppendingPathComponent:@"/Contents/Resources/plugins"];
[fileManager copyItemAtPath:providedPath toPath:pluginPath error:nil];
}
//Initialize Arguments
getiPlayerPath = [[NSString alloc] initWithString:[[NSBundle mainBundle] bundlePath]];
getiPlayerPath = [getiPlayerPath stringByAppendingString:@"/Contents/Resources/get_iplayer.pl"];
runScheduled=NO;
quickUpdateFailed=NO;
nilToEmptyStringTransformer = [[NilToStringTransformer alloc] init];
nilToAsteriskTransformer = [[NilToStringTransformer alloc] initWithString:@"*"];
[NSValueTransformer setValueTransformer:nilToEmptyStringTransformer forName:@"NilToEmptyStringTransformer"];
[NSValueTransformer setValueTransformer:nilToAsteriskTransformer forName:@"NilToAsteriskTransformer"];
verbose = [[NSUserDefaults standardUserDefaults] boolForKey:@"Verbose"];
return self;
}
#pragma mark Delegate Methods
- (void)awakeFromNib
{
#ifdef __x86_64__
[itvTVCheckbox setEnabled:YES];
#else
[itvTVCheckbox setEnabled:NO];
[itvTVCheckbox setState:NSOffState];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:NO] forKey:@"CacheITV_TV"];
#endif
//Initialize Search Results Click Actions
[searchResultsTable setTarget:self];
[searchResultsTable setDoubleAction:@selector(addToQueue:)];
//Read Queue & Series-Link from File
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *folder = @"~/Library/Application Support/Get iPlayer Automator/";
folder = [folder stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath: folder] == NO)
{
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:nil];
}
// TODO: remove 4oD
// disable 4oD and delete CH4 cache
[[NSUserDefaults standardUserDefaults] setValue:@NO forKey:@"Cache4oD_TV"];
[ch4TVCheckbox setState:NSOffState];
[ch4TVCheckbox setEnabled:NO];
[fileManager removeItemAtPath:[folder stringByAppendingPathComponent:@"ch4.cache"] error:nil];
NSString *filename = @"Queue.automatorqueue";
NSString *filePath = [folder stringByAppendingPathComponent:filename];
NSDictionary * rootObject;
@try
{
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSArray *tempQueue = [rootObject valueForKey:@"queue"];
NSArray *tempSeries = [rootObject valueForKey:@"serieslink"];
lastUpdate = [rootObject valueForKey:@"lastUpdate"];
[queueController addObjects:tempQueue];
[pvrQueueController addObjects:tempSeries];
}
@catch (NSException *e)
{
[fileManager removeItemAtPath:filePath error:nil];
NSLog(@"Unable to load saved application data. Deleted the data file.");
rootObject=nil;
}
//Read Format Preferences
filename = @"Formats.automatorqueue";
filePath = [folder stringByAppendingPathComponent:filename];
@try
{
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
[radioFormatController addObjects:[rootObject valueForKey:@"radioFormats"]];
[tvFormatController addObjects:[rootObject valueForKey:@"tvFormats"]];
}
@catch (NSException *e)
{
[fileManager removeItemAtPath:filePath error:nil];
NSLog(@"Unable to load saved application data. Deleted the data file.");
rootObject=nil;
}
if (!tvFormats || !radioFormats) {
[BBCDownload initFormats];
}
// clear obsolete formats
NSMutableArray *tempTVFormats = [[NSMutableArray alloc] initWithArray:[tvFormatController arrangedObjects]];
for (TVFormat *tvFormat in tempTVFormats) {
if (!tvFormats[[tvFormat format]]) {
[tvFormatController removeObject:tvFormat];
}
}
NSMutableArray *tempRadioFormats = [[NSMutableArray alloc] initWithArray:[radioFormatController arrangedObjects]];
for (RadioFormat *radioFormat in tempRadioFormats) {
if (!radioFormats[[radioFormat format]]) {
[radioFormatController removeObject:radioFormat];
}
}
// TODO: Remove 4oD
BOOL hasCached4oD = [[rootObject valueForKey:@"hasUpdatedCacheFor4oD"] boolValue];
filename = @"ITVFormats.automator";
filePath = [folder stringByAppendingPathComponent:filename];
@try {
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
[itvFormatController addObjects:[rootObject valueForKey:@"itvFormats"]];
}
@catch (NSException *exception) {
[fileManager removeItemAtPath:filePath error:nil];
rootObject=nil;
}
//Adds Defaults to Type Preferences
if ([[tvFormatController arrangedObjects] count] == 0)
{
TVFormat *format1 = [[TVFormat alloc] init];
[format1 setFormat:@"Flash - HD"];
TVFormat *format2 = [[TVFormat alloc] init];
[format2 setFormat:@"Flash - Very High"];
TVFormat *format3 = [[TVFormat alloc] init];
[format3 setFormat:@"Flash - High"];
[tvFormatController addObjects:@[format1,format2,format3]];
}
if ([[radioFormatController arrangedObjects] count] == 0)
{
RadioFormat *format1 = [[RadioFormat alloc] init];
[format1 setFormat:@"Flash AAC - High"];
RadioFormat *format2 = [[RadioFormat alloc] init];
[format2 setFormat:@"Flash AAC - Standard"];
RadioFormat *format3 = [[RadioFormat alloc] init];
[format3 setFormat:@"Flash - MP3"];
[radioFormatController addObjects:@[format1,format2,format3]];
}
if ([[itvFormatController arrangedObjects] count] == 0)
{
TVFormat *format1 = [[TVFormat alloc] init];
[format1 setFormat:@"Flash - High"];
TVFormat *format2 = [[TVFormat alloc] init];
[format2 setFormat:@"Flash - Standard"];
TVFormat *format3 = [[TVFormat alloc] init];
[format3 setFormat:@"Flash - Low"];
TVFormat *format4 = [[TVFormat alloc] init];
[format4 setFormat:@"Flash - Very Low"];
[itvFormatController addObjects:@[format1,format2,format3,format4]];
}
//Growl Initialization
@try {
[GrowlApplicationBridge setGrowlDelegate:(id<GrowlApplicationBridgeDelegate>)@""];
}
@catch (NSException *e) {
NSLog(@"ERROR: Growl initialisation failed: %@: %@", [e name], [e description]);
[logger addToLog:[NSString stringWithFormat:@"ERROR: Growl initialisation failed: %@: %@", [e name], [e description]]];
}
//Populate Live TV Channel List
LiveTVChannel *bbcOne = [[LiveTVChannel alloc] initWithChannelName:@"BBC One"];
LiveTVChannel *bbcTwo = [[LiveTVChannel alloc] initWithChannelName:@"BBC Two"];
LiveTVChannel *bbcNews24 = [[LiveTVChannel alloc] initWithChannelName:@"BBC News 24"];
[liveTVChannelController setContent:@[bbcOne,bbcTwo,bbcNews24]];
[liveTVTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
//Remove SWFinfo
NSString *infoPath = @"~/.swfinfo";
infoPath = [infoPath stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath:infoPath]) [fileManager removeItemAtPath:infoPath error:nil];
if (hasCached4oD)
[self updateCache:nil];
else
[self updateCache:@""];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)application
{
return YES;
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (runDownloads)
{
NSAlert *downloadAlert = [NSAlert alertWithMessageText:@"Are you sure you wish to quit?"
defaultButton:@"No"
alternateButton:@"Yes"
otherButton:nil
informativeTextWithFormat:@"You are currently downloading shows. If you quit, they will be cancelled."];
NSInteger response = [downloadAlert runModal];
if (response == NSAlertDefaultReturn) return NSTerminateCancel;
}
else if (runUpdate && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"QuickCache"] boolValue])
{
NSAlert *updateAlert = [NSAlert alertWithMessageText:@"Are you sure?"
defaultButton:@"No"
alternateButton:@"Yes"
otherButton:nil
informativeTextWithFormat:@"Get iPlayer Automator is currently updating the cache."
@"If you proceed with quiting, some series-link information will be lost."
@"It is not reccommended to quit during an update. Are you sure you wish to quit?"];
NSInteger response = [updateAlert runModal];
if (response == NSAlertDefaultReturn) return NSTerminateCancel;
}
return NSTerminateNow;
}
- (BOOL)windowShouldClose:(id)sender
{
if ([sender isEqualTo:mainWindow])
{
if (runUpdate && ![[[NSUserDefaults standardUserDefaults] objectForKey:@"QuickCache"] boolValue])
{
NSAlert *updateAlert = [NSAlert alertWithMessageText:@"Are you sure?"
defaultButton:@"No"
alternateButton:@"Yes"
otherButton:nil
informativeTextWithFormat:@"Get iPlayer Automator is currently updating the cache."
@"If you proceed with quiting, some series-link information will be lost."
@"It is not reccommended to quit during an update. Are you sure you wish to quit?"];
NSInteger response = [updateAlert runModal];
if (response == NSAlertDefaultReturn) return NO;
else if (response == NSAlertAlternateReturn) return YES;
}
else if (runDownloads)
{
NSAlert *downloadAlert = [NSAlert alertWithMessageText:@"Are you sure you wish to quit?"
defaultButton:@"No"
alternateButton:@"Yes"
otherButton:nil
informativeTextWithFormat:@"You are currently downloading shows. If you quit, they will be cancelled."];
NSInteger response = [downloadAlert runModal];
if (response == NSAlertDefaultReturn) return NO;
else return YES;
}
return YES;
}
else return YES;
}
- (void)windowWillClose:(NSNotification *)note
{
if ([[note object] isEqualTo:mainWindow]) [application terminate:self];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
//End Downloads if Running
if (runDownloads)
[currentDownload cancelDownload:nil];
[self saveAppData];
}
- (void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)update
{
@try
{
[GrowlApplicationBridge notifyWithTitle:@"Update Available!"
description:[NSString stringWithFormat:@"Get iPlayer Automator %@ is available.",[update displayVersionString]]
notificationName:@"New Version Available"
iconData:nil
priority:0
isSticky:NO
clickContext:nil];
}
@catch (NSException *e) {
NSLog(@"ERROR: Growl notification failed (updater): %@: %@", [e name], [e description]);
[logger addToLog:[NSString stringWithFormat:@"ERROR: Growl notification failed (updater): %@: %@", [e name], [e description]]];
}
}
#pragma mark Cache Update
- (IBAction)updateCache:(id)sender
{
@try
{
[searchField setEnabled:NO];
[stopButton setEnabled:NO];
[startButton setEnabled:NO];
[pvrSearchField setEnabled:NO];
}
@catch (NSException *e) {
NSLog(@"NO UI: updateCache:");
}
if ((![[[NSUserDefaults standardUserDefaults] objectForKey:@"QuickCache"] boolValue] || quickUpdateFailed) && [[[NSUserDefaults standardUserDefaults] valueForKey:@"AlwaysUseProxy"] boolValue])
{
getiPlayerProxy = [[GetiPlayerProxy alloc] initWithLogger:logger];
[getiPlayerProxy loadProxyInBackgroundForSelector:@selector(updateCache:proxyDict:) withObject:sender onTarget:self silently:runScheduled];
}
else
{
[self updateCache:sender proxyDict:nil];
}
}
- (void)updateCache:(id)sender proxyDict:(NSDictionary *)proxyDict
{
getiPlayerProxy = nil;
// reset after proxy load
@try
{
[searchField setEnabled:YES];
[stopButton setEnabled:YES];
[startButton setEnabled:YES];
[pvrSearchField setEnabled:YES];
}
@catch (NSException *e) {
NSLog(@"NO UI: updateCache:proxyError:");
}
if (proxyDict && [proxyDict[@"error"] code] == kProxyLoadCancelled) {
[stopButton setEnabled:NO];
return;
}
runSinceChange=YES;
runUpdate=YES;
didUpdate=NO;
[mainWindow setDocumentEdited:YES];
NSArray *tempQueue = [queueController arrangedObjects];
for (Programme *show in tempQueue)
{
if (show.successful.boolValue)
{
[queueController removeObject:show];
}
}
//UI might not be loaded yet
@try
{
//Update Should Be Running:
[currentIndicator setIndeterminate:YES];
[currentIndicator startAnimation:nil];
[currentProgress setStringValue:@"Updating Program Indexes..."];
//Shouldn't search until update is done.
[searchField setEnabled:NO];
[stopButton setEnabled:NO];
[startButton setEnabled:NO];
[pvrSearchField setEnabled:NO];
}
@catch (NSException *e) {
NSLog(@"NO UI");
}
HTTPProxy *proxy;
if (proxyDict) {
proxy = proxyDict[@"proxy"];
}
if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"QuickCache"] boolValue] || quickUpdateFailed)
{
quickUpdateFailed=NO;
NSString *cacheExpiryArg;
if ([[sender class] isEqualTo:[@"" class]])
{
cacheExpiryArg = @"-e1";
}
else
{
cacheExpiryArg = [[NSString alloc] initWithFormat:@"-e%d", ([[[NSUserDefaults standardUserDefaults] objectForKey:@"CacheExpiryTime"] intValue]*3600)];
}
NSString *typeArgument = [[GetiPlayerArguments sharedController] typeArgumentForCacheUpdate:YES];
getiPlayerUpdateArgs = @[getiPlayerPath,cacheExpiryArg,typeArgument,@"--nopurge",[GetiPlayerArguments sharedController].profileDirArg];
if (proxy && [[[NSUserDefaults standardUserDefaults] valueForKey:@"AlwaysUseProxy"] boolValue])
{
getiPlayerUpdateArgs = [getiPlayerUpdateArgs arrayByAddingObject:[[NSString alloc] initWithFormat:@"-p%@", [proxy url]]];
}
[logger addToLog:@"Updating Program Index Feeds...\r" :self];
getiPlayerUpdateTask = [[NSTask alloc] init];
[getiPlayerUpdateTask setLaunchPath:@"/usr/bin/perl"];
[getiPlayerUpdateTask setArguments:getiPlayerUpdateArgs];
getiPlayerUpdatePipe = [[NSPipe alloc] init];
[getiPlayerUpdateTask setStandardOutput:getiPlayerUpdatePipe];
[getiPlayerUpdateTask setStandardError:getiPlayerUpdatePipe];
NSFileHandle *fh = [getiPlayerUpdatePipe fileHandleForReading];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(dataReady:)
name:NSFileHandleReadCompletionNotification
object:fh];
NSMutableDictionary *envVariableDictionary = [NSMutableDictionary dictionaryWithDictionary:[getiPlayerUpdateTask environment]];
envVariableDictionary[@"HOME"] = [@"~" stringByExpandingTildeInPath];
envVariableDictionary[@"PERL_UNICODE"] = @"AS";
[getiPlayerUpdateTask setEnvironment:envVariableDictionary];
[getiPlayerUpdateTask launch];
[fh readInBackgroundAndNotify];
}
else
{
[logger addToLog:@"Updating Program Index Feeds from Server..." :nil];
NSLog(@"DEBUG: Last cache update: %@",lastUpdate);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (!lastUpdate || ([[NSDate date] timeIntervalSinceDate:lastUpdate] > ([[defaults objectForKey:@"CacheExpiryTime"] intValue]*3600)) || [[sender class] isEqualTo:[@"" class]])
{
typesToCache = [[NSMutableArray alloc] initWithCapacity:5];
if ([[defaults objectForKey:@"CacheBBC_TV"] boolValue]) [typesToCache addObject:@"tv"];
if ([[defaults objectForKey:@"CacheITV_TV"] boolValue]) [typesToCache addObject:@"itv"];
if ([[defaults objectForKey:@"CacheBBC_Radio"] boolValue]) [typesToCache addObject:@"radio"];
if ([[defaults objectForKey:@"CacheBBC_Podcasts"] boolValue]) [typesToCache addObject:@"podcast"];
// TODO: Remove 4oD
if ([[defaults objectForKey:@"Cache4oD_TV"] boolValue]) [typesToCache addObject:@"ch4"];
NSArray *urlKeys = @[@"tv",@"itv",@"radio",@"podcast",@"ch4"];
NSArray *urlObjects = @[@"http://tom-tech.com/get_iplayer/cache/tv.cache",
@"http://tom-tech.com/get_iplayer/cache/itv.cache",
@"http://tom-tech.com/get_iplayer/cache/radio.cache",
@"http://tom-tech.com/get_iplayer/cache/podcast.cache",
@"http://tom-tech.com/get_iplayer/cache/ch4.cache"];
updateURLDic = [[NSDictionary alloc] initWithObjects:urlObjects forKeys:urlKeys];
nextToCache=0;
if ([typesToCache count] > 0)
[self updateCacheForType:typesToCache[0]];
}
else [self getiPlayerUpdateFinished];
}
}
- (void)updateCacheForType:(NSString *)type
{
[logger addToLog:[NSString stringWithFormat:@" Retrieving %@ index feeds.",type] :nil];
[currentProgress setStringValue:[NSString stringWithFormat:@"Updating Program Indexes: Getting %@ index feeds from server...",type]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:updateURLDic[type]]];
[request setDelegate:self];
[request setDidFinishSelector:@selector(indexRequestFinished:)];
[request setDidFailSelector:@selector(indexRequestFinished:)];
[request setTimeOutSeconds:10];
[request setNumberOfTimesToRetryOnTimeout:2];
[request setDownloadDestinationPath:[[@"~/Library/Application Support/Get iPlayer Automator" stringByExpandingTildeInPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.cache",type]]];
[request startAsynchronous];
}
- (void)indexRequestFinished:(ASIHTTPRequest *)request
{
if ([request responseStatusCode] != 200)
{
quickUpdateFailed=YES;
[self updateCache:@""];
}
else
{
didUpdate=YES;
nextToCache++;
if (nextToCache < [typesToCache count])
[self updateCacheForType:typesToCache[nextToCache]];
else
{
[self getiPlayerUpdateFinished];
}
}
}
- (void)dataReady:(NSNotification *)n
{
NSData *d;
d = [[n userInfo] valueForKey:NSFileHandleNotificationDataItem];
BOOL matches=NO;
if ([d length] > 0) {
NSString *s = [[NSString alloc] initWithData:d
encoding:NSUTF8StringEncoding];
if ([s hasPrefix:@"INFO:"])
{
[logger addToLog:[NSString stringWithString:s] :nil];
NSScanner *scanner = [NSScanner scannerWithString:s];
NSString *r;
[scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet] intoString:&r];
NSString *infoMessage = [[NSString alloc] initWithFormat:@"Updating Program Indexes: %@", r];
[currentProgress setStringValue:infoMessage];
infoMessage = nil;
scanner = nil;
}
else if ([s hasPrefix:@"WARNING:"] || [s hasPrefix:@"ERROR:"])
{
[logger addToLog:s :nil];
}
else if ([s isEqualToString:@"."])
{
NSMutableString *infomessage = [[NSMutableString alloc] initWithFormat:@"%@.", [currentProgress stringValue]];
if ([infomessage hasSuffix:@".........."]) [infomessage deleteCharactersInRange:NSMakeRange([infomessage length]-9, 9)];
[currentProgress setStringValue:infomessage];
infomessage = nil;
didUpdate = YES;
}
else if ([s hasPrefix:@"Matches:"])
{
matches=YES;
getiPlayerUpdateTask=nil;
[self getiPlayerUpdateFinished];
}
}
else
{
getiPlayerUpdateTask = nil;
[self getiPlayerUpdateFinished];
}
// If the task is running, start reading again
if (getiPlayerUpdateTask && !matches)
[[getiPlayerUpdatePipe fileHandleForReading] readInBackgroundAndNotify];
}
- (void)getiPlayerUpdateFinished
{
runUpdate=NO;
[mainWindow setDocumentEdited:NO];
[currentProgress setStringValue:@""];
[currentIndicator setIndeterminate:NO];
[currentIndicator stopAnimation:nil];
[searchField setEnabled:YES];
getiPlayerUpdatePipe = nil;
getiPlayerUpdateTask = nil;
[startButton setEnabled:YES];
[pvrSearchField setEnabled:YES];
if (didUpdate)
{
@try
{
[GrowlApplicationBridge notifyWithTitle:@"Index Updated"
description:@"The program index was updated."
notificationName:@"Index Updating Completed"
iconData:nil
priority:0
isSticky:NO
clickContext:nil];
}
@catch (NSException *e) {
NSLog(@"ERROR: Growl notification failed (getiPlayerUpdateFinished): %@: %@", [e name], [e description]);
[logger addToLog:[NSString stringWithFormat:@"ERROR: Growl notification failed (getiPlayerUpdateFinished): %@: %@", [e name], [e description]]];
}
[logger addToLog:@"Index Updated." :self];
lastUpdate=[NSDate date];
}
else
{
runSinceChange=NO;
[logger addToLog:@"Index was Up-To-Date." :self];
}
//Long, Complicated Bit of Code that updates the index number.
//This is neccessary because if the cache is updated, the index number will almost certainly change.
NSArray *tempQueue = [queueController arrangedObjects];
for (Programme *show in tempQueue)
{
BOOL foundMatch=NO;
if ([[show showName] length] > 0)
{
NSTask *pipeTask = [[NSTask alloc] init];
NSPipe *newPipe = [[NSPipe alloc] init];
NSFileHandle *readHandle2 = [newPipe fileHandleForReading];
NSData *someData;
NSString *name = [[show showName] copy];
NSScanner *scanner = [NSScanner scannerWithString:name];
NSString *searchArgument;
[scanner scanUpToString:@" - " intoString:&searchArgument];
// write handle is closed to this process
[pipeTask setStandardOutput:newPipe];
[pipeTask setStandardError:newPipe];
[pipeTask setLaunchPath:@"/usr/bin/perl"];
[pipeTask setArguments:@[getiPlayerPath,[GetiPlayerArguments sharedController].profileDirArg,@"--nopurge",[GetiPlayerArguments sharedController].noWarningArg,[[GetiPlayerArguments sharedController] typeArgumentForCacheUpdate:NO],[[GetiPlayerArguments sharedController] cacheExpiryArgument:nil],[GetiPlayerArguments sharedController].standardListFormat,
searchArgument]];
NSMutableString *taskData = [[NSMutableString alloc] initWithString:@""];
NSMutableDictionary *envVariableDictionary = [NSMutableDictionary dictionaryWithDictionary:[pipeTask environment]];
envVariableDictionary[@"HOME"] = [@"~" stringByExpandingTildeInPath];
envVariableDictionary[@"PERL_UNICODE"] = @"AS";
[pipeTask setEnvironment:envVariableDictionary];
[pipeTask launch];
while ((someData = [readHandle2 availableData]) && [someData length]) {
[taskData appendString:[[NSString alloc] initWithData:someData
encoding:NSUTF8StringEncoding]];
}
NSString *string = [NSString stringWithString:taskData];
NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *string in array)
{
if (![string isEqualToString:@"Matches:"] && ![string hasPrefix:@"INFO:"] && ![string hasPrefix:@"WARNING:"] && [string length]>0)
{
@try
{
NSScanner *myScanner = [NSScanner scannerWithString:string];
Programme *p = [[Programme alloc] init];
NSString *temp_pid, *temp_showName, *temp_tvNetwork, *temp_type, *url;
[myScanner scanUpToString:@":" intoString:&temp_pid];
[myScanner scanUpToString:@"," intoString:&temp_type];
[myScanner scanString:@", ~" intoString:NULL];
[myScanner scanUpToString:@"~," intoString:&temp_showName];
[myScanner scanString:@"~," intoString:NULL];
[myScanner scanUpToString:@"," intoString:&temp_tvNetwork];
[myScanner scanString:@"," intoString:nil];
[myScanner scanUpToString:@"kljkjkj" intoString:&url];
if ([temp_showName hasSuffix:@" - -"])
{
NSString *temp_showName2;
NSScanner *dashScanner = [NSScanner scannerWithString:temp_showName];
[dashScanner scanUpToString:@" - -" intoString:&temp_showName2];
temp_showName = temp_showName2;
temp_showName = [temp_showName stringByAppendingFormat:@" - %@", temp_showName2];
}
[p setValue:temp_pid forKey:@"pid"];
[p setValue:temp_showName forKey:@"showName"];
[p setValue:temp_tvNetwork forKey:@"tvNetwork"];
[p setUrl:url];
if ([temp_type isEqualToString:@"radio"]) [p setValue:@YES forKey:@"radio"];
if ([[p showName] isEqualToString:[show showName]] || ([[p url] isEqualToString:[show url]] && [show url]))
{
[show setValue:[p pid] forKey:@"pid"];
show.status = @"Available";
foundMatch=YES;
break;
}
}
@catch (NSException *e) {
NSAlert *searchException = [[NSAlert alloc] init];
[searchException addButtonWithTitle:@"OK"];
[searchException setMessageText:[NSString stringWithFormat:@"Invalid Output!"]];
[searchException setInformativeText:@"Please check your query. Your query must not alter the output format of Get_iPlayer. (getiPlayerUpdateFinished)"];
[searchException setAlertStyle:NSWarningAlertStyle];
[searchException runModal];
searchException = nil;
}
}
else
{
if ([string hasPrefix:@"Unknown option:"] || [string hasPrefix:@"Option"] || [string hasPrefix:@"Usage"])
{
NSLog(@"Unknown Option");
}
}
}
if (!foundMatch)
{
show.status = @"Processing...";
[show getName];
}
}
}
//Don't want to add these until the cache is up-to-date!
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SeriesLinkStartup"] boolValue])
{
NSLog(@"Checking series link");
[self addSeriesLinkToQueue:self];
}
else
{
if (runScheduled)
{
[self performSelectorOnMainThread:@selector(startDownloads:) withObject:self waitUntilDone:NO];
}
}
//Check for Updates - Don't want to prompt the user when updates are running.
SUUpdater *updater = [SUUpdater sharedUpdater];
[updater checkForUpdatesInBackground];
if (runDownloads)
{
[logger addToLog:@"Download(s) are still running." :self];
}
}
- (IBAction)forceUpdate:(id)sender
{
[self updateCache:@"force"];
}
#pragma mark Search
- (IBAction)goToSearch:(id)sender {
[mainWindow makeKeyAndOrderFront:self];
[mainWindow makeFirstResponder:searchField];
}
- (IBAction)mainSearch:(id)sender
{
if([searchField.stringValue length] > 0)
{
[searchField setEnabled:NO];
[searchIndicator startAnimation:nil];
[resultsController removeObjectsAtArrangedObjectIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [resultsController.arrangedObjects count])]];
currentSearch = [[GiASearch alloc] initWithSearchTerms:searchField.stringValue
allowHidingOfDownloadedItems:YES
logController:logger
selector:@selector(searchFinished:)
withTarget:self];
}
}
- (void)searchFinished:(NSArray *)results
{
[searchField setEnabled:YES];
[resultsController addObjects:results];
[resultsController setSelectionIndexes:[NSIndexSet indexSet]];
[searchIndicator stopAnimation:nil];
if (![results count])
{
NSAlert *noneFound = [NSAlert alertWithMessageText:@"No Shows Found"
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"0 shows were found for your search terms. Please check your spelling!"];
[noneFound runModal];
}
currentSearch = nil;
}
#pragma mark Queue
- (NSArray *)queueArray
{
return [NSArray arrayWithArray:queueArray];
}
- (void)setQueueArray:(NSArray *)queue
{
queueArray = [NSMutableArray arrayWithArray:queue];
}
- (IBAction)addToQueue:(id)sender
{
for (Programme *show in resultsController.selectedObjects)
{
if (![queueController.arrangedObjects containsObject:show])
{
if (runDownloads) show.status = @"Waiting...";
else show.status = @"Available";
[queueController addObject:show];
}
}
}
- (IBAction)getName:(id)sender
{
for (Programme *p in queueController.selectedObjects)
{
p.status = @"Processing...";
[p performSelectorInBackground:@selector(getName) withObject:nil];
}
}
- (IBAction)getCurrentWebpage:(id)sender
{
Programme *p = [GetCurrentWebpage getCurrentWebpage:logger];
if (p) [queueController addObject:p];
}
- (IBAction)removeFromQueue:(id)sender
{
//Check to make sure one of the shows isn't currently downloading.
if (runDownloads)
{
BOOL downloading=NO;
NSArray *selected = [queueController selectedObjects];
for (Programme *show in selected)
{
if (![[show status] isEqualToString:@"Waiting..."] && ![[show complete] isEqualToNumber:@YES])
{
downloading = YES;
}
}
if (downloading)
{
NSAlert *cantRemove = [NSAlert alertWithMessageText:@"A Selected Show is Currently Downloading."
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"You can not remove a show that is currently downloading. "
@"Please stop the downloads then remove the download if you wish to cancel it."];
[cantRemove runModal];
}
else
{
[queueController remove:self];
}
}
else
{
[queueController remove:self];
}
}
- (IBAction)hidePvrShow:(id)sender
{
NSArray *temp_queue = [queueController selectedObjects];
for (Programme *show in temp_queue)
{
if ([show realPID] && show.addedByPVR)
{
NSDictionary *info = @{@"Programme": show};
[[NSNotificationCenter defaultCenter] postNotificationName:@"AddProgToHistory" object:self userInfo:info];
[queueController removeObject:show];
}
}
}
#pragma mark Download Controller
- (IBAction)startDownloads:(id)sender
{
@try
{
[stopButton setEnabled:NO];
[startButton setEnabled:NO];
}
@catch (NSException *e) {
NSLog(@"NO UI: startDownloads:");
}
[self saveAppData]; //Save data in case of crash.
getiPlayerProxy = [[GetiPlayerProxy alloc] initWithLogger:logger];
[getiPlayerProxy loadProxyInBackgroundForSelector:@selector(startDownloads:proxyDict:) withObject:sender onTarget:self silently:runScheduled];
}
- (void)startDownloads:(id)sender proxyDict:(NSDictionary *)proxyDict
{
getiPlayerProxy = nil;
// reset after proxy load
@try
{
[stopButton setEnabled:YES];
}
@catch (NSException *e) {
NSLog(@"NO UI: startDownloads:proxyError:");
}
if (proxyDict && [proxyDict[@"error"] code] == kProxyLoadCancelled) {
[startButton setEnabled:YES];
[stopButton setEnabled:NO];
return;
}
if (proxyDict) {
proxy = proxyDict[@"proxy"];
}
NSAlert *whatAnIdiot = [NSAlert alertWithMessageText:@"No Shows in Queue!"
defaultButton:nil
alternateButton:nil
otherButton:nil
informativeTextWithFormat:@"Try adding shows to the queue before clicking start; "
@"Get iPlayer Automator needs to know what to download."];
if ([[queueController arrangedObjects] count] > 0)
{
NSLog(@"Initialising Failure Dictionary");
if (!solutionsDictionary)
solutionsDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ReasonsForFailure" ofType:@"plist"]];
NSLog(@"Failure Dictionary Ready");
BOOL foundOne=NO;
runDownloads=YES;
runScheduled=NO;
[mainWindow setDocumentEdited:YES];
[logger addToLog:@"\rAppController: Starting Downloads" :nil];
//Clean-Up Queue
NSArray *tempQueue = [queueController arrangedObjects];
for (Programme *show in tempQueue)
{
if ([[show successful] isEqualToNumber:@NO])
{
if ([[show processedPID] boolValue])
{
[show setComplete:@NO];
[show setStatus:@"Waiting..."];
foundOne=YES;
}
else
{
[show getNameSynchronous];
if ([[show showName] isEqualToString:@"Unknown - Not in Cache"])
{
[show setComplete:@YES];
[show setSuccessful:@NO];
[show setStatus:@"Failed: Please set the show name"];
[logger addToLog:@"Could not download. Please set a show name first." :self];
}
else
{
[show setComplete:@NO];
[show setStatus:@"Waiting..."];
foundOne=YES;
}
}
}
else