jjzjj

javascript - 将视频添加到 YouTube 上用户的 "Watch Later"播放列表

coder 2023-06-15 原文

目标是使用 YouTube API 创建一个稍后观看 按钮。当用户单击该按钮时,视频将保存到用户的“稍后观看”播放列表中。类似于在您自己的网站上实现 Facebook 点赞按钮时的工作方式。

到目前为止,我们在 API 文档中有两个官方条目:

我们有很多 PHP code samples在 API 文档上。

这如何使用 PHP 或/和 javascript 实现?

最佳答案

稍后观看播放列表是 ID 为 WL 的播放列表。您可以像添加其他 Youtube 播放列表一样将视频添加到此播放列表。

您首先需要转到您的 Google developer console :

  • 为您的项目启用 Youtube 数据 API
  • 生成一个 Oauth 客户端 ID

然后您可以使用下面的代码进行身份验证,使用 https://www.googleapis.com/auth/youtube 范围检索访问 token ,然后将视频添加到稍后观看的播放列表中.

对于以下 Javascript 和 PHP 示例,按下按钮时,如果用户尚未通过身份验证,它将登录并将视频添加到经过身份验证的用户的稍后观看播放列表中。


Javascript

这基于 Google 提供的 api 示例 here .

Heresource code 的现场演示(如下)

Here是一个 fiddle 。替换您的客户端 ID 并在开发人员控制台中添加为授权的 JavaScript 来源:https://fiddle.jshell.net

index.html :

<!doctype html>
<html>

<head>
    <title>Add to Watch Later playlist</title>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <style>
    .btn-tech {
        color: #2c3e50;
        border: solid 2px #2c3e50;
        background: transparent;
        transition: all 0.3s ease-in-out;
        margin: 20px;
        border-radius: 20% 20% 20% 20%;
    }

    .btn-tech:hover,
    .btn-tech:active,
    .btn-tech.active {
        color: #FFFFFF;
        background: #2c3e50;
        cursor: pointer;
    }
    </style>
</head>

<body>
    <div id="watch_later">
        <div id="buttons">
            <label>Enter Video ID you want to add to Watch Later playlist :
                <input id="video-id" value='T4ZE2KtoFzs' type="text" />
            </label>
        </div>
        <div class="like">
            <a id="fb-link">
                <span class="btn-tech fa-stack fa-3x">
                  <i class="fa fa-thumbs-up fa-stack-1x"></i>
                </span>
            </a>
        </div>
        <div id="playlist-container">
            <span id="status"></span>
        </div>
        <p>
            <a href="https://www.youtube.com/playlist?list=WL">check your watch later playlist</a>
        </p>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script>
    var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
    var OAUTH2_SCOPES = [
        'https://www.googleapis.com/auth/youtube'
    ];
    var init = false;
    googleApiClientReady = function() {
        gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
        });
    }

    function checkAuth() {
        gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
        }, handleAuthResult);
    }
    // Handle the result of a gapi.auth.authorize() call.
    function handleAuthResult(authResult) {

        $('.like').off('click');
        $('.like').click(function(e) {
            if (authResult && !authResult.error) {
                addVideoToPlaylist();
            } else {
                init = true;
                gapi.auth.authorize({
                    client_id: OAUTH2_CLIENT_ID,
                    scope: OAUTH2_SCOPES,
                    immediate: false
                }, handleAuthResult);
            }
            return false;
        });

        if (authResult && !authResult.error) {
            // Authorization was successful. Hide authorization prompts and show
            // content that should be visible after authorization succeeds.
            $('.pre-auth').hide();
            $('.post-auth').show();
            loadAPIClientInterfaces();

            $('#add_to_wl').click(function(e) {
                addVideoToPlaylist();
            });
        }
    }

    function loadAPIClientInterfaces() {
        gapi.client.load('youtube', 'v3', function() {
            if (init) {
                init = false;
                addVideoToPlaylist();
            }
        });
    }
    // Add a video ID specified in the form to the playlist.
    function addVideoToPlaylist() {
        addToPlaylist($('#video-id').val());
    }
    // Add a video to a playlist. The "startPos" and "endPos" values let you
    // start and stop the video at specific times when the video is played as
    // part of the playlist. However, these values are not set in this example.
    function addToPlaylist(id, startPos, endPos) {
        var details = {
            videoId: id,
            kind: 'youtube#video'
        }
        if (startPos != undefined) {
            details['startAt'] = startPos;
        }
        if (endPos != undefined) {
            details['endAt'] = endPos;
        }
        var request = gapi.client.youtube.playlistItems.insert({
            part: 'snippet',
            resource: {
                snippet: {
                    playlistId: "WL",
                    resourceId: details
                }
            }
        });
        request.execute(function(response) {
            console.log(response);
            if (!response.code) {
                $('#status').html('<pre>Succesfully added the video : ' + JSON.stringify(response.result) + '</pre>');
            } else if (response.code == 409) {
                $('#status').html('<p>Conflict : this video is already on your Watch Later playlist</p>');
            } else if (response.code == 404) {
                $('#status').html('<p>Not Found : this video hasnt been found</p>');
            } else {
                $('#status').html('<p>Error : code ' + response.code + '</p>');
            }
        });
    }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>

