forked from Ascoware/get-iplayer-automator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppController.m
2249 lines (2053 loc) · 94.9 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 <Sparkle/Sparkle.h>
#import "HTTPProxy.h"
#import "Programme.h"
#import "Safari.h"
#import "iTunes.h"
#import <Growl/Growl.h>
#import "JRFeedbackController.h"
#import "ReasonForFailure.h"
#import "Chrome.h"
#import "ASIHTTPRequest.h"
#import "GetITVListings.h"
#import "NPHistoryWindowController.h"
static AppController *sharedController;
bool runDownloads=NO;
bool runUpdate=NO;
NSDictionary *tvFormats;
NSDictionary *radioFormats;
// New ITV Cache
GetITVShows *newITVListing;
NPHistoryTableViewController *npHistoryTableViewController;
NewProgrammeHistory *sharedHistoryController;
@implementation AppController
#pragma mark Overriden Methods
- (id)description
{
return @"AppController";
}
- (instancetype)init {
//Initialization
if (!(self = [super init])) return nil;
sharedController = self;
sharedHistoryController = [NewProgrammeHistory sharedInstance];
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"] = @"None";
defaultValues[@"CustomProxy"] = @"";
defaultValues[@"AutoRetryFailed"] = @YES;
defaultValues[@"AutoRetryTime"] = @"30";
defaultValues[@"AddCompletedToiTunes"] = @YES;
defaultValues[@"DefaultBrowser"] = @"Safari";
defaultValues[@"CacheBBC_TV"] = @YES;
defaultValues[@"CacheITV_TV"] = @YES;
defaultValues[@"CacheBBC_Radio"] = @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"] = @NO;
defaultValues[@"TagShows"] = @YES;
defaultValues[@"BBCOne"] = @YES;
defaultValues[@"BBCTwo"] = @YES;
defaultValues[@"BBCThree"] = @YES;
defaultValues[@"BBCFour"] = @YES;
defaultValues[@"BBCAlba"] = @NO;
defaultValues[@"S4C"] = @NO;
defaultValues[@"CBBC"] = @NO;
defaultValues[@"CBeebies"] = @NO;
defaultValues[@"BBCNews"] = @NO;
defaultValues[@"BBCParliament"] = @NO;
defaultValues[@"Radio1"] = @YES;
defaultValues[@"Radio2"] = @YES;
defaultValues[@"Radio3"] = @YES;
defaultValues[@"Radio4"] = @YES;
defaultValues[@"Radio4Extra"] = @YES;
defaultValues[@"Radio6Music"] = @YES;
defaultValues[@"BBCWorldService"] = @NO;
defaultValues[@"Radio5Live"] = @NO;
defaultValues[@"Radio5LiveSportsExtra"] = @NO;
defaultValues[@"Radio1Xtra"] = @NO;
defaultValues[@"RadioAsianNetwork"] = @NO;
defaultValues[@"ShowRegionalRadioStations"] = @NO;
defaultValues[@"ShowLocalRadioStations"] = @NO;
defaultValues[@"IgnoreAllTVNews"] = @YES;
defaultValues[@"IgnoreAllRadioNews"] = @YES;
defaultValues[@"ShowBBCTV"] = @YES;
defaultValues[@"ShowBBCRadio"] = @YES;
defaultValues[@"ShowITV"] = @YES;
defaultValues[@"TestProxy"] = @YES;
defaultValues[@"ShowDownloadedInSearch"] = @YES;
defaultValues[@"AudioDescribedNew"] = @NO;
defaultValues[@"SignedNew"] = @NO;
defaultValues[@"Use50FPSStreams"] = @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"];
}
// remove obsolete preferences
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"DefaultFormat"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AlternateFormat"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Cache4oD_TV"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CacheBBC_Podcasts"];
//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:@"*"];
_tvFormatTransformer = [[EmptyToStringTransformer alloc] initWithString:@"Please select..."];
_radioFormatTransformer = [[EmptyToStringTransformer alloc] initWithString:@"Please select..."];
_itvFormatTransformer = [[EmptyToStringTransformer alloc] initWithString:@"Please select..."];
[NSValueTransformer setValueTransformer:_nilToEmptyStringTransformer forName:@"NilToEmptyStringTransformer"];
[NSValueTransformer setValueTransformer:_nilToAsteriskTransformer forName:@"NilToAsteriskTransformer"];
[NSValueTransformer setValueTransformer:_tvFormatTransformer forName:@"TVFormatTransformer"];
[NSValueTransformer setValueTransformer:_radioFormatTransformer forName:@"RadioFormatTransformer"];
[NSValueTransformer setValueTransformer:_itvFormatTransformer forName:@"ITVFormatTransformer"];
_verbose = [[NSUserDefaults standardUserDefaults] boolForKey:@"Verbose"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itvUpdateFinished) name:@"ITVUpdateFinished" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forceITVUpdateFinished) name:@"ForceITVUpdateFinished" object:nil];
_forceITVUpdateInProgress = NO;
newITVListing = [[GetITVShows alloc] init];
return self;
}
#pragma mark Delegate Methods
- (void)awakeFromNib
{
//Initialize Search Results Click Actions
_searchResultsTable.target = self;
_searchResultsTable.doubleAction = @selector(addToQueue:);
_tvFormatList = [NSMutableArray array];
_itvFormatList = [NSMutableArray array];
_radioFormatList = [NSMutableArray array];
//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];
}
// remove obsolete cache files
[fileManager removeItemAtPath:[folder stringByAppendingPathComponent:@"ch4.cache"] error:nil];
[fileManager removeItemAtPath:[folder stringByAppendingPathComponent:@"podcast.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];
}
}
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.format = @"Best";
TVFormat *format2 = [[TVFormat alloc] init];
format2.format = @"Better";
TVFormat *format3 = [[TVFormat alloc] init];
format3.format = @"Very Good";
[_tvFormatController addObjects:@[format1,format2,format3]];
}
if ([_radioFormatController.arrangedObjects count] == 0)
{
RadioFormat *format1 = [[RadioFormat alloc] init];
format1.format = @"Best";
RadioFormat *format2 = [[RadioFormat alloc] init];
format2.format = @"Better";
RadioFormat *format3 = [[RadioFormat alloc] init];
format3.format = @"Very Good";
[_radioFormatController addObjects:@[format1,format2,format3]];
}
if ([_itvFormatController.arrangedObjects count] == 0)
{
TVFormat *format0 = [[TVFormat alloc] init];
format0.format = @"Flash - HD";
TVFormat *format1 = [[TVFormat alloc] init];
format1.format = @"Flash - Very High";
TVFormat *format2 = [[TVFormat alloc] init];
format2.format = @"Flash - High";
[_itvFormatController addObjects:@[format0, format1, format2]];
}
//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]];
}
//Remove SWFinfo
NSString *infoPath = @"~/.swfinfo";
infoPath = infoPath.stringByExpandingTildeInPath;
if ([fileManager fileExistsAtPath:infoPath]) [fileManager removeItemAtPath:infoPath error:nil];
[self updateCache:nil];
}
- (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 didFinishLoadingAppcast:(SUAppcast *)appcast
{
NSLog(@"didFinishLoadingAppcast");
}
- (void)updaterDidNotFindUpdate:(SUUpdater *)updater
{
NSLog(@"No update found.");
}
- (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];
[_addSeriesLinkToQueueButton setEnabled:NO];
[_refreshCacheButton setEnabled:NO];
[_forceCacheUpdateMenuItem setEnabled:NO];
[_checkForCacheUpdateMenuItem setEnabled:NO];
[_showNewProgrammesMenuItem setEnabled:NO];
if (!_forceITVUpdateMenuItem.hidden)
[_forceITVUpdateMenuItem 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];
[_addSeriesLinkToQueueButton setEnabled:YES];
[_refreshCacheButton setEnabled:YES];
[_forceCacheUpdateMenuItem setEnabled:YES];
[_checkForCacheUpdateMenuItem setEnabled:YES];
[_showNewProgrammesMenuItem setEnabled:YES];
if (!_forceITVUpdateMenuItem.hidden)
[_forceITVUpdateMenuItem 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];
//Shouldn't search until update is done.
[_searchField setEnabled:NO];
[_stopButton setEnabled:NO];
[_startButton setEnabled:NO];
[_searchField setEnabled:NO];
[_addSeriesLinkToQueueButton setEnabled:NO];
[_refreshCacheButton setEnabled:NO];
[_forceCacheUpdateMenuItem setEnabled:NO];
[_checkForCacheUpdateMenuItem setEnabled:NO];
[_showNewProgrammesMenuItem setEnabled:NO];
if (!_forceITVUpdateMenuItem.hidden)
[_forceITVUpdateMenuItem setEnabled:NO];
}
@catch (NSException *e) {
NSLog(@"NO UI");
}
if (proxyDict) {
_proxy = proxyDict[@"proxy"];
}
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"CacheITV_TV"] isEqualTo:@YES])
{
_updatingITVIndex = true;
[self.itvProgressIndicator startAnimation:self];
self.itvProgressIndicator.doubleValue = 0.0;
[self.itvProgressIndicator setHidden:false];
[_itvProgressText setHidden:false];
[newITVListing itvUpdateWithLogger:_logger];
}
_updatingBBCIndex = true;
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 andIncludeITV:NO];
if (![typeArgument isEqualToString:@"--type"]) {
_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 Programme Index Feeds...\r" :self];
_currentProgress.stringValue = @"Updating Programme Index Feeds...";
_getiPlayerUpdateTask = [[NSTask alloc] init];
_getiPlayerUpdateTask.launchPath = @"/usr/bin/perl";
_getiPlayerUpdateTask.arguments = _getiPlayerUpdateArgs;
_getiPlayerUpdatePipe = [[NSPipe alloc] init];
_getiPlayerUpdateTask.standardOutput = _getiPlayerUpdatePipe;
_getiPlayerUpdateTask.standardError =_getiPlayerUpdatePipe;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(dataReady:)
name:NSFileHandleReadCompletionNotification
object:_getiPlayerUpdatePipe.fileHandleForReading];
[_getiPlayerUpdatePipe.fileHandleForReading readInBackgroundAndNotify];
NSMutableDictionary *envVariableDictionary = [NSMutableDictionary dictionaryWithDictionary:_getiPlayerUpdateTask.environment];
envVariableDictionary[@"HOME"] = (@"~").stringByExpandingTildeInPath;
envVariableDictionary[@"PERL_UNICODE"] = @"AS";
_updatingBBCIndex = true;
_getiPlayerUpdateTask.environment = envVariableDictionary;
[_getiPlayerUpdateTask launch];
}
else
{
_updatingBBCIndex = false;
[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];
NSArray *lines = [s componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
if ([line hasPrefix:@"INFO:"])
{
[_logger addToLog:line];
NSString *actualMessage = [line substringFromIndex:5];
NSString *infoMessage = [[NSString alloc] initWithFormat:@"Updating Programme Indexes: %@", actualMessage];
_currentProgress.stringValue = infoMessage;
}
else if ([line hasPrefix:@"WARNING:"] || [line hasPrefix:@"ERROR:"])
{
[_logger addToLog:s :nil];
}
else if ([line isEqualToString:@"."])
{
NSMutableString *infomessage = [[NSMutableString alloc] initWithFormat:@"%@.", _currentProgress.stringValue];
if ([infomessage hasSuffix:@".........."]) [infomessage deleteCharactersInRange:NSMakeRange(infomessage.length-9, 9)];
_currentProgress.stringValue = infomessage;
_didUpdate = YES;
}
else if ([line hasPrefix:@"Matches:"])
{
matches=YES;
_getiPlayerUpdateTask=nil;
_updatingBBCIndex = false;
[self getiPlayerUpdateFinished];
}
}
}
else
{
_getiPlayerUpdateTask = nil;
_updatingBBCIndex = false;
[self getiPlayerUpdateFinished];
}
// If the task is running, start reading again
if (_getiPlayerUpdateTask && !matches) {
[_getiPlayerUpdatePipe.fileHandleForReading readInBackgroundAndNotify];
}
}
- (void)itvUpdateFinished
{
// ITV Cache Update Finished - turn off progress display and process data
_updatingITVIndex = false;
_didUpdate = YES;
[self.itvProgressIndicator stopAnimation:self];
[self.itvProgressIndicator setHidden:true];
[_itvProgressText setHidden:true];
[self getiPlayerUpdateFinished];
}
- (void)getiPlayerUpdateFinished
{
if (_updatingITVIndex || _updatingBBCIndex)
return;
runUpdate=NO;
[_mainWindow setDocumentEdited:NO];
_getiPlayerUpdatePipe = nil;
_getiPlayerUpdateTask = nil;
_currentProgress.stringValue = @"";
[_currentIndicator setIndeterminate:NO];
[_currentIndicator stopAnimation:nil];
[_searchField setEnabled:YES];
[_startButton setEnabled:YES];
[_searchField setEnabled:YES];
[_addSeriesLinkToQueueButton setEnabled:YES];
[_refreshCacheButton setEnabled:YES];
[_forceCacheUpdateMenuItem setEnabled:YES];
[_checkForCacheUpdateMenuItem setEnabled:YES];
[_showNewProgrammesMenuItem setEnabled:YES];
if (!_forceITVUpdateMenuItem.hidden)
[_forceITVUpdateMenuItem 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];
[self updateHistory];
}
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.standardOutput = newPipe;
pipeTask.standardError = newPipe;
pipeTask.launchPath = @"/usr/bin/perl";
pipeTask.arguments = @[_getiPlayerPath,[GetiPlayerArguments sharedController].profileDirArg,@"--nopurge",[GetiPlayerArguments sharedController].noWarningArg,[[GetiPlayerArguments sharedController] typeArgumentForCacheUpdate:NO andIncludeITV:YES],[[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.environment = 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 hasPrefix:@"reading"]
&& 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.url = url;
if ([temp_type isEqualToString:@"radio"]) [p setValue:@YES forKey:@"radio"];
if ( [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.messageText = [NSString stringWithFormat:@"Invalid Output!"];
searchException.informativeText = @"Please check your query. Your query must not alter the output format of Get_iPlayer. (getiPlayerUpdateFinished)";
searchException.alertStyle = 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.delegate = self;
[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
- (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) {
/* don't allow duplicates */
NSArray *tempQueue = _queueController.arrangedObjects;
BOOL foundIt = false;
for (Programme *show in tempQueue)
if ( [show.pid isEqualToString:p.pid] )
foundIt = true;
if ( !foundIt )
[_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"]];