@@ -429,4 +429,90 @@ module Invidious::Routes::API::V1::Videos
429
429
end
430
430
end
431
431
end
432
+
433
+ # Fetches transcripts from YouTube
434
+ #
435
+ # Use the `lang` and `autogen` query parameter to select which transcript to fetch
436
+ # Request without any URL parameters to see all the available transcripts.
437
+ def self.transcripts (env )
438
+ env.response.content_type = " application/json"
439
+
440
+ id = env.params.url[" id" ]
441
+ lang = env.params.query[" lang" ]?
442
+ label = env.params.query[" label" ]?
443
+ auto_generated = env.params.query[" autogen" ]? ? true : false
444
+
445
+ # Return all available transcript options when none is given
446
+ if ! label && ! lang
447
+ begin
448
+ video = get_video(id)
449
+ rescue ex : NotFoundException
450
+ return error_json(404 , ex)
451
+ rescue ex
452
+ return error_json(500 , ex)
453
+ end
454
+
455
+ response = JSON .build do |json |
456
+ # The amount of transcripts available to fetch is the
457
+ # same as the amount of captions available.
458
+ available_transcripts = video.captions
459
+
460
+ json.object do
461
+ json.field " transcripts" do
462
+ json.array do
463
+ available_transcripts.each do |transcript |
464
+ json.object do
465
+ json.field " label" , transcript.name
466
+ json.field " languageCode" , transcript.language_code
467
+ json.field " autoGenerated" , transcript.auto_generated
468
+
469
+ if transcript.auto_generated
470
+ json.field " url" , " /api/v1/transcripts/#{ id } ?lang=#{ URI .encode_www_form(transcript.language_code)} &autogen"
471
+ else
472
+ json.field " url" , " /api/v1/transcripts/#{ id } ?lang=#{ URI .encode_www_form(transcript.language_code)} "
473
+ end
474
+ end
475
+ end
476
+ end
477
+ end
478
+ end
479
+ end
480
+
481
+ return response
482
+ end
483
+
484
+ # If lang is not given then we attempt to fetch
485
+ # the transcript through the given label
486
+ if lang.nil?
487
+ begin
488
+ video = get_video(id)
489
+ rescue ex : NotFoundException
490
+ return error_json(404 , ex)
491
+ rescue ex
492
+ return error_json(500 , ex)
493
+ end
494
+
495
+ target_transcript = video.captions.select(& .name.== label)
496
+ if target_transcript.empty?
497
+ return error_json(404 , NotFoundException .new(" Requested transcript does not exist" ))
498
+ else
499
+ target_transcript = target_transcript[0 ]
500
+ lang, auto_generated = target_transcript.language_code, target_transcript.auto_generated
501
+ end
502
+ end
503
+
504
+ params = Invidious ::Videos ::Transcript .generate_param(id, lang, auto_generated)
505
+
506
+ begin
507
+ transcript = Invidious ::Videos ::Transcript .from_raw(
508
+ YoutubeAPI .get_transcript(params), lang, auto_generated
509
+ )
510
+ rescue ex : NotFoundException
511
+ return error_json(404 , ex)
512
+ rescue ex
513
+ return error_json(500 , ex)
514
+ end
515
+
516
+ return transcript.to_json
517
+ end
432
518
end
0 commit comments