</html>

OAUTH2_CLIENT_ID 替换为您自己的客户端 ID

在 API 响应中,我检查了以下状态代码:

  • 409 : 视频已经在播放列表中
  • 404 : 找不到视频

PHP

基于 google-api php sample :

  • 安装 Composer :参见instructions
  • 安装 google-api 客户端:

    composer require google/apiclient:~2.0
    

php脚本watchlater.php :

<?php
/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$response = "";

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'YOUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'YOUR_CLIENT_SECRET';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');

$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);

$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }
  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.

if ($client->getAccessToken()) {
  try {

    $videoId = "";

    if (isset($_GET['video'])){
    $videoId = $_GET['video'];
    }
    else if(isset($_SESSION['video'])){
      $videoId = $_SESSION['video'];
    }

    if(isset($videoId) && !isset($_GET['state'])) {

      file_put_contents('php://stderr', print_r("adding video to watch later playlist " . $videoId . "\n", TRUE));

      $playlistId = "WL";
      // 5. Add a video to the playlist. First, define the resource being added
      // to the playlist by setting its video ID and kind.
      $resourceId = new Google_Service_YouTube_ResourceId();
      $resourceId->setVideoId($videoId);
      $resourceId->setKind('youtube#video');

      // Then define a snippet for the playlist item. Set the playlist item's
      // title if you want to display a different value than the title of the
      // video being added. Add the resource ID and the playlist ID retrieved
      // in step 4 to the snippet as well.
      $playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
      $playlistItemSnippet->setTitle('First video in the test playlist');
      $playlistItemSnippet->setPlaylistId($playlistId);
      $playlistItemSnippet->setResourceId($resourceId);
      // Finally, create a playlistItem resource and add the snippet to the
      // resource, then call the playlistItems.insert method to add the playlist
      // item.
      $playlistItem = new Google_Service_YouTube_PlaylistItem();
      $playlistItem->setSnippet($playlistItemSnippet);

      $playlistItemResponse = $youtube->playlistItems->insert(
          'snippet,contentDetails', $playlistItem, array());

      $response = json_encode($playlistItem);

      $_SESSION['video'] = "";
  }
  else{
    file_put_contents('php://stderr', print_r("no video was specified", TRUE));
  }

  } catch (Google_Service_Exception $e) {
    $response = htmlspecialchars($e->getMessage());
  } catch (Google_Exception $e) {
    $response = htmlspecialchars($e->getMessage());
  }
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} else {

  if(isset($_GET['video'])){

    $_SESSION["video"] = $_GET['video'];

    // If the user hasn't authorized the app, initiate the OAuth flow
    $state = mt_rand();
    $client->setState($state);
    $_SESSION['state'] = $state;
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
  }
}
?>

<!doctype html>
<html>
<head>
 <title>Add to Watch Later playlist</title>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <style>
    .btn-tech {
        color: #2c3e50;
        border: solid 2px #2c3e50;
        background: transparent;
        transition: all 0.3s ease-in-out;
        margin: 20px;
        border-radius: 20% 20% 20% 20%;
    }

    .btn-tech:hover,
    .btn-tech:active,
    .btn-tech.active {
        color: #FFFFFF;
        background: #2c3e50;
        cursor: pointer;
    }
    </style>
</head>
<body>
   <div id="watch_later">
        <form id="form" action="watchlater.php"">

          <label>Enter Video ID you want to add to Watch Later playlist :
                <input id="video-id" name="video" value='T4ZE2KtoFzs' type="text" />
          </label>

          <div>
              <span class="btn-tech fa-stack fa-3x" onclick="javascript:document.getElementById('form').submit();">
                <i class="fa fa-thumbs-up fa-stack-1x"></i>
              </span>
          </div>
        </form>
        <div id="playlist-container">
          <?php echo $response ?>
        </div>
        <p>
            <a href="https://www.youtube.com/playlist?list=WL">check your watch later playlist</a>
        </p>
    </div>
</body>
</html>

$OAUTH2_CLIENT_ID$OAUTH2_CLIENT_SECRET 替换为它们各自的值。此外,您必须在谷歌控制台中设置一个 redirect_uri,此处为 http://localhost/watchlater.php

在 PHP 版本中,您可以看到我将视频 ID 存储在 $_SESSION["video"] 中,以便在 google 身份验证重定向到 watchlater.php<>


这是这个项目的谷歌控制台 Oauth 客户端 ID 的屏幕(对上面的 Javascript 和 PHP 版本有效):

注意:

  • 对于 Javascript 版本:您需要 CLIENT_ID 并设置 Javascript Origin
  • 对于 PHP 版本:您需要 CLIENT_IDCLIENT_SECRET、设置 Javascript Origin 和设置 Redirect URI

测试注意事项,我注意到如果您想再次重新添加视频,手动删除视频可能需要一些时间

关于javascript - 将视频添加到 YouTube 上用户的 "Watch Later"播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513339/

有关javascript - 将视频添加到 YouTube 上用户的 "Watch Later"播放列表的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