-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploadProductToYoutubeCommand.php
1973 lines (1533 loc) · 93.4 KB
/
UploadProductToYoutubeCommand.php
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
<?php
namespace Arclight\ImportBundle\Command\Social;
use Arclight\ImportBundle\Utils\ApiRequestBuilder;
use Arclight\ImportBundle\Utils\ArclightShareQueryHelper;
use Arclight\ImportBundle\Utils\YouTubeRequestBuilder;
use Arclight\ImportBundle\Utils\YouTubeServiceBuilder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Arclight\MMDBBundle\php\misc\Parameters;
use Arclight\MMDBBundle\php\misc\Utils;
use Arclight\MMDBBundle\php\ovp\OvpStorageServiceInterface;
use Symfony\Component\Finder\Finder;
/**
* UploadProductToYouTubeCommand
*
* Usage: bin/console import:uploadProductToYouTube [email protected] "JESUS Film":default CS1 529 21028 --uploadvideos
* bin/console import:uploadProductToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1_jf-0-0 4415 --listallvideos
* bin/console import:uploadProductToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1_jf-0-0 12551 --downloadvideos
* bin/console import:uploadProductToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1_jf-0-0 12551 --uploadvideos --includeparentinchildrentitles --privacystatus=unlisted
* bin/console import:uploadProductToYouTube [email protected] "YouTube API Tests":"default" 1_jf-0-0 12551 --listallvideos
*
* Changes per Howard Crutsinger on 2020-06-02
*
* 1. bin/console import:uploadPlaylistsToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1197 --parentmediacomponentid=1_jf-0-0 --allowemptyplaylists --privacystatus=unlisted
* 2. bin/console import:uploadProductToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1_jf-0-0 1197 --uploadvideos --includeparentinchildrentitles --videolanguageoverride=1197:en --playlistid={{playlistId from previous command}} --privacystatus=unlisted
* 3. bin/console import:uploadPlaylistsToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1197 --parentmediacomponentid=1_jf-0-0
* 4. bin/console import:uploadProductToYouTube [email protected] "Arclight-uploader-3":"Jesus Film Project" 1_jf-0-0 1197 --updatevideostatus --includeparentinchildrentitles --privacystatus=public
* 5. Use Youtube studio to update the privacy status of the playlist to "public" (until we add that to one of the commands)
*
* - English title format for 1_jf-0-0 (feature film):
* Formula: The JESUS Film • Official Full Feature Film • in {{LANG_NAME_EN}} voice
* Example: The JESUS Film • Official Full Feature Film • in Hindi voice
* - English title format (parent/standalone):
* Formula: {{TITLE_EN}} • {{SUBTYPE_EN}} • {{LANG_NAME_NATIVE}} ({{LANG_NAME_EN}})
* Example: My Last Day • Short Film • हिन्दी (Hindi)
* - Localized title format (parent/standalone):
* Formula: {{TITLE_LOCALE}} • {{SUBTYPE_LOCALE}} • {{LANG_NAME_NATIVE}} ({{LANG_NAME_EN}})
* Example: ИИСУС • Художественный фильм • हिन्दी (Hindi)
*
* - English title format for 1_jf-0-0 (segment):
* Formula: The JESUS Film clip • "{{CLIP_NAME_EN}}" • clip {{POSITION}} of {{TOTAL}} clips • in {{LANG_NAME_EN}} voice
* Example: The JESUS Film clip • "The Devil Tempts Jesus" • clip 5 of 61 clips • in Hindi voice
* - English title format (segment/episode):
* Formula: {{PARENT_TITLE_EN}} • "{{TITLE_EN}}" • {{POSITION_OF_COUNT}} • {{LANG_NAME_NATIVE}} ({{LANG_NAME_EN}})
* Example: Magdalena • "Mary Magdalene goes to Rivka's house" • 2/44 • हिन्दी (Hindi)
* - Localized title format (segment/episode):
* Formula: {{PARENT_TITLE_LOCALE}} • {{TITLE_LOCALE}} • {{POSITION_OF_COUNT}} • {{LANG_NAME_NATIVE}} ({{LANG_NAME_EN}})
* Example: Магдалена • "Мария Магдалина идет в дом Ривки" • 2/44 • हिन्दी (Hindi)
*
* - English description format for 1_jf-0-0 parents and children:
* Formula: {{BOILERPLATE_PLAYLIST_EN}} \n\n {{DESCRIPTION_EN}} \n\n {{BOILERPLATE_AFTER_EN}}
* - Localized description format for 1_jf-0-0 parents and children:
* Formula: {{BOILERPLATE_PLAYLIST_EN}} \n\n {{DESCRIPTION_LOCALE}} \n\n {{YOUTUBE_TITLE_EN}} \n\n {{BOILERPLATE_AFTER_EN}}
* - English description format for 1_wjv-0-0 parents and children:
* Formula: {{DESCRIPTION_EN}} \n\n {{BOILERPLATE_AFTER_EN}}
* - Localized description format for 1_wjv-0-0 parents and children:
* Formula: {{DESCRIPTION_LOCALE}} \n\n {{YOUTUBE_TITLE_EN}} \n\n {{BOILERPLATE_AFTER_EN}}
* - English description format (others):
* Formula: {{DESCRIPTION_EN}}
* - Localized description format (others):
* Formula: {{DESCRIPTION_LOCALE}} \n\n {{YOUTUBE_TITLE_EN}}
*/
class UploadProductToYouTubeCommand extends Command
{
/*
* Device access_token retrieval:
* 1. curl -d "client_id=29954156185-f517501cn3mk7diuuoimcqo473a2j01p.apps.googleusercontent.com&\
scope=https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube.readonly" \
https://accounts.google.com/o/oauth2/device/code
* 2. In browser,
* navigate to: https://www.google.com/device
* enter "user_code" returned in step 1
* choose "allow"
* 3. curl -d "client_id=29954156185-f517501cn3mk7diuuoimcqo473a2j01p.apps.googleusercontent.com&client_secret=L_hEWQ3SkWAGqg25AiFPPtD3&\
code=AH-1Ng1JZaNHGnhg2jxvw037WTVd2_b8yp8dO0OQa5ex-n7NXNF2umI8Hb3eugKgXllCLGEQmaCM7VPPAgySIIyhLl6zMB8eEw&grant_type=http://oauth.net/grant_type/device/1.0" \
-H "Content-Type: application/x-www-form-urlencoded" https://www.googleapis.com/oauth2/v4/token
*
* 4. Put access_token, refresh_token etc into DB
*/
const DEFAULT_ARCLIGHT_API_KEY = "5715236f730906.19676983"; //jf.org key
const DEFAULT_USER_ACCOUNT = '[email protected]';
const DEFAULT_CHANNEL_TITLE = 'default';
const BASE_URI = "http://api.arclight.org";
private $langToSubLang = [
12551 => [ 529 ], // Tagalog
6464 => [ 529, 6464 ], // Hindi => English, Hindi
16639 => [ 529, 16639 ], // Indonesian (Yesus) => English, Indonesian (Yesus)
13169 => [ 529 ], // Thai => English
20601 => [ 529, 21754, 21753 ], // Cantonese => English, Chinese Simplified, Chinese Traditional
1927 => [ 529, 16639 ], // Malay => English, Indonesian (Yesus)
5871 => [ 529, 6464 ], // Tamil => English, Hindi
];
private $langToDescLang = [
12551 => [ "en" ], // Tagalog
6464 => [ "en", "hi" ], // Hindi => English, Hindi
16639 => [ "en", "id" ], // Indonesian (Yesus) => English, Indonesian
13169 => [ "en" ], // Thai => English
20601 => [ "en", "zh-Hans", "zh-Hant" ], // Cantonese => English, Chinese Simplified, Chinese Traditional
1927 => [ "en", "id" ], // Malay => English, Indonesian
5871 => [ "en", "hi" ], // Tamil => English, Hindi
21028 => [ "es" ]
];
/**
* @var \Doctrine\DBAL\Connection
*/
private $conn;
/**
* @var \Arclight\MMDBBundle\php\ovp\OvpStorageServiceInterface
*/
private $ovpStorageService;
/**
* @var string
*/
private $projectDir;
/**
* @var ApiRequestBuilder
*/
private $api;
/**
* @var YouTubeServiceBuilder
*/
private $yts;
/**
* @var YouTubeRequestBuilder
*/
private $yt;
/**
* @var ArclightShareQueryHelper
*/
private $shareQuery;
/**
* @var array Key = wess lang ID, value = array containing keys: name, locale
*/
private $youTubeLocales;
/**
* @var array Key = media_asset ID, value = array containing keys: shareUniqueId, mediaLocationShareId, mediaComponentId, languageId
*/
private $videosInChannel = [];
/**
* @var array
*/
private $languagesTitles = [];
// Command options:
private $uploadVideos = false;
private $skipContains = false;
private $uploadLocalizations = false;
private $uploadCaptions = false;
private $uploadPlaylist = false;
private $reconcileVideos = false;
private $downloadVideos = false;
private $deleteCaptions = false;
private $deleteInvalidCaptions = false;
private $reconcileCaptions = false;
private $includeParentInChildrenTitles = false;
private $updateVideoTitles = false;
private $updateVideoStatus = false;
private $updateVideoLocation = false;
private $playlistId = null;
private $privacyStatus = null;
private $publishAt = null;
public function __construct(\Doctrine\DBAL\Connection $mmdbConnection,
\Arclight\MMDBBundle\php\ovp\OvpStorageServiceInterface $ovpStorageService,
string $projectDir)
{
parent::__construct();
$this->conn = $mmdbConnection;
$this->ovpStorageService = $ovpStorageService;
$this->projectDir = $projectDir;
}
protected function configure()
{
$this
->setName('import:uploadProductToYouTube')
->addArgument('useraccountemail', InputArgument::REQUIRED, 'The Google user account email address used for authentication (e.g. [email protected])')
->addArgument('projectname[:channeltitle]', InputArgument::REQUIRED, 'The api project name and brand account channel title to be used for YouTube API access (e.g. "Conversation Starters Project:Conversation Starters")')
->addArgument('mediaComponentId', InputArgument::REQUIRED, 'The media component ID of the product (parent+children) to be uploaded to the given channel')
->addArgument('languageIds', InputArgument::IS_ARRAY, 'Media language IDs to be uploaded to then given channel')
->addOption('uploadvideos', null, InputOption::VALUE_NONE, 'Upload parent+child videos to YouTube (downloading each first, if necessary)')
->addOption('skipcontains', null, InputOption::VALUE_NONE, 'Skip any child videos')
->addOption('includeparentinchildrentitles', null, InputOption::VALUE_NONE, 'Include parent name in child videos, if true')
->addOption('uploadlocalizations', null, InputOption::VALUE_NONE, 'Upload localizations for videos already in channel that match the given media component+children and language IDs')
->addOption('uploadcaptions', null, InputOption::VALUE_NONE, 'Upload captions for videos already in channel that match the given media component+children and language IDs')
->addOption('uploadplaylist', null, InputOption::VALUE_NONE, 'Upload playlist+items to YouTube based on children of the given media component + language ID')
->addOption('updatevideotitles', null, InputOption::VALUE_NONE, 'Update title(s) of the given video(s)')
->addOption('languagestitlesfile', null, InputOption::VALUE_REQUIRED, 'Optional - if provided, provides the list of audio languages to be processed and overrides the Arclight titles for the given locale(s)')
->addOption('updatevideostatus', null, InputOption::VALUE_NONE, 'Update status (privacy etc) of the given video(s)')
->addOption('updatevideolocation', null, InputOption::VALUE_NONE, 'Update location of the given video(s)')
->addOption('downloadvideos', null, InputOption::VALUE_NONE, 'Download videos to local system in preparation for eventual --uploadvideos')
->addOption('listallvideos', null, InputOption::VALUE_NONE, 'List all videos in channel')
->addOption('reconcilevideos', null, InputOption::VALUE_NONE, 'Reconcile videos already uploaded to YouTube but that did not make it into the DB')
->addOption('deletecaptions', null, InputOption::VALUE_NONE, 'Delete captions for videos already in channel that match the given media component+children and language ID')
->addOption('deleteinvalidcaptions', null, InputOption::VALUE_NONE, 'One off')
->addOption('reconcilecaptions', null, InputOption::VALUE_NONE, 'One off')
->addOption('uploadallthumbnails', null, InputOption::VALUE_NONE, 'Upload thumbnails for ALL videos current in channel (ignores media component and language ID arguments)')
->addOption('reportservicecallcounts', null, InputOption::VALUE_NONE, 'Utility option - report on current service call counts. Only utility actions are performed; no uploading.')
->addOption('forcerefreshaccesstoken', null, InputOption::VALUE_NONE, '')
->addOption('dumpyoutubelocales', null, InputOption::VALUE_NONE, 'Utility option - look in the DB for supported YouTube locales. Only utility actions are performed; no uploading.')
->addOption('sampleanalyticsquery', null, InputOption::VALUE_NONE, 'Utility option - run a sample google analytics query')
->addOption('listplaylistitems', null, InputOption::VALUE_OPTIONAL, 'Optional - specific playlist ID of which to list items')
->addOption('listvideos', null, InputOption::VALUE_NONE, 'List video in channel using media component ID and language IDs arguments')
->addOption('listvideosbyyoutubeid', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'List videos in channel by YouTube id')
->addOption('videolanguageoverride', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Optional - specific Youtube video language code to use instead of the bcp47 code associated with the language in Arclight. If providing multiple values, each should both the language ID and the video language code separated by a colon, e.g. 529:en')
->addOption('videocountryoverride', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Optional - country code to use instead of the primaryCountryId for each language in Arclight. If providing multiple values, each should both the language ID and the video language code separated by a colon, e.g. 529:US')
->addOption('parentid', null, InputOption::VALUE_REQUIRED, 'Optional - since titles of segments are built using parent title, this specifies which parent to use')
->addOption('playlistid', null, InputOption::VALUE_REQUIRED, 'Optional - if provided, can be used to add a playlist URL to an uploaded videos long description')
->addOption('privacystatus', null, InputOption::VALUE_REQUIRED, 'Optional - if provided, will be used during uploadvideo / updatingvideostatus', null)
->addOption('publishatutc', null, InputOption::VALUE_REQUIRED, 'Optional - if provided, will be used during uploadvideo / updatingvideostatus, and privacy status will be set to "private". Expects UTC datetime in format: "Y-m-d H:i:s"', null)
->addOption('publishathoursfromnow', null, InputOption::VALUE_REQUIRED, 'Optional - if provided, will be used during uploadvideo / updatingvideostatus, and privacy status will be set to "private"', null)
->addOption('test', 't', InputOption::VALUE_NONE, 'Outputs command arguments')
->setDescription('Uploads product videos to YouTube, and creates playlist');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// $output->writeln("Check and deal with lines 1450 - 1455!!");
// return;
$userAccountEmail = $input->getArgument('useraccountemail');
$projectNameChannelTitle = $input->getArgument('projectname[:channeltitle]');
$parts = explode(':', $projectNameChannelTitle);
$projectName = $parts[0];
$channelTitle = (count($parts) > 1) ? $parts[1] : $projectName;
$mediaComponentId = $input->getArgument('mediaComponentId');
$languageIds = $input->getArgument('languageIds'); // array
$languagesTitlesFile = $input->hasOption('languagestitlesfile') ? $input->getOption('languagestitlesfile') : null;
if (null !== $languagesTitlesFile) {
$this->extractLanguagesTitles($languagesTitlesFile);
$languageIds = array_map('strval', array_keys($this->languagesTitles));
if (Utils::isEmpty($languageIds)) {
throw new \Exception("No [languageid] column values found in file [".$input->getOption('languagestitlesfile')."]");
}
}
$isTest = $input->getOption('test');
$output->writeln("");
$output->writeln("Incoming arguments:");
$output->writeln("\t[ARGUMENT] User account email: ".$userAccountEmail);
$output->writeln("\t[ARGUMENT] Project name: ".$projectName);
$output->writeln("\t[ARGUMENT] Channel title: ".$channelTitle);
$output->writeln("\t[ARGUMENT] Media component ID: ".$mediaComponentId);
$output->writeln("\t[ARGUMENT] Language IDs: ".implode(", ", $languageIds));
$output->writeln("");
$this->parsePrivacyStatus($input, $output);
if (!Utils::isEmpty($this->languagesTitles)) {
$this->outputLanguageTitleOverrides($output);
}
$output->writeln("");
if (true === $isTest) {
return Parameters::COMMAND_SUCCESS;
}
$client = new \GuzzleHttp\Client(['base_uri' => self::BASE_URI]);
$this->api = new ApiRequestBuilder($client, self::DEFAULT_ARCLIGHT_API_KEY, $output);
$this->yts = new YouTubeServiceBuilder($userAccountEmail, $projectName, $channelTitle, $this->conn, $output);
$userId = $this->yts->getUserId();
$channelId = $this->yts->getChannelId();
$this->shareQuery = new ArclightShareQueryHelper(
ArclightShareQueryHelper::YOUTUBE_SHARE_NAME,
$channelId,
$userId,
$this->conn,
$output);
$this->yt = new YouTubeRequestBuilder($this->yts, $this->shareQuery, $this->ovpStorageService, $output);
//var_dump($this->yt->listI18NRegions());
//var_dump($this->yt->listI18NLanguages());
//var_dump($this->yt->listI18NLanguages("ar"));
//exit;
$this->youTubeLocales = $this->shareQuery->lookupLocales();
//TODO: total hack until bcp47 code is fixed in the database:
if (isset($this->youTubeLocales["21028"]) && $this->youTubeLocales["21028"]["locale"] === "es") {
$this->youTubeLocales["21028"]["locale"] = "es-419";
}
$dumpYouTubeLocales = $input->hasOption('dumpyoutubelocales') ? $input->getOption('dumpyoutubelocales') : false;
if (true === $dumpYouTubeLocales) {
$output->writeln(json_encode($this->youTubeLocales, JSON_PRETTY_PRINT));
$output->writeln("Count: ".count($this->youTubeLocales));
return;
}
$reportServiceCallCounts= $input->hasOption('reportservicecallcounts') ? $input->getOption('reportservicecallcounts') : false;
if (true === $reportServiceCallCounts) {
$this->reportServiceCallCounts($output);
return;
}
$this->uploadVideos = $input->hasOption('uploadvideos') ? $input->getOption('uploadvideos') : false;
$this->skipContains = $input->hasOption('skipcontains') ? $input->getOption('skipcontains') : false;
$this->uploadLocalizations = $input->hasOption('uploadlocalizations') ? $input->getOption('uploadlocalizations') : false;
$this->uploadCaptions = $input->hasOption('uploadcaptions') ? $input->getOption('uploadcaptions') : false;
$this->uploadPlaylist = $input->hasOption('uploadplaylist') ? $input->getOption('uploadplaylist') : false;
$this->updateVideoTitles = $input->hasOption('updatevideotitles') ? $input->getOption('updatevideotitles') : false;
$this->updateVideoStatus = $input->hasOption('updatevideostatus') ? $input->getOption('updatevideostatus') : false;
$this->updateVideoLocation = $input->hasOption('updatevideolocation') ? $input->getOption('updatevideolocation') : false;
$this->downloadVideos = $input->hasOption('downloadvideos') ? $input->getOption('downloadvideos') : false;
$this->reconcileVideos = $input->hasOption('reconcilevideos') ? $input->getOption('reconcilevideos') : false;
$this->deleteCaptions = $input->hasOption('deletecaptions') ? $input->getOption('deletecaptions') : false;
$this->deleteInvalidCaptions = $input->hasOption('deleteinvalidcaptions') ? $input->getOption('deleteinvalidcaptions') : false;
$this->reconcileCaptions = $input->hasOption('reconcilecaptions') ? $input->getOption('reconcilecaptions') : false;
$this->includeParentInChildrenTitles = $input->hasOption('includeparentinchildrentitles') ? $input->getOption('includeparentinchildrentitles') : false;
$uploadAllThumbnails = $input->hasOption('uploadallthumbnails') ? $input->getOption('uploadallthumbnails') : false;
$forceRefreshAccessToken = $input->hasOption('forcerefreshaccesstoken') ? $input->getOption('forcerefreshaccesstoken') : false;
$sampleAnalyticsQuery = $input->hasOption('sampleanalyticsquery') ? $input->getOption('sampleanalyticsquery') : false;
$listAllVideos = $input->hasOption('listallvideos') ? $input->getOption('listallvideos') : false;
$listPlaylistItems = $input->getOption('listplaylistitems');
$listVideos = $input->hasOption('listvideos') ? $input->getOption('listvideos') : false;
$listVideosByYoutubeId = array_filter($input->getOption('listvideosbyyoutubeid'));
$vlos = array_filter($input->getOption('videolanguageoverride'));
$vcos = array_filter($input->getOption('videocountryoverride'));
$parentId = $input->hasOption('parentid') ? $input->getOption('parentid') : null;
$this->playlistId = $input->hasOption('playlistid') ? $input->getOption('playlistid') : null;
$videoLanguageOverrides = $this->parseLanguageSpecificOverides($vlos, $languageIds, false);
$videoCountryOverrides = $this->parseLanguageSpecificOverides($vcos, $languageIds, true);
$this->videosInChannel = $this->shareQuery->getVideosOnChannelPageFromDB();
if (true === $listAllVideos) {
$this->yt->searchListAllMyVideos($this->videosInChannel, $output);
exit;
}
if (true === $listVideos) {
$filteredVideosInChannel = $this->filterVideosInChannelByMCLs($mediaComponentId, $languageIds);
$this->yt->listVideosByYoutubeId($filteredVideosInChannel, $output);
exit;
}
if (!Utils::isEmpty($listVideosByYoutubeId)) {
$filteredVideosInChannel = $this->filterVideosInChannelByYoutubeIds($listVideosByYoutubeId);
if (Utils::isEmpty($filteredVideosInChannel)) {
$filteredVideosInChannel = [];
foreach ($listVideosByYoutubeId as $ytid) {
$filteredVideosInChannel[] = [ 'shareUniqueId' => $ytid ];
}
}
$this->yt->listVideosByYoutubeId($filteredVideosInChannel, $output);
exit;
}
if (!Utils::isEmpty($listPlaylistItems)) {
$output->writeln("Items contained within playlist: ".$listPlaylistItems);
$playlistItems = $this->yt->getItemsInPlaylistYT($listPlaylistItems);
if (!Utils::isEmpty($playlistItems)) {
foreach ($playlistItems as $i) {
$output->writeln("ID: ".$i['id'].
", video ID: ".$i['videoId'].
", position: ".$i['position'].
", title: ".$i['title']);
}
}
$output->writeln("Playlist item count: ".count($playlistItems ?? []));
exit;
}
if (true === $sampleAnalyticsQuery) {
//$this->createYouTubeReportJobs();
$this->downloadYouTubeReports(new \DateTime("-5 day", new \DateTimeZone('UTC')));
return;
}
$parentMetadata = $this->api->mediaComponent($parentId ?? $mediaComponentId, 'languageIds');
if (!isset($parentMetadata['mediaComponentId'])) {
$output->writeln("Media component [$mediaComponentId] not found. Exiting...");
return;
}
$containsIds = null;
if (false === $this->skipContains) {
$containsIds = $this->api->mediaComponentContains($parentId ?? $mediaComponentId);
}
if (is_null($containsIds) && true === $this->includeParentInChildrenTitles) {
throw new \Exception("Invalid option 'includeparentinchildrentitles' since media component ID "
."[$mediaComponentId] has no children. Either include a 'parentid' option, or remove "
."'includeparentinchildrentitles'.");
}
// TODO: what if playlist already exists and has some items in it?
foreach($languageIds as $lang) {
if ($lang === '184854' && !array_key_exists($lang, $this->youTubeLocales)) {
$this->youTubeLocales[$lang] = [ 'name' => 'Burmese, Standard', 'locale' => 'my' ];
}
if ($lang === '184855' && !array_key_exists($lang, $this->youTubeLocales)) {
$this->youTubeLocales[$lang] = [ 'name' => 'Burmese, Common', 'locale' => 'my' ];
}
if (!array_key_exists($lang, $this->youTubeLocales)) {
$output->writeln("Language ID [$lang] not supported for YouTube. Processing of media asset skipped...");
continue;
}
$languageMetadata = $this->api->mediaLanguage($lang);
$languageMetadata['youtube_locale'] = $videoLanguageOverrides[$lang] ?? $this->youTubeLocales[$lang]['locale'];
$languageName = $languageMetadata['name'];
if ($lang === '184854') {
$languageMetadata['bcp47'] = 'my';
}
if ($lang === '184855') {
$languageMetadata['bcp47'] = 'my';
}
if ($lang === '584') {
$languageMetadata['bcp47'] = 'pt-BR';
}
if ($lang === '20615') {
$languageMetadata['bcp47'] = 'zh-Hans';
}
if ($lang === '21028') {
$languageMetadata['bcp47'] = 'es-419';
}
$output->writeln("Youtube locale: ".$languageMetadata['youtube_locale']);
$output->writeln("Bcp47: ".$languageMetadata['bcp47']);
$locationCountryId = $videoCountryOverrides[$lang] ?? $languageMetadata['primaryCountryId'] ?? null;
$countryMetadata = null;
if (!Utils::isEmpty($locationCountryId)) {
$countryMetadata = $this->api->mediaCountry($locationCountryId);
}
$languageMetadata['locationLongitude'] = $countryMetadata['longitude'] ?? null;
$languageMetadata['locationLatitude'] = $countryMetadata['latitude'] ?? null;
$languageMetadata['locationDescription'] = $countryMetadata['name'] ?? null;
if (true === $this->downloadVideos || true === $this->uploadVideos || true === $this->uploadLocalizations ||
true === $this->uploadCaptions || true === $this->deleteCaptions || true === $this->deleteInvalidCaptions ||
true === $this->reconcileCaptions || true === $this->updateVideoTitles || true === $this->updateVideoStatus ||
true === $this->updateVideoLocation) {
if (false === $this->shouldSkipProcessVideo($parentMetadata['mediaComponentId'], $lang)) {
if ($mediaComponentId === $parentMetadata['mediaComponentId']) {
if (in_array($lang, $parentMetadata['languageIds'])) {
$this->processMediaAsset($parentMetadata, $languageMetadata, $output);
sleep(30);
} else {
$output->writeln("WARNING: parent video [$mediaComponentId] not available in language [$languageName]. Skipping...");
}
}
}
$containsPosition = 1;
if (!is_null($containsIds)) {
foreach($containsIds as $containsId) {
if (false === $this->shouldSkipProcessVideo($containsId, $lang)) {
if (null === $parentId || $mediaComponentId === $containsId) {
$containsMetadata = $this->api->mediaComponent($containsId, 'languageIds');
$containsMetadata['containsPosition'] = $containsPosition;
$containsMetadata['containsCount'] = count($containsIds);
if (in_array($lang, $containsMetadata['languageIds'])) {
$this->processMediaAsset($containsMetadata, $languageMetadata, $output, $parentMetadata);
sleep(30);
} else {
$output->writeln("WARNING: contained video [$containsId] not available in language [$languageName]. Skipping...");
}
}
}
$containsPosition++;
}
}
}
if (true === $this->uploadPlaylist) {
$this->uploadToPlaylist($parentMetadata, $languageMetadata, $output);
}
}
if (true === $uploadAllThumbnails) {
$this->videosInChannel = $this->shareQuery->getVideosOnChannelPageFromDB();
foreach ($this->videosInChannel as $vid) {
$shareUniqueId = $vid['shareUniqueId'];
$mediaComponentId = $vid['mediaComponentId'];
$output->writeln("Updating thumbnail for YouTube video ID [$shareUniqueId] and media component ID [$mediaComponentId]");
$metadata = $this->api->mediaComponent($mediaComponentId);
$imageUrl = ApiRequestBuilder::chooseThumbnailUrl($metadata);
$this->yt->uploadVideoThumbnail($shareUniqueId, $imageUrl);
}
}
if (true === $this->reconcileVideos) {
$this->videosInChannel = $this->shareQuery->getVideosOnChannelPageFromDB();
$videosInChannelYT = $this->yt->getVideosInChannelYT($channelId, $output);
if (count($this->videosInChannel) != count($videosInChannelYT)) {
$output->writeln("Mismatch number of videos between DB [".count($this->videosInChannel)."] and YT [".count($videosInChannelYT)."]");
$videoIdsInChannel = array_map(function($a) { return $a['shareUniqueId']; }, $this->videosInChannel);
$missing = array_filter($videosInChannelYT, function($a) use ($videoIdsInChannel) { return !in_array($a['id'], $videoIdsInChannel); });
foreach ($missing as $missingVideo) {
$shareUniqueId = $missingVideo['id'];
$title = $missingVideo['title'];
$permalinkUrl = "https://youtu.be/$shareUniqueId";
$mcId = $this->findMediaComponentByTitle($title, $parentMetadata, $containsIds);
if (is_null($mcId)) {
$output->writeln("Unable to reconcile title [$title] to a media component ID");
} else {
$mediaAsset = $this->api->mediaAsset($mcId, $languageIds[0]);
$mediaAsset['mediaAssetId'] = $this->shareQuery->lookupMediaAssetId($mediaAsset['refId']);
$mediaLocationShareId = $this->shareQuery->insertMediaLocationSocial($shareUniqueId, $mediaAsset, $permalinkUrl);
$output->writeln("Adding missing video [".$mediaAsset['refId']."] to DB as mediaLocationShareId [$mediaLocationShareId]");
}
}
} else {
$output->writeln("No videos to reconcile for channel [$channelId] - all YT videos are already in the DB.");
}
}
return Parameters::COMMAND_SUCCESS;
}
protected function parsePrivacyStatus(InputInterface $input, OutputInterface $output)
{
$privacyStatusDefault = 'public';
$publishAtUtc = $input->hasOption('publishatutc') ? $input->getOption('publishatutc') : null;
$publishAtHoursFromNow = $input->hasOption('publishathoursfromnow') ? $input->getOption('publishathoursfromnow') : null;
if (null !== $publishAtUtc) {
$this->publishAt = \DateTime::createFromFormat("Y-m-d H:i:s", $publishAtUtc, new \DateTimeZone('UTC'));
$privacyStatusDefault = 'private';
if (false === $this->publishAt) {
throw new \Exception("Unable to create DateTime from [publishatutc] option value: ".$publishAtUtc);
}
$output->writeln("\t[OPTION] publishatutc: ".$this->publishAt->format(\DateTime::ATOM));
} else if (null !== $publishAtHoursFromNow) {
$this->publishAt = new \DateTime("$publishAtHoursFromNow hour");
$privacyStatusDefault = 'private';
if (false === $this->publishAt) {
throw new \Exception("Unable to create DateTime from [publishatutc] option value: ".$publishAtUtc);
}
$output->writeln("\t[OPTION] publishathoursfromnow ($publishAtHoursFromNow): ".$this->publishAt->format(\DateTime::ATOM));
}
$this->privacyStatus = $input->getOption('privacystatus');
if (null === $this->privacyStatus) {
$this->privacyStatus = $privacyStatusDefault;
}
$output->writeln("\t[OPTION] privacystatus: ".$this->privacyStatus);
if (null !== $this->publishAt && $this->privacyStatus !== 'private') {
throw new \Exception("Setting 'publishAt' date without having privacy status set to 'private' is unsupported by Youtube API");
}
}
protected function outputLanguageTitleOverrides(OutputInterface $output)
{
$maxLengths = [
'language_id' => 7,
'bcp47' => 12
];
$output->writeln("\t[OPTION] Language - title overrides:");
foreach ($this->languagesTitles as $languageId => $languageTitles) {
foreach ($languageTitles as $bcp47 => $languageInfo) {
$lidPad = max($maxLengths['language_id'] - mb_strlen($languageId, 'UTF-8'), 0);
$bcpPad = max($maxLengths['bcp47'] - mb_strlen($bcp47, 'UTF-8'), 0);
$output->write("\t\tLang ID: {$languageId} ".str_repeat(' ', $lidPad));
if (true === $languageInfo['isnativelocale']) {
$output->write("bcp47 (native locale): {$bcp47} ".str_repeat(' ', $bcpPad));
} else {
$output->write("bcp47: {$bcp47} ".str_repeat(' ', $bcpPad));
}
if (!Utils::isEmpty($languageInfo['title'])) {
if (true === $languageInfo['istitleyoutubeready']) {
$output->write(' title (youtube ready): '.$languageInfo['title']);
} else {
$output->write(' title: '.$languageInfo['title']);
}
}
if (!Utils::isEmpty($languageInfo['description'])) {
if (true === $languageInfo['idescriptionyoutubeready']) {
$output->write(' description (youtube ready): '.$languageInfo['description']);
} else {
$output->write(' description: '.$languageInfo['description']);
}
}
$output->writeln("");
}
}
}
/**
* Assumes that the file is pipe-delimited, and contains the following
* column headers:
* languageid
* bcp47
* title
* description
* languagename
* tags (comma delmited)
* isnativelocale (default true: true if bcp47 is considered 'native' locale for audio language)
* istitleyoutubeready (default true: if false, construct youtube title using algorithm + parts)
* isdescriptionyoutubeready (default true)
*
* For each unique languageid, there may be multiple bcp47+title
* combinations, but only one associated bcp47+title should have
* isnativelocale = true.
*/
protected function extractLanguagesTitles(string $videoTitlesFile): void
{
$finder = new Finder();
$finder->files()->in($this->projectDir)->name($videoTitlesFile);
if (0 == count($finder)) {
throw new \Exception("File not having name [$videoTitlesFile] not found.");
}
foreach ($finder as $file) {
echo "\n\tReading contents of data file: ".$file->getRealpath().PHP_EOL;
$sourceHandle = fopen($file->getRealpath(), 'r');
$rowIndex = 0;
$colIndexesToFieldNames = [];
while (($row = fgetcsv($sourceHandle, 0, '|')) !== false) {
if (0 == $rowIndex) {
$colIndexesToFieldNames = $row;
++$rowIndex;
continue;
}
$currentRow = $this->mapColumnIndexesToNames($row, $colIndexesToFieldNames);
$this->languagesTitles[$currentRow['languageid']][$currentRow['bcp47']] = [
'title' => $currentRow['title'],
'description' => $currentRow['description'] ?? "",
'languagename' => $currentRow['languagename'] ?? "",
'languagenameen' => $currentRow['languagenameen'] ?? "",
'tags' => explode(',', $currentRow['tags'] ?? ""),
'isnativelocale' => filter_var($currentRow['isnativelocale'] ?? 1, FILTER_VALIDATE_BOOLEAN),
'istitleyoutubeready' => filter_var($currentRow['istitleyoutubeready'] ?? 1, FILTER_VALIDATE_BOOLEAN),
'isdescriptionyoutubeready' => filter_var($currentRow['isdescriptionyoutubeready'] ?? 1, FILTER_VALIDATE_BOOLEAN),
];
}
}
}
protected function mapColumnIndexesToNames(array $row, array $colIndexesToFieldNames) {
$mappedRow = [];
foreach ($row as $index => $value) {
$fieldName = $colIndexesToFieldNames[$index];
$mappedRow[$fieldName] = $value;
}
return $mappedRow;
}
protected function parseLanguageSpecificOverides(array $incomingOverrides, array $languageIds, bool $allowEmptyCode) {
$parsedOverrides = [];
if (is_array($incomingOverrides)) {
foreach ($incomingOverrides as $ilo) {
$matches = null;
$codeMatch = (true === $allowEmptyCode) ? "([\w\-]+)?" : "([\w\-]+)";
if (preg_match('/(\d+):'.$codeMatch.'/', $ilo, $matches)) {
$parsedOverrides[$matches[1]] = $matches[2] ?? "";
} else if (1 === count($languageIds) && 1 === count($incomingOverrides)) {
$parsedOverrides[$languageIds[0]] = $ilo;
} else {
throw new \Exception("Language override option [$ilo] does not match langid:code format");
}
}
foreach ($parsedOverrides as $langId => $ilo) {
if (!in_array($langId, $languageIds)) {
throw new \Exception("Language override option [$ilo] has language [$langId], which doesn't match any of the 'languageids' argument(s)");
}
}
}
return $parsedOverrides;
}
protected function createYouTubeReportJobs()
{
$youTubeService = $this->yts->getAuthorizedYouTubeQueryService();
$youtubeReporting= new \Google_Service_YouTubeReporting($youTubeService->getClient());
//$reportTypes = $youtubeReporting->reportTypes->listReportTypes();
//var_dump($reportTypes);
//return;
// JESUS Film:
// channel_basic_a2, "User activity" - job id: 23a2954e-a4c9-4609-b700-377760d87887
// channel_combined_a2, "Combined" - job id: b7803d82-b6d0-407b-88b4-30be5e9e1f73
//
// Conversation Starters:
// channel_basic_a2, "User activity" - job id: 0e65a5ed-b032-4bee-98f9-7a0ff6f298e0
// channel_combined_a2, "Combined" - job id: 0564d3b8-1248-4153-a82d-fbb5f05dc11c
//
$reportingJob1 = new \Google_Service_YouTubeReporting_Job();
$reportingJob1->setReportTypeId("channel_basic_a2");
$reportingJob1->setName("User activity");
// Call the YouTube Reporting API's jobs.create method to create a job.
$jobCreateResponse = $youtubeReporting->jobs->create($reportingJob1);
var_dump($jobCreateResponse);
$reportingJob2 = new \Google_Service_YouTubeReporting_Job();
$reportingJob2->setReportTypeId("channel_combined_a2");
$reportingJob2->setName("Combined");
// Call the YouTube Reporting API's jobs.create method to create a job.
$jobCreateResponse = $youtubeReporting->jobs->create($reportingJob2);
var_dump($jobCreateResponse);
}
protected function downloadYouTubeReports(\DateTime $createdAfterDt)
{
$createdAfter = $createdAfterDt->setTime(0, 0)->format("Y-m-d\TH:i:s\Z");
$youTubeService = $this->yts->getAuthorizedYouTubeReportService();
$youtubeReporting= new \Google_Service_YouTubeReporting($youTubeService->getClient());
$reportingJobs = $youtubeReporting->jobs->listJobs();
if (0 == count($reportingJobs)) {
echo "\t No reporting jobs found in list".PHP_EOL;
}
foreach ($reportingJobs as $job) {
$reports = $youtubeReporting->jobs_reports->listJobsReports($job['id'], [ 'createdAfter' => $createdAfter ]);
foreach ($reports as $report) {
$startDt = \DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $report['startTime'], new \DateTimeZone('UTC'));
$endDt = \DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $report['endTime'], new \DateTimeZone('UTC'));
$createDt = \DateTime::createFromFormat("Y-m-d\TH:i:s.u\Z", $report['createTime'], new \DateTimeZone('UTC'));
$reportDownloadUrl = $report['downloadUrl'];
// DOWNLOAD REPORT:
$client = $youtubeReporting->getClient();
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Call YouTube Reporting API's media.download method to download a report.
$request = $youtubeReporting->media->download('', array('alt' => 'media'));
$request = $request->withUri(new \GuzzleHttp\Psr7\Uri($reportDownloadUrl));
$responseBody = '';
try {
$response = $client->execute($request);
$responseBody = $response->getBody();
} catch (Google_Service_Exception $e) {
$responseBody = $e->getTrace()[0]['args'][0]->getResponseBody();
}
$fileName = $job['reportTypeId']."_".$startDt->format('Y-m-d').".txt";
file_put_contents($fileName, $responseBody);
$client->setDefer(false);
echo "\t Retrieved report for filename [$fileName]".PHP_EOL;
}
}
}
protected function reportServiceCallCounts(OutputInterface $output)
{
$overallCallCountOver24Hours = $this->shareQuery->getServiceCallCountSince(1440, null, true);
$overallQuotaCostOver24Hours = $this->shareQuery->getServiceQuotaCostSince(1440, null, true);
$uploadVideoCallCountOver24Hours = $this->shareQuery->getServiceCallCountSince(1440, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoCallCountOver12Hours = $this->shareQuery->getServiceCallCountSince(720, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoCallCountOver6Hours = $this->shareQuery->getServiceCallCountSince(360, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoCallCountOver3Hours = $this->shareQuery->getServiceCallCountSince(180, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoQuotaCostOver24Hours = $this->shareQuery->getServiceQuotaCostSince(1440, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoQuotaCostOver12Hours = $this->shareQuery->getServiceQuotaCostSince(720, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoQuotaCostOver6Hours = $this->shareQuery->getServiceQuotaCostSince(360, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadVideoQuotaCostOver3Hours = $this->shareQuery->getServiceQuotaCostSince(180, YouTubeRequestBuilder::CALL_ID_UPLOAD_VIDEO, true);
$uploadCaptionCallCountOver24Hours = $this->shareQuery->getServiceCallCountSince(1440, YouTubeRequestBuilder::CALL_ID_UPLOAD_CAPTION, true);
$uploadCaptionQuotaCostOver24Hours = $this->shareQuery->getServiceQuotaCostSince(1440, YouTubeRequestBuilder::CALL_ID_UPLOAD_CAPTION, true);
$output->writeln("Since last 24 hours: [".number_format($overallCallCountOver24Hours).
"] service calls, [".number_format($overallQuotaCostOver24Hours).
"] quota cost, [".number_format($uploadVideoCallCountOver24Hours).
"] upload calls, [".number_format($uploadVideoQuotaCostOver24Hours).
"] upload quota cost, [".number_format($uploadCaptionCallCountOver24Hours).
"] caption upload calls, [".number_format($uploadCaptionQuotaCostOver24Hours).
"] caption upload quota cost");
$output->writeln("Since last 12 hours: [".number_format($uploadVideoCallCountOver12Hours).
"] upload calls, [".number_format($uploadVideoQuotaCostOver12Hours)."] upload quota cost");
$output->writeln("Since last 6 hours: [".number_format($uploadVideoCallCountOver6Hours).
"] upload calls, [".number_format($uploadVideoQuotaCostOver6Hours)."] upload quota cost");
$output->writeln("Since last 3 hours: [".number_format($uploadVideoCallCountOver3Hours).
"] upload calls, [".number_format($uploadVideoQuotaCostOver3Hours)."] upload quota cost");
}
protected function filterVideosInChannelByMCLs(string $mediaComponentId, array $languageIds) {
$videosInChannel = array_filter($this->videosInChannel, function($a) use ($mediaComponentId, $languageIds) {
return ($a['mediaComponentId'] == $mediaComponentId && in_array($a['languageId'], $languageIds));
});
return $videosInChannel;
}
protected function filterVideosInChannelByYoutubeIds(array $youtubeIds) {
$videosInChannel = array_filter($this->videosInChannel, function($a) use ($youtubeIds) {
return (in_array($a['shareUniqueId'], $youtubeIds));
});
return $videosInChannel;
}
protected function shouldSkipProcessVideo($mediaComponentId, $languageId)
{
if (false === $this->downloadVideos && true === $this->uploadVideos && false === $this->uploadCaptions &&
false === $this->deleteCaptions && false === $this->deleteInvalidCaptions && false === $this->reconcileCaptions) {
$found = array_filter($this->videosInChannel, function($a) use ($mediaComponentId, $languageId) {
return ($a['mediaComponentId'] == $mediaComponentId && $a['languageId'] == $languageId);
});
return count($found) > 0;
}
return false;
}
protected function findMediaComponentByTitle($title, $parentMetadata, $containsIds)
{
if ($title == $parentMetadata['title']) {
return $parentMetadata['mediaComponentId'];
}
foreach ($containsIds as $containsId) {
$containsMetadata = $this->api->mediaComponent($containsId);
if ($title == $containsMetadata['title']) {
return $containsMetadata['mediaComponentId'];
}
}
return null;
}
protected function processMediaAsset($metadata, $languageMetadata, OutputInterface $output, $parentMetadata = null)
{
if (false === $this->downloadVideos && false === $this->uploadVideos && false === $this->uploadLocalizations &&
false === $this->deleteCaptions && false === $this->deleteInvalidCaptions && false === $this->reconcileCaptions &&
false === $this->uploadCaptions && false === $this->updateVideoTitles && false === $this->updateVideoStatus &&
false === $this->updateVideoLocation) {
return;
}
if ($metadata['contentType'] != 'video') {
return;
}
// $output->writeln("Looking up media asset by [".$metadata['mediaComponentId']."] and [".$languageMetadata['languageId']."]");
$mediaAsset = $this->api->mediaAsset($metadata['mediaComponentId'], $languageMetadata['languageId']);
$mediaAssetDb = $this->shareQuery->lookupMediaAssetDb($mediaAsset['refId']);
$mediaAsset['mediaAssetId'] = $mediaAssetDb['id'];
$mediaAsset['masterAssetUrl'] = $mediaAssetDb['master_asset_url'];
if (empty($mediaAsset['mediaAssetId'])) {
$output->writeln("Unable to lookup media asset ID. Skipping....");
return;
}
$this->processVideo($metadata, $languageMetadata, $mediaAsset, $output, $parentMetadata);
$this->processVideoCaptions($mediaAsset, $parentMetadata, $output);
}
protected function processVideo($metadata, $languageMetadata, $mediaAsset, OutputInterface $output, $parentMetadata = null)
{
if (true === $this->downloadVideos) {
if (!array_key_exists($mediaAsset['mediaAssetId'], $this->videosInChannel)) {
$basename = $mediaAsset['refId'];
if (!Utils::isEmpty($mediaAsset['masterAssetUrl'])) {
$output->writeln("Downloading video [".$metadata['mediaComponentId']."] in language [".$languageMetadata['name']."] from master assset URL");
$this->yt->downloadUrlTmp($mediaAsset['masterAssetUrl'], $basename, true);
} else {
$output->writeln("Downloading video [".$metadata['mediaComponentId']."] in language [".$languageMetadata['name']."] from transcoded streaming URL");
$url = ApiRequestBuilder::chooseAssetUrl($mediaAsset);
$this->yt->downloadUrlTmp($url, $basename, false);
}
}
}
if (true === $this->uploadVideos || true === $this->updateVideoTitles) {
if (true === $this->includeParentInChildrenTitles && is_null($parentMetadata)) {
if ($metadata['subType'] === "episode" || $metadata['subType'] === "segment") {
$parentMcId = $this->findParentMediaComponentId($metadata['mediaComponentId']);
$parentMetadata = $this->api->mediaComponent($parentMcId, null, "en");
}
}
}
if (true === $this->uploadVideos) {
if (!array_key_exists($mediaAsset['mediaAssetId'], $this->videosInChannel)) {
$output->writeln("Uploading video [".$metadata['mediaComponentId']."] in language [".$languageMetadata['name']."]");
$defaultLanguage = 'en';
$title = "";
$description = "";
$tags = [];
$localizations = [];
if (!Utils::isEmpty($this->languagesTitles)) {
if (isset($this->languagesTitles[$languageMetadata['languageId']])) {
// Until we get clearer requirements from Howard on how to build titles
// and descriptions using building blocks such as native/en film title,
// native/en language name, etc., we only use the incoming "title" and/or
// "description" values from the file as-is: