Youtube 不会更新视频的字幕

问题描述 投票:0回答:1

我正在尝试使用以下代码片段在我的频道上插入/更新视频的字幕,

let tokens = {
  access_token: 'ya29...',
  scope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.upload',
  token_type: 'Bearer',
  id_token: 'ey....',
  expiry_date: 1672523820523,
user:{....}
}

async function upsertCaption(token, videoId, caption) {

  oauth2Client.setCredentials(token);

  return youtube.captions
    .list({
      auth: oauth2Client,
      part: ["snippet"],
      videoId: videoId
    })
    .then(response => {
      let track_id = _.get(response.data, "items[0].id", 0);
      console.log(`track id ${track_id}`);

      if (track_id == 0) {
        console.log("inerting new caption");
        return youtube.captions
          .insert({
            auth: oauth2Client,
            part: "snippet",
            sync: false,
            requestBody: {
              snippet: {
                language: "en",
                name: "my captions",
                videoId: videoId,
                isDraft: false
              }
            },
            media: {
              mimeType: "*/*",
              body: caption
            }
          })
          .then(response => {
            console.log(response.data);
            return response;
          });
      } else {
        console.log("updating  caption");
        return youtube.captions
          .update({
            auth: oauth2Client,
            part: "snippet",
            sync: false,
            requestBody: {
              id: track_id,
              snippet: {
                language: "en",
                name: "my captions",
                videoId: videoId,
                isDraft: false
              }
            },
            media: {
              mimeType: "*/*",
              body: caption
            }
          })
          .then(response => {
            console.log(response.data);
            return response;
          });
      }
    });

}

所使用的令牌是在这些范围内请求的

scopes = [
  "profile",
  "https://www.googleapis.com/auth/youtube.upload",
  "https://www.googleapis.com/auth/youtube.force-ssl",
  "https://www.googleapis.com/auth/youtubepartner",
  "https://www.googleapis.com/auth/userinfo.profile"
];

如果插入新的字幕或更新它们,该逻辑有效,但如果更新 youtube 生成的字幕,则该逻辑不起作用

code: 403,
  errors: [
    {
      message: 'The permissions associated with the request are not sufficient to update the caption track. The request might not be properly authorized.',
      domain: 'youtube.caption',
      reason: 'forbidden',
      location: 'id',
      locationType: 'parameter'
    }
  ]

可能是什么问题?

node.js youtube google-oauth youtube-data-api google-api-nodejs-client
1个回答
0
投票

与请求关联的权限不足以更新字幕轨道。该请求可能未得到正确授权。

这个错误的意思正是它所说的。您当前经过身份验证的用户拥有的访问令牌不包含 captions.update 方法所需的权限。此方法需要用户同意以下范围之一

我已经两次要求您发布[示例],因为您选择不发布并且只发布了代码片段。我只需猜测您将访问令牌存储在代码中的某个位置。您授权了您的应用程序,然后更改了代码中的范围。您没有做的是删除旧令牌并再次请求用户授权。我看不到你的代码,所以我不知道你将其存储在哪里。

检查快速入门以获得正确的授权示例

我认为你应该遵循官方的 Node.js 数据 api 快速入门

此快速入门将向您展示如何正确授权您的应用程序。它甚至将用户凭据存储在 TOKEN_PATH 中。

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.