node.js - 使用 node.js 直接从服务器使用 youtube/google API 上传视频?

标签 node.js youtube google-api youtube-api google-api-nodejs-client

我正在尝试从服务器上传视频,而无需客户端用户进行任何手动身份验证。我尝试了以下视频上传代码片段,但它在浏览器中对用户进行了身份验证并要求接受该应用。

var ResumableUpload = require('node-youtube-resumable-upload');
var googleauth = require('google-auth-cli');
var google = require('googleapis');

var getTokens = function(callback) {
  googleauth({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/youtube.upload' //can do just 'youtube', but 'youtube.upload' is more restrictive
  },
  {     client_id: CLIENT_ID, //replace with your client_id and _secret
      client_secret: CLIENT_SECRET,
      port: 3000
  },
  function(err, authClient, tokens) {
    console.log(tokens);
    callback(tokens);
  });
};

getTokens(function(result) {
  tokens = result;
  upload();
});



var upload = function() {
      var metadata = {snippet: { title: 'title', description: 'Uploaded with ResumableUpload' },
          status: { privacyStatus: 'public' }};
      var resumableUpload = new ResumableUpload(); //create new ResumableUpload
      resumableUpload.tokens = tokens;
      resumableUpload.filepath = 'youtube/test4.mp4';
      resumableUpload.metadata = metadata;
      resumableUpload.monitor = true;
    resumableUpload.eventEmitter.on('progress', function(progress) {
        console.log(progress);
    });
      resumableUpload.initUpload(function(result) {
        console.log(result);
        return;
      });
    }

但对于我的应用程序,它应该直接将视频从服务器上传到 youtube。为此,我需要访问 token 和刷新 token ,我尝试了很多直接获取访问 token ,但我无法获取它。

关于如何将视频直接从服务器上传到 channel 帐户的任何帮助或想法。我在谷歌中搜索了很多 Node 模块来执行此操作,但我无法找到它。

我一直在用这种方式上传视频

  1. 使用客户端库获取基于网络生成的 token 。
  2. 为我的申请获得用户的 YouTube 上传许可 & access_type=离线。
  3. 离线访问类型提供刷新 token 作为响应。这个 token 将有助于继续从后端服务器 token 上传时 到期。
  4. 获得许可后。它将重定向到带有代码的 URL。
  5. 使用给定的代码生成access_token
  6. 保存此 token 以备将来使用。
  7. 使用相同的 token 将视频从您的服务器推送到 youtube 服务器
  8. token 过期时刷新 token 。

但有没有办法在没有获得用户对我的应用程序的 YouTube 上传许可的情况下实现这种方法。

最佳答案

您可以使用带有“服务帐户”的谷歌 API (JWT) 进行服务器端身份验证。但未经用户许可,无法直接从您的服务器上传到 youtube 服务器。谷歌上传视频需要OAuth2.0认证。它会给你错误unAuthorized(401)- youtubeSignupRequired 使用 JWT 身份验证的“服务帐户”。 youtubeSignupRequired

由于上述限制。您使用以下方法来处理这个问题是-

  1. 使用客户端库获取基于网络生成的 token 。
  2. 为您的应用程序和 access_type=offline 获得用户的 YouTube 上传许可。
  3. 离线访问类型为您提供刷新 token 作为响应。此 token 将帮助您在其过期时继续从后端服务器 token 上传。
  4. 获得许可后。它将重定向到带有代码的 URL。
  5. 使用给定的代码生成access_token
  6. 保存此 token 以备将来使用。
  7. 使用相同的 token 将视频从您的服务器推送到 youtube 服务器
  8. token 过期时刷新 token 。并再次执行步骤 3 - 5。
  9. 目前这是将视频上传到 youtube 的唯一方式。
  10. 将代码添加到 git 存储库 nodejs-upload-youtube-video-using-google-api

为什么不可能?检查以下引用链接和代码:

  1. 来自 google API 文档:如果您尝试使用 OAuth 2.0 服务帐户流程,这个错误很常见。 YouTube 不支持服务帐户,如果您尝试使用服务帐户进行身份验证,则会收到此错误。您可以使用链接查看所有错误代码及其详细信息:YouTube Data API - Errors
  2. 来自 gadata 问题: Youtube v3 Google Service Account Access
  3. 来自谷歌博客: List of Google API supported using Service Account
  4. 检查以下代码以从服务器端获取 access_token
  5. 您可以使用以下步骤和代码自行检查:

    • 转到 Google Developer Console
    • 创建项目
    • 要获取 Google+ API 访问权限,请转到:APIs & Auth->APIs ->enable YouTube Data API v3
    • 要启用服务帐户,请转到:API 和 Auth->Credentials->Create new Client ID->Click on Service Account->Create Client Id
    • 将 secret 文件保存在您的系统上并确保其安全。
    • 使用以下命令和您下载的文件创建 key :

openssl pkcs12 -in/home/rajesh/Downloads/Yourkeyfile.p12 -out youtube.pem -nodes

- Enter password: ***notasecret***

6.您可以从服务器端授权和访问 api,如下所示:

    var google = require('googleapis');
    var authClient = new google.auth.JWT(
            'Service account client email address', #You will get "Email address" in developer console for Service Account:
            'youtube.pem', #path to pem file which we create using step 6
            null,
            ['https://www.googleapis.com/auth/youtube.upload'],
            null
    );
    authClient.authorize(function(err, tokens) {
       if (err) {
               console.log(err);
               return;
       }
       console.log(tokens);
    });
  1. 使用服务帐户获取 youtube 视频列表(工作):

         var google = require('googleapis');
         var youtube = google.youtube('v3');
         var authClient = new google.auth.JWT(
              'Service account client email address', #You will get "Email address" in developer console for Service Account:
              'youtube.pem',
              null,
           ['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
           null
         );
        authClient.authorize(function(err, tokens) {
            if (err) {
               console.log(err);
               return;
        }
        youtube.videos.list({auth:authClient,part:'snippet',chart:'mostPopular'}, function(err, resp) {
           console.log(resp);
           console.log(err);
         });
        });
    
  2. 使用服务帐户和 googleapis 模块插入 youtube 视频:

         var google = require('googleapis');
         var youtube = google.youtube('v3');
         var authClient = new google.auth.JWT(
              'Service account client email address', #You will get "Email address" in developer console for Service Account:
              'youtube.pem',
              null,
           ['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
           null
         );
        authClient.authorize(function(err, tokens) {
            if (err) {
               console.log(err);
               return;
        }
          youtube.videos.insert({auth:authClient,part:'snippet,status,contentDetails'},function(err,resp)
           console.log(resp);
           console.log(err);
         });
        });
    

插入/上传 API 返回以下错误:

{ errors: 
   [ { domain: 'youtube.header',
       reason: 'youtubeSignupRequired',
       message: 'Unauthorized',
       locationType: 'header',
       location: 'Authorization' } ],
  code: 401,
  message: 'Unauthorized' }
  1. 使用服务帐户和 ResumableUpload 模块插入 youtube 视频:

         var google = require('googleapis');
         var ResumableUpload = require('node-youtube-resumable-upload');
         var authClient = new google.auth.JWT(
              'Service account client email address', #You will get "Email address" in developer console for Service Account:
              'youtube.pem',
              null,
           ['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
           null
         );
        authClient.authorize(function(err, tokens) {
            if (err) {
               console.log(err);
               return;
        }
          var metadata = {snippet: { title: 'title', description: 'Uploaded with ResumableUpload' },status: { privacyStatus: 'private' }};
          var resumableUpload = new ResumableUpload(); //create new ResumableUpload
          resumableUpload.tokens = tokens;
          resumableUpload.filepath = 'youtube.3gp';
          resumableUpload.metadata = metadata;
          resumableUpload.monitor = true;
          resumableUpload.eventEmitter.on('progress', function(progress) {
               console.log(progress);
          });
          resumableUpload.initUpload(function(result) {
               console.log(result);
               return;
          });
    
        });
    

插入/上传 API 返回以下错误:

   { 'www-authenticate': 'Bearer realm="https://accounts.google.com/AuthSubRequest", error=invalid_token',
  'content-type': 'application/json; charset=UTF-8',
  'content-length': '255',
  date: 'Tue, 16 Sep 2014 10:21:53 GMT',
  server: 'UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")',
  'alternate-protocol': '443:quic,p=0.002' }
  1. 附上“如何获取谷歌 key ?”的屏幕截图 Create Client Id Download Application key & Password Client Email id used to call using backend

结论:未经用户许可上传视频是不可能的。

关于node.js - 使用 node.js 直接从服务器使用 youtube/google API 上传视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25803937/

相关文章:

javascript - 如何使用 excel.js 库编辑 Multer 发布的文件?

node.js - 如何在express js中授予用户特定的文件访问权限

javascript - 既然我们有 ES6 promise ,还有理由使用 Q 或 BlueBird 之类的 promise 库吗?

java - 未能创建 google+ 客户端对象来检索 java 中的 Activity

google-api - 谷歌时间线可视化中的垂直引用线

javascript - 每个任务完成后,如何一遍又一遍地运行异步函数

ios - iOS中YouTube和LinkedIn URL方案的使用

iphone - Youtube iPhone问题

android - 在 Android 中检测 YouTube 视频何时结束

node.js - Vue 项目和 googleapis - 不会构建 - child_process 错误