R/list_caption_tracks.R

Defines functions list_caption_tracks

Documented in list_caption_tracks

#' List Captions of a Video
#'
#' @param part  Caption resource requested. Required. Comma separated
#' list of one or more of the
#' following: \code{id, snippet}. e.g., "id, snippet", "id" Default:
#' \code{snippet}.
#' @param video_id ID of the video whose captions are requested. Required.
#' No default.
#' @param lang  Language of the caption; required; default is English ("en")
#' @param id    comma-separated list of IDs that identify the caption
#' resources that should be retrieved; optional; string
#' @param simplify Boolean. Default is TRUE. When TRUE, and part is
#' \code{snippet}, a data.frame is returned
#' @param \dots Additional arguments passed to \code{\link{tuber_GET}}.
#'
#' @return list of caption tracks. When \code{simplify} is \code{TRUE}, a
#' \code{data.frame} is returned with
#' following columns: \code{videoId, lastUpdated, trackKind, language, name,
#' audioTrackType, isCC,
#' isLarge, isEasyReader, isDraft, isAutoSynced, status, id} (caption id)
#'
#' @export
#'
#' @references \url{https://developers.google.com/youtube/v3/docs/captions/list}
#'
#' @examples
#' \dontrun{
#'
#' # Set API token via yt_oauth() first
#'
#' list_caption_tracks(video_id = "yJXTXN4xrI8")
#' }

list_caption_tracks <- function(part = "snippet", video_id = NULL, lang = "en",
                                 id = NULL, simplify = TRUE, ...) {

  # Modern validation using checkmate
  assert_character(video_id, len = 1, min.chars = 1, .var.name = "video_id")
  assert_character(part, len = 1, min.chars = 1, .var.name = "part")
  assert_character(lang, len = 1, min.chars = 1, .var.name = "lang")
  assert_logical(simplify, len = 1, .var.name = "simplify")

  if (!is.null(id)) {
    assert_character(id, min.chars = 1, .var.name = "id")
  }

  querylist <- list(part = part, videoId = video_id, id = id)
  raw_res   <- tuber_GET("captions", query = querylist, ...)

  if (length(raw_res$items) == 0) {
      warn("No caption tracks available. Likely cause: Incorrect video ID",
           video_id = video_id,
           class = "tuber_no_captions")
      return(list())
    }

    if (simplify == TRUE && part == "snippet") {
      res_df <- bind_rows(lapply(raw_res$items, function(x) {
        as.data.frame(t(unlist(x$snippet)), stringsAsFactors = FALSE)
      }))
      res_df$id <- sapply(raw_res$items, function(x) unlist(x$id))
      return(res_df)
    }
  raw_res
}

Try the tuber package in your browser

Any scripts or data that you put into this service are public.

tuber documentation built on March 25, 2026, 9:08 a.m.