-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppController.m
1513 lines (1260 loc) · 51.4 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
//
// QMController.m
// QueueManager
//
// Created by Cory Powers on 12/20/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "AppController.h"
#import "SystemEvents.h"
#import "StringToNumberTransformer.h"
#import "TheTVDBProvider.h"
#import "TheMovieDBProvider.h"
#import "PrefController.h"
#import "QueueController.h"
#import "QueueItem.h"
#import "MediaItem.h"
#define FolderActionScriptName @"add to transcoding machine.scpt"
#define EncodeStatusFilename @"tm_encoder.log"
const NSString *QMErrorDomain = @"QMErrors";
@implementation AppController
@synthesize delegate;
@synthesize metadataProvider;
- (id)init{
self = [super init];
if( !self ){
return nil;
}
// create an autoreleased instance of our value transformer
StringToNumberTransformer *sToNTransformer = [[StringToNumberTransformer alloc] init];
// register it with the name that we refer to it with
[NSValueTransformer setValueTransformer:sToNTransformer
forName:@"StringToNumberTransformer"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskEnded:)
name:NSTaskDidTerminateNotification
object:nil];
runQueue = TRUE;
terminating = FALSE;
encodeProgress = 0.0;
encodeETA = @"--h--m--s";
/* Check for check for the app support directory here as
* outputPanel needs it right away, as may other future methods
*/
NSString *libraryDir = NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
NSUserDomainMask,
YES )[0];
NSArray *appSupportURLs = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
NSURL *appSupportURL;
if (appSupportURLs.count > 0) {
appSupportURL = appSupportURLs[0];
}
appSupportDir = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
stringByAppendingPathComponent:@"TranscodingMachine"];
if( ![[NSFileManager defaultManager] fileExistsAtPath:appSupportDir] ){
[[NSFileManager defaultManager] createDirectoryAtPath:appSupportDir
attributes:nil];
}
appResourceDir = [[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"Resources"];
[PrefController registerUserDefaults: appSupportDir];
encodeStatusFile = [appSupportDir stringByAppendingPathComponent:EncodeStatusFilename];
NSLog(@"Using output file: %@", encodeStatusFile);
// Initialize controllers
prefController = [[PrefController alloc] initWithController: self];
queueController = [[QueueController alloc] initWithController: self];
return self;
}
/**
Returns the support directory for the application, used to store the Core Data
store file. This code uses a directory named "QueueManager" for
the content, either in the NSApplicationSupportDirectory location or (if the
former cannot be found), the system's temporary directory.
*/
- (NSString *)applicationSupportDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? paths[0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:@"TranscodingMachine"];
}
/**
Creates, retains, and returns the managed object model for the application
by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel) return managedObjectModel;
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application. This
implementation will create and return a coordinator, having added the
store for the application to it. (The directory for the store is created,
if necessary.)
*/
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
if (persistentStoreCoordinator) return persistentStoreCoordinator;
NSManagedObjectModel *mom = [self managedObjectModel];
if (!mom) {
NSAssert(NO, @"Managed object model is nil");
NSLog(@"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
if ( ![fileManager fileExistsAtPath:applicationSupportDirectory isDirectory:NULL] ) {
if (![fileManager createDirectoryAtPath:applicationSupportDirectory withIntermediateDirectories:NO attributes:nil error:&error]) {
NSAssert(NO, ([NSString stringWithFormat:@"Failed to create App Support directory %@ : %@", applicationSupportDirectory,error]));
NSLog(@"Error creating application support directory at %@ : %@",applicationSupportDirectory,error);
return nil;
}
}
NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"storedata"]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: mom];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType
configuration:nil
URL:url
options:nil
error:&error]){
[[NSApplication sharedApplication] presentError:error];
persistentStoreCoordinator = nil;
return nil;
}
return persistentStoreCoordinator;
}
/**
Returns the managed object context for the application (which is already
bound to the persistent store coordinator for the application.)
*/
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext) return managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
return managedObjectContext;
}
/**
Returns the NSUndoManager for the application. In this case, the manager
returned is that of the managed object context for the application.
*/
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
return [[self managedObjectContext] undoManager];
}
/**
Performs the save action for the application, which is to send the save:
message to the application's managed object context. Any encountered errors
are presented to the user.
*/
- (IBAction) saveAction:(id)sender {
NSError *error = nil;
if (![[self managedObjectContext] commitEditing]) {
NSLog(@"%@:%@ unable to commit editing before saving", [self class], NSStringFromSelector(_cmd));
}
if (![[self managedObjectContext] save:&error]) {
[[NSApplication sharedApplication] presentError:error];
}
}
/**
Implementation of the applicationShouldTerminate: method, used here to
handle the saving of changes in the application managed object context
before the application terminates.
*/
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
if ([self isEncodeRunning]) {
NSInteger returnCode = NSRunAlertPanel(@"Encode in progress", @"An encoding process is currently running, if you continue the encoding process will be canceled!\n Are you sure you want to quit?", @"Cancel", @"Quit", nil);
if (returnCode == NSAlertAlternateReturn) {
[self stopEncode];
terminating = TRUE;
return NSTerminateLater;
}
}
if (!managedObjectContext) return NSTerminateNow;
if (![managedObjectContext commitEditing]) {
NSLog(@"%@:%@ unable to commit editing to terminate", [self class], NSStringFromSelector(_cmd));
return NSTerminateCancel;
}
if (![managedObjectContext hasChanges]) return NSTerminateNow;
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// This error handling simply presents error information in a panel with an
// "Ok" button, which does not include any attempt at error recovery (meaning,
// attempting to fix the error.) As a result, this implementation will
// present the information to the user and then follow up with a panel asking
// if the user wishes to "Quit Anyway", without saving the changes.
// Typically, this process should be altered to include application-specific
// recovery steps.
BOOL result = [sender presentError:error];
if (result) return NSTerminateCancel;
NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:question];
[alert setInformativeText:info];
[alert addButtonWithTitle:quitButton];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
alert = nil;
if (answer == NSAlertAlternateReturn) return NSTerminateCancel;
}
return NSTerminateNow;
}
- (void)applicationDidFinishLaunching: (NSNotification *)aNotification{
// Check for our folder action script
NSString *folderActionDest = [@"/Library/Scripts/Folder Action Scripts" stringByAppendingPathComponent:FolderActionScriptName];
NSLog(@"Looking for folder action script at %@", folderActionDest);
if(![[NSFileManager defaultManager] fileExistsAtPath: folderActionDest]){
NSString *folderActionSource = [appResourceDir stringByAppendingPathComponent:FolderActionScriptName];
NSLog(@"NOT FOUND: Copying script from %@", folderActionSource);
NSError *error;
if (![[NSFileManager defaultManager] copyItemAtPath:folderActionSource toPath:folderActionDest error:&error]) {
NSAlert *theAlert = [NSAlert alertWithError:error];
[theAlert runModal]; // Ignore return value.
}
}
}
#pragma mark ===== Encode Management ======
- (BOOL)runQueue{
if ([self isEncodeRunning]) {
return NO;
}
// Start the next item
if (runQueue == TRUE) {
QueueItem *nextItem = [self nextQueueItem];
BOOL foundItem = NO;
while (foundItem == NO) {
// TODO: Make sure filesize is stable;
if([self startEncode:nextItem]){
foundItem = YES;
}else {
nextItem = [self nextQueueItemAfterItem:nextItem];
if (nextItem == nil) {
return NO;
}
}
}
return [self isEncodeRunning];
}
return NO;
}
- (BOOL)startEncode:(QueueItem *)anItem {
if ([self isEncodeRunning]) {
NSLog(@"Encoding is already running");
return NO;
}
if(anItem == nil){
NSLog(@"nil item passed to startEncode");
return NO;
}
// Restart the automatic queue running
runQueue = TRUE;
NSError *error;
// Clean up old status file
NSFileManager *defaultManger = [NSFileManager defaultManager];
if ([defaultManger fileExistsAtPath:encodeStatusFile]) {
NSLog(@"Removing old log file %@", encodeStatusFile);
[defaultManger removeItemAtPath:encodeStatusFile
error:&error];
}
[[NSFileManager defaultManager] createFileAtPath:encodeStatusFile contents:nil attributes:nil];
encodeProgress = 0.0;
// make task object
encodingTask = [[NSTask alloc] init];
encodingItem = anItem;
// make stdout file
NSFileHandle *taskStdout = [NSFileHandle fileHandleForWritingAtPath:encodeStatusFile];
[encodingTask setStandardOutput:taskStdout];
[encodingTask setStandardError:taskStdout];
// set arguments
NSString *argString = [[NSUserDefaults standardUserDefaults] stringForKey:@"transcoderArgs"];
NSArray *argArray = [argString componentsSeparatedByString:@" "];
NSMutableArray *taskArgs = [NSMutableArray array];
for(NSString *inputArg in argArray){
if ([inputArg isEqual:@"|INPUT|"]) {
[taskArgs addObject: anItem.mediaItem.input];
}else if ([inputArg isEqual:@"|OUTPUT|"]) {
[taskArgs addObject: anItem.mediaItem.output];
}else{
[taskArgs addObject:inputArg];
}
}
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[encodingTask setArguments:taskArgs];
// launch
[encodingTask setLaunchPath:[[NSUserDefaults standardUserDefaults] stringForKey:@"transcoderPath"]];
[encodingTask launch];
[encodingItem setStatus:@1];
[self saveAction:nil];
// Check to make sure there wasn't an immediate failure
if ([self isEncodeRunning]) {
// Store the pid in case we die
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:@([encodingTask processIdentifier]) forKey:@"encodePid"];
[queueController updateEncodeProgress:0.0 withEta:nil ofItem:[self encodingItem]];
// Setup the timer and status file
outputReadTimer = [NSTimer scheduledTimerWithTimeInterval: 2
target: self
selector:@selector(encodeProgressTimer:)
userInfo: nil
repeats: TRUE];
encodeOutputHandle = [NSFileHandle fileHandleForReadingAtPath:encodeStatusFile];
return YES;
}
return NO;
}
- (void)encodeProgressTimer:(NSTimer*)theTimer{
// Read the last line
NSLog(@"Output read timer fired");
NSString *fileData = [[NSString alloc] initWithData:[encodeOutputHandle readDataToEndOfFile]
encoding:NSASCIIStringEncoding];
NSArray *lines = [fileData componentsSeparatedByString:@"\r"];
NSLog(@"Found %ld lines", (unsigned long)[lines count]);
NSString *lastLine = lines[[lines count] - 1];
NSLog(@"Last line: %@", lastLine);
// Extract required info from last line
NSString *encodeProgressString;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString* regexString = @".*, (\\d+.\\d+) %.*ETA ([\\dhms]+).*";
NSRegularExpressionOptions options = NSRegularExpressionCaseInsensitive;
NSError* error = NULL;
NSRegularExpression* progressRegex = [NSRegularExpression regularExpressionWithPattern:regexString options:options error:&error];
if (error) {
NSLog(@"Error setting up regex: %@", error.localizedDescription);
}
encodeProgress = 0.0;
encodeETA = @"--h--m--s";
NSTextCheckingResult *firstMatch = [progressRegex firstMatchInString:lastLine options:options range:NSMakeRange(0, lastLine.length)];
if (firstMatch.range.location != NSNotFound) {
NSRange progressStringRange = [firstMatch rangeAtIndex:1];
NSRange encodeETARange = [firstMatch rangeAtIndex:2];
if (progressStringRange.location != NSNotFound && encodeETARange.location != NSNotFound) {
encodeProgressString = [lastLine substringWithRange:progressStringRange];
encodeProgress = [[formatter numberFromString:encodeProgressString] doubleValue];
encodeETA = [lastLine substringWithRange:encodeETARange];
[queueController updateEncodeProgress:encodeProgress withEta:encodeETA ofItem:[self encodingItem]];
NSLog(@"Current progress %f, eta %@", encodeProgress, encodeETA);
}else{
NSLog(@"Could not determine progress from line: %@", lastLine);
}
}else{
NSLog(@"Could not determine progress from line: %@", lastLine);
}
}
- (BOOL)isEncodeRunning {
if (encodingItem != nil && encodingTask != nil) {
return TRUE;
}
return FALSE;
}
- (void)taskEnded:(NSNotification *)aNotification {
NSTask *notifyingTask = [aNotification object];
NSError *error;
int status = [notifyingTask terminationStatus];
if (notifyingTask == encodingTask) {
QueueItem *currentItem = [self encodingItem];
NSLog(@"The encoding task has stopped");
BOOL encodeSucceeded = NO;
if (status == 0){
// See if output file exists. Sometimes handbrake exits with 0 code without working
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: currentItem.mediaItem.output]){
encodeSucceeded = YES;
NSLog(@"Task succeeded.");
}
}
// Clear out our cached encode pid
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:@0 forKey:@"encodePid"];
// Update the queue item's status
[queueController encodeEnded];
// Clean up
[outputReadTimer invalidate];
outputReadTimer = nil;
encodingItem = nil;
encodingTask = nil;
encodeOutputHandle = nil;
if (encodeSucceeded == YES) {
[self setHDFlag:currentItem.mediaItem error:&error];
[self writeMetadata:currentItem.mediaItem error:&error];
[currentItem setStatus:@255];
}else {
NSFileHandle *logHandle = [NSFileHandle fileHandleForReadingAtPath:encodeStatusFile];
NSString *fileData = [[NSString alloc] initWithData:[logHandle readDataToEndOfFile]
encoding:NSASCIIStringEncoding];
currentItem.mediaItem.message = fileData;
currentItem.status = @3;
}
[self saveAction:nil];
// If the user requested to terminate then do so
if (terminating == TRUE) {
[[NSApplication sharedApplication] replyToApplicationShouldTerminate: YES];
}else {
[self runQueue];
}
}else if(notifyingTask == metadataTask){
NSLog(@"metadata task ended with status %d", status);
[metadataReadTimer invalidate];
metadataReadTimer = nil;
metadataTask = nil;
metadataOutputHandle = nil;
if(status == 0){
[progressLabel setStringValue:@"Writing cover art to file...."];
[self writeArt:metadataItem error:&error];
}
if (self.delegate != nil) {
[self.delegate metadataDidComplete:metadataItem];
}
[progressWindow orderOut:nil];
metadataItem = nil;
}
}
- (void)metadataProgressTimer:(NSTimer*)theTimer{
// No way to get progress
return;
// Read the last line
NSString *fileData;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
fileData = [[NSString alloc] initWithData:[metadataOutputHandle readDataToEndOfFile]
encoding:NSASCIIStringEncoding];
NSLog(@"File Data: %@", fileData);
NSArray *lines = [fileData componentsSeparatedByString:@"\r"];
NSLog(@"Found %ld lines", (unsigned long)[lines count]);
NSString *lastLine = lines[[lines count] - 1];
if ([lastLine isEqualToString:@""] && [lines count] > 1) {
NSLog(@"Using previous line");
lastLine = lines[[lines count] - 2];
}
NSLog(@"Last line: %@", lastLine);
// Extract required info from last line
NSString *progressString;
NSString* regexString = @"(\\d+)";
NSRegularExpressionOptions options = NSRegularExpressionCaseInsensitive;
NSError* error = NULL;
NSRegularExpression* progressRegex = [NSRegularExpression regularExpressionWithPattern:regexString options:options error:&error];
if (error) {
NSLog(@"Error setting up regex: %@", error.localizedDescription);
}
NSTextCheckingResult *firstMatch = [progressRegex firstMatchInString:lastLine options:options range:NSMakeRange(0, lastLine.length)];
if (firstMatch.range.location != NSNotFound) {
NSRange progressStringRange = [firstMatch rangeAtIndex:1];
if (progressStringRange.location != NSNotFound) {
progressString = [lastLine substringWithRange:progressStringRange];
[progressBar setIndeterminate:NO];
[progressBar setDoubleValue:[[formatter numberFromString:progressString] doubleValue]];
}else{
NSLog(@"Could not determine progress from line: %@", lastLine);
}
}else{
NSLog(@"Could not determine progress from line: %@", lastLine);
}
}
- (BOOL) cleanOldTags: (MediaItem *)anItem error:(NSError **) outError{
if(anItem == nil){
NSLog(@"cleanOldTags received nil MediaItem!");
}
NSTask *cleanTask = [[NSTask alloc] init];
// set arguments
NSMutableArray *taskArgs = [NSMutableArray array];
[taskArgs addObject:anItem.output];
[taskArgs addObject:@"--overWrite"];
[taskArgs addObject:@"--artwork"];
[taskArgs addObject:@"REMOVE_ALL"];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[cleanTask setArguments:taskArgs];
// launch
[cleanTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"AtomicParsley"]];
[cleanTask launch];
while ([cleanTask isRunning]) {
sleep(1);
}
NSLog(@"art clear task ended with status %d", [cleanTask terminationStatus]);
return YES;
}
- (BOOL) writeMetadata: (MediaItem *)anItem error:(NSError **) outError {
NSString *metadataLogPath = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"metadata.log"];
[[NSFileManager defaultManager] createFileAtPath:metadataLogPath contents:nil attributes:nil];
metadataTask = [[NSTask alloc] init];
NSFileHandle *taskStdout = [NSFileHandle fileHandleForWritingAtPath:metadataLogPath];
[metadataTask setStandardOutput:taskStdout];
[metadataTask setStandardError:taskStdout];
[progressLabel setStringValue:@"Preparing to write new tags..."];
[progressWindow makeKeyAndOrderFront:nil];
// set arguments
NSMutableArray *taskArgs = [NSMutableArray array];
if ([anItem episodeId] != [NSString string]) {
[taskArgs addObject:@"-o"];
[taskArgs addObject: [anItem episodeId]];
}
if ([anItem hdVideo] != nil) {
[taskArgs addObject:@"-H"];
[taskArgs addObject: [[anItem hdVideo] stringValue]];
}
if ([anItem title] != nil) {
[taskArgs addObject:@"-s"];
[taskArgs addObject: [anItem title]];
}
if ([anItem showName] != nil) {
[taskArgs addObject:@"-a"];
[taskArgs addObject: [anItem showName]];
[taskArgs addObject:@"-S"];
[taskArgs addObject: [anItem showName]];
}
if ([anItem releaseDate] != nil) {
[taskArgs addObject:@"-y"];
[taskArgs addObject: [anItem releaseDate]];
}
if ([anItem summary] != nil) {
[taskArgs addObject:@"-m"];
[taskArgs addObject: [anItem longDescription]];
}
if ([anItem longDescription] != nil) {
[taskArgs addObject:@"-l"];
[taskArgs addObject: [anItem longDescription]];
}
if ([anItem episode] != nil) {
[taskArgs addObject:@"-t"];
[taskArgs addObject: [[anItem episode] stringValue]];
[taskArgs addObject:@"-M"];
[taskArgs addObject: [[anItem episode] stringValue]];
}
if ([anItem network] != nil) {
[taskArgs addObject:@"-N"];
[taskArgs addObject: [anItem network]];
}
if ([anItem season] != nil) {
[taskArgs addObject:@"-n"];
[taskArgs addObject: [[anItem season] stringValue]];
[taskArgs addObject:@"-d"];
[taskArgs addObject: [[anItem season] stringValue]];
}
[taskArgs addObject:@"-i"];
if ([[anItem type] intValue] == ItemTypeTV) {
[taskArgs addObject:@"tvshow"];
}else {
[taskArgs addObject:@"movie"];
}
[taskArgs addObject:[anItem output]];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[metadataTask setArguments:taskArgs];
// launch
[metadataTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"mp4tags"]];
[metadataTask launch];
if ([metadataTask isRunning]) {
metadataItem = anItem;
[progressLabel setStringValue:@"Writing metadata to output file..."];
[progressBar setIndeterminate:YES];
[progressBar setDoubleValue:0.0];
}
return YES;
}
- (BOOL) writeArt: (MediaItem *)anItem error:(NSError **) outError {
if(anItem == nil){
NSLog(@"writeArt received nil MediaItem!");
}
if(anItem.coverArt == nil){
return YES;
}
NSTask *mp4artTask = [[NSTask alloc] init];
NSString *tempArtPath = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"coverart.jpg"];
if([anItem.coverArt writeToFile:tempArtPath atomically:NO] == NO){
return NO;
};
// set arguments
NSMutableArray *taskArgs = [NSMutableArray array];
[taskArgs addObject:@"--keepgoing"];
[taskArgs addObject:@"--remove"];
[taskArgs addObject:@"--art-any"];
[taskArgs addObject:anItem.output];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[mp4artTask setArguments:taskArgs];
// launch
[mp4artTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"mp4art"]];
[mp4artTask launch];
while ([mp4artTask isRunning]) {
sleep(1);
}
NSLog(@"art clear task ended with status %d", [mp4artTask terminationStatus]);
NSTask *mp4artAddTask = [[NSTask alloc] init];
[taskArgs removeAllObjects];
[taskArgs addObject:@"--keepgoing"];
[taskArgs addObject:@"--add"];
[taskArgs addObject:tempArtPath];
[taskArgs addObject:@"--art-index"];
[taskArgs addObject:@"0"];
[taskArgs addObject:anItem.output];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[mp4artAddTask setArguments:taskArgs];
// launch
[mp4artAddTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"mp4art"]];
[mp4artAddTask launch];
while ([mp4artAddTask isRunning]) {
sleep(1);
}
NSLog(@"art add task ended with status %d", [mp4artAddTask terminationStatus]);
return YES;
}
- (BOOL) setHDFlag: (MediaItem *)anItem error:(NSError **) outError {
NSTask *mp4trackTask = [[NSTask alloc] init];
NSPipe *mp4trackStdoutPipe = [NSPipe pipe];
NSFileHandle *mp4trackStdoutHandle = [mp4trackStdoutPipe fileHandleForReading];
[mp4trackTask setStandardOutput:mp4trackStdoutPipe];
// set arguments
NSMutableArray *taskArgs = [NSMutableArray array];
[taskArgs addObject:@"--list"];
[taskArgs addObject:anItem.output];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[mp4trackTask setArguments:taskArgs];
// launch
[mp4trackTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"mp4track"]];
[mp4trackTask launch];
NSData *outputData = nil;
while ([mp4trackTask isRunning]) {
sleep(1);
}
outputData = [mp4trackStdoutHandle readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData:outputData encoding:NSASCIIStringEncoding];
NSArray *lines = [output componentsSeparatedByString:@"\n"];
NSLog(@"Found %ld lines", (unsigned long)[lines count]);
NSString *keyName = nil;
NSString *value = nil;
NSNumber *width = nil;
BOOL foundVideo = NO;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString* regexString = @"\\s*([a-zA-Z]+)\\s*=\\s*([a-zA-Z0-9]+)";
NSRegularExpressionOptions options = NSRegularExpressionCaseInsensitive;
NSError* error = NULL;
NSRegularExpression* keyValueRegex = [NSRegularExpression regularExpressionWithPattern:regexString options:options error:&error];
if (error) {
NSLog(@"Error setting up regex: %@", error.localizedDescription);
}
for(NSString *line in lines){
NSLog(@"Looking at line %@", line);
keyName = @"";
value = @"";
NSTextCheckingResult *firstMatch = [keyValueRegex firstMatchInString:line options:options range:NSMakeRange(0, line.length)];
if (firstMatch.range.location != NSNotFound) {
NSRange keyNameRange = [firstMatch rangeAtIndex:1];
NSRange valueRange = [firstMatch rangeAtIndex:2];
if (keyNameRange.location != NSNotFound && valueRange.location != NSNotFound) {
keyName = [line substringWithRange:keyNameRange];
value = [line substringWithRange:valueRange];
}else{
NSLog(@"Could not determine key/value from line: %@", line);
}
}else{
NSLog(@"Could not determine key/value from line: %@", line);
}
if ([keyName isEqualToString:@"type"] && [value isEqualToString:@"video"]) {
foundVideo = YES;
NSLog(@"Found video track");
}
if (foundVideo && [keyName isEqualToString:@"height"] ) {
NSLog(@"Found width %@", value);
width = [formatter numberFromString:value];
break;
}
}
NSLog(@"mp4track task ended with status %d", [mp4trackTask terminationStatus]);
if([width intValue] >= 720){
NSLog(@"Setting hd flag to 1");
anItem.hdVideo = @1;
}else{
NSLog(@"Setting hd flag to 0");
anItem.hdVideo = @0;
}
return YES;
}
- (MediaItem *)mediaItemFromFile:(NSString *)path error:(NSError **) outError{
NSMutableDictionary *errorDict = [NSMutableDictionary dictionary];
MediaItem *newMediaItem;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = NO;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir] || ![fileManager isReadableFileAtPath:path] || isDir){
if (outError != NULL) {
NSString *errorMsg = [NSString stringWithFormat:@"%@ does not exist or is not readable", path];
errorDict[NSLocalizedDescriptionKey] = errorMsg;
*outError = [[NSError alloc] initWithDomain:@"QMErrors" code:100 userInfo:errorDict];
}
return NO;
}
NSString *extensionList = @"mp4,m4v";
NSArray *extensions = [extensionList componentsSeparatedByString:@","];
NSString *fileExtension = [path pathExtension];
BOOL validExtension = NO;
if (fileExtension != nil && ![fileExtension isEqualToString:@""]){
for(NSString *ext in extensions){
if ([ext isEqualToString:fileExtension]) {
validExtension = YES;
break;
}
}
}
if (validExtension == NO){
if (outError != NULL) {
NSString *errorMsg = [NSString stringWithFormat:@"%@ does not have an allowed extension", path];
errorDict[NSLocalizedDescriptionKey] = errorMsg;
*outError = [[NSError alloc] initWithDomain:@"QMErrors" code:101 userInfo:errorDict];
}
return NO;
}
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *mediaEntity = [NSEntityDescription entityForName:@"MediaItem" inManagedObjectContext:moc];
if(mediaEntity){
newMediaItem = (MediaItem *)[[NSManagedObject alloc] initWithEntity:mediaEntity insertIntoManagedObjectContext:moc];
newMediaItem.input = path;
newMediaItem.output = path;
[self processFileName:newMediaItem error:&error];
}
NSTask *apTask = [[NSTask alloc] init];
NSPipe *apStdoutPipe = [NSPipe pipe];
NSFileHandle *apStdoutHandle = [apStdoutPipe fileHandleForReading];
[apTask setStandardOutput:apStdoutPipe];
// set arguments
NSMutableArray *taskArgs = [NSMutableArray array];
[taskArgs addObject:path];
[taskArgs addObject:@"-t"];
NSLog(@"Starting task with arguments: %@", [taskArgs componentsJoinedByString:@" "]);
[apTask setArguments:taskArgs];
// launch
[apTask setLaunchPath:[appResourceDir stringByAppendingPathComponent:@"AtomicParsley"]];
[apTask launch];
NSData *outputData = nil;
while ([apTask isRunning]) {
sleep(1);
}
outputData = [apStdoutHandle readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData:outputData encoding:NSASCIIStringEncoding];
NSArray *lines = [output componentsSeparatedByString:@"\n"];
NSLog(@"Found %ld lines", (unsigned long)[lines count]);
NSString *atomName = nil;
NSString *value = nil;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSString* regexString = @"Atom\\s*\"([^\"]+)\"\\s*contains:\\s*(.+)";
NSRegularExpressionOptions options = NSRegularExpressionCaseInsensitive;
NSRegularExpression* atomRegex = [NSRegularExpression regularExpressionWithPattern:regexString options:options error:&error];
if (error) {
NSLog(@"Error setting up regex: %@", error.localizedDescription);
}
for(NSString *line in lines){
NSLog(@"Looking at line %@", line);
atomName = @"";
value = @"";
NSTextCheckingResult *firstMatch = [atomRegex firstMatchInString:line options:options range:NSMakeRange(0, line.length)];
if (firstMatch.range.location != NSNotFound) {
NSRange atomRange = [firstMatch rangeAtIndex:1];
NSRange valueRange = [firstMatch rangeAtIndex:2];
if (atomRange.location != NSNotFound && valueRange.location != NSNotFound) {
atomName = [line substringWithRange:atomRange];
value = [line substringWithRange:valueRange];
}else{
NSLog(@"Could not determine atom/value from line: %@", line);
}
}else{
NSLog(@"Could not determine atom/value from line: %@", line);
}
if ([atomName isEqualToString:@"stik"]) {
if ([value isEqualToString:@"TV Show"]) {
newMediaItem.type = @ItemTypeTV;
}else{
newMediaItem.type = @ItemTypeMovie;
}
NSLog(@"Found stik atom");
}else if ([atomName isEqualToString:@"tvsh"]) {
newMediaItem.showName = value;
NSLog(@"Found tvsh atom");
}else if ([atomName isEqualToString:@"tvsn"]) {
newMediaItem.season = [formatter numberFromString:value];
NSLog(@"Found tvsn atom");
}else if ([atomName isEqualToString:@"tves"]) {
newMediaItem.episode = [formatter numberFromString:value];
NSLog(@"Found tves atom");
}
}
return newMediaItem;
}
- (void)stopEncode{
if ([self isEncodeRunning]) {
runQueue = FALSE;
[encodingTask terminate];
}
}
- (QueueItem *)encodingItem{
return encodingItem;
}
#pragma mark ===== Queue Management ======
- (QueueItem *) addFileToQueue:(NSString *)path error:(NSError **) outError {
NSMutableDictionary *errorDict = [NSMutableDictionary dictionary];
QueueItem *newQueueItem;
MediaItem *newMediaItem;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = NO;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir] || ![fileManager isReadableFileAtPath:path] || isDir){
if(outError != NULL){
NSString *errorMsg = [NSString stringWithFormat:@"%@ does not exist or is not readable", path];
errorDict[NSLocalizedDescriptionKey] = errorMsg;
*outError = [[NSError alloc] initWithDomain:@"QMErrors" code:100 userInfo:errorDict];
}
return NO;
}
NSString *extensionList = [[NSUserDefaults standardUserDefaults] objectForKey:@"allowedExtensions"];
NSArray *extensions = [extensionList componentsSeparatedByString:@","];
NSString *fileExtension = [path pathExtension];
BOOL validExtension = NO;
if (fileExtension != nil && ![fileExtension isEqualToString:@""]){
for(NSString *ext in extensions){
if ([ext isEqualToString:fileExtension]) {