PHP कोड के नमूने

नीचे दिए गए कोड सैंपल, जो PHP के लिए Google API क्लाइंट लाइब्रेरी का इस्तेमाल करते हैं, वे YouTube Content ID API के लिए उपलब्ध हैं.

ध्यान दें: ये सैंपल, YouTubePartner सेवा को इंपोर्ट करते हैं. क्लाइंट लाइब्रेरी के दस्तावेज़ देखें, ताकि आप इन सैंपल को चलाने के लिए ज़रूरी, जनरेट की गई YouTube Content ID API बाइंडिंग डाउनलोड कर सकें.

वीडियो अपलोड करना और उससे कमाई करना (सेवा खाते की अनुमति देना)

ध्यान दें: इस उदाहरण में, सेवा खाते की अनुमति का इस्तेमाल किया गया है.

यह कोड सैंपल, YouTube वीडियो को अपलोड करता है और उस पर कमाई करने की नीति लागू करता है. किसी वीडियो से कमाई करने के लिए, आपको उस वीडियो पर YouTube के राइट्स मैनेजमेंट सिस्टम से, किसी एसेट के साथ दावा करना होगा. यह सैंपल वीडियो अपलोड करता है, नई एसेट बनाता है, एसेट का इस्तेमाल करके वीडियो पर दावा करता है, और वीडियो पर कमाई करने से जुड़ी नीति लागू करता है.

कोड ये चरण चलाता है:

  1. यह कॉन्टेंट के मालिक के उस आईडी को हासिल करता है जिसके लिए अनुरोध करने की अनुमति देने वाले उपयोगकर्ता ने अनुरोध किया था. इसके लिए, यह youtubePartner.contentOwners.list एपीआई तरीके को कॉल करता है. इस तरीके में fetchMine पैरामीटर को true पर सेट किया जाता है.

  2. यह Data API के videos.insert तरीके का इस्तेमाल करके, किसी ऐसे चैनल पर वीडियो जोड़ता है जिसे कॉन्टेंट का मालिक मैनेज करता है. यह एपीआई कॉल, onBehalfOfContentOwner डेलिगेशन पैरामीटर को उस कॉन्टेंट के मालिक के आईडी पर सेट करता है जिसे पिछले चरण में हासिल किया गया था. यह सही चैनल की पहचान करने के लिए, onBehalfOfContentOwnerChannel डेलिगेशन पैरामीटर भी सेट करता है.

    अपलोड किए जाने वाले वीडियो को अपलोड करने के लिए, प्रोग्राम Google_MediaFileUpload क्लास का इस्तेमाल करता है, जिसमें resumable upload पैरामीटर को true पर सेट किया जाता है. अगर अपलोड में रुकावट आती है, तो बाद में की जाने वाली कोशिशें उस पॉइंट से अपलोड करना फिर से शुरू कर सकती हैं जहां पिछली कोशिश सफल नहीं हुई थी. यह सुविधा उन प्रोग्राम के लिए काम की है जिन्हें बड़े वीडियो अपलोड करने की ज़रूरत होती है.

  3. वीडियो कॉन्टेंट अपलोड होने के बाद, कोड को एक एसेट ऑब्जेक्ट बनाना होगा, ताकि कॉन्टेंट के मालिकाना हक वाले कॉन्टेंट की पहचान की जा सके. एसेट, YouTube के राइट मैनेजमेंट सिस्टम में बौद्धिक संपत्ति का एक हिस्सा दिखाती है. एसेट के मालिक, एसेट का इस्तेमाल करके, एसेट के कॉन्टेंट से मिलते-जुलते वीडियो को ट्रैक करने, उनसे कमाई करने या उन्हें ब्लॉक करने के लिए नीतियां सेट कर सकते हैं.

    यह कोड, अपलोड किए गए वीडियो का एसेट बनाने के लिए, youtubePartner.assets.insert एपीआई तरीके का इस्तेमाल करता है. इसके बाद, youtubePartner.ownership.update तरीके का इस्तेमाल करके मालिकाना हक तय करता है.

  4. कोड सैंपल के ज़रिए कमाई करने की एक नीति बनाई जाती है. इस नीति का इस्तेमाल करके वीडियो पर दावा किया जाता है.

  5. यह कोड, youtubePartner.claims.insert को कॉल करके, अपलोड किए गए वीडियो पर हाल ही में बनाई गई एसेट से मिलते-जुलते वीडियो का दावा करता है. यह दावा, वीडियो पर कमाई करने से जुड़ी उस नीति पर लागू होता है जिसके लिए पिछले चरण में बनाया गया था.

  6. आखिर में, कोड सैंपल youtubePartner.videoAdvertisingOptions.update तरीके का इस्तेमाल करता है, ताकि वीडियो के दौरान TrueView इनस्ट्रीम विज्ञापन दिखाए जा सकें.

youtubePartner.contentOwners.list तरीके को छोड़कर, YouTube Content ID API के सभी तरीके onBehalfOfContentOwner डेलिगेशन पैरामीटर का इस्तेमाल करते हैं. इस पैरामीटर में, अपनी वैल्यू को कॉन्टेंट के मालिक के आईडी पर सेट किया जाता है.

<?php

/**
 * This sample uploads, claims and monetizes a video by :
 *
 * 1. Finding the content owner ID via "youtubePartner.contentOwners.listContentOwners" method
 * 2. Uploading the video via "youtube.videos.insert" with utilizing "Google_MediaFileUpload"
 * 3. Creating an asset via "youtubePartner.assets.insert" method
 * 4. Creating ownership on the asset via "youtubePartner.ownership.update" method
 * 5. Claiming the video with the asset and a policy via "youtubePartner.claims.insert"
 * 6. Enabling the TrueView advertising on the video via "youtubePartner.videoAdvertisingOptions.update"
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 service account name and private key file from the
 * Google API Console <https://console.cloud.google.com/>
 * For more information about using OAuth 2.0 Service Accounts to access Google APIs, please see:
 * <https://developers.google.com/accounts/docs/OAuth2ServiceAccount>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_SERVICE_ACCOUNT_NAME = 'REPLACE ME';

// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
$OAUTH2_KEY_FILE = '/super/secret/path/to/key.p12';

$client = new Google_Client();

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

/* Load the key in PKCS 12 format. You need to download this from the
 * Google API Console when the service account was created.
 * Please read https://developers.google.com/youtube/partner/guides/oauth2_for_service_accounts
 * for info on configuration.
 */
$key = file_get_contents($OAUTH2_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
    $OAUTH2_SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/youtubepartner'),
    $key);
$client->setAssertionCredentials($cred);


if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

  try{

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];

    // REPLACE this value with the path to the file you are uploading.
    $videoPath = "/path/to/file.mp4";

    // REPLACE this value with the ID that uniquely identifies the channel that
    // you are uploading to.
    $channelId = "CHANNEL_ID";

    // Create a snippet with title, description, tags and category ID
    // Create an asset resource and set its snippet metadata and type.
    // This example sets the video's title, description, keyword tags, and
    // video category.
    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test description");
    $snippet->setTags(array("tag1", "tag2"));

    // Numeric video category. See
    // https://developers.google.com/youtube/v3/docs/videoCategories/list
    $snippet->setCategoryId("22");

    // Set the video's status to "public". Valid statuses are "public",
    // "private" and "unlisted".
    $status = new Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = "public";

    // Associate the snippet and status objects with a new video resource.
    $video = new Google_Service_YouTube_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a request for the API's videos.insert method to create and upload the video.
    $insertRequest = $youtube->videos->insert("status,snippet", $video,
        array('onBehalfOfContentOwner' => $contentOwnerId,
            'onBehalfOfContentOwnerChannel' => $channelId));

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($videoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }

    fclose($handle);

    // Set defer back to false to be able to make other calls after the file upload.
    $client->setDefer(false);

    $videoId = $status['id'];

    // Create an asset resource and set its metadata and type. Assets support
    // many metadata fields, but this sample only sets a title and description.
    $asset = new Google_Service_YouTubePartner_Asset();
    $metadata = new Google_Service_YouTubePartner_Metadata();
    $metadata->setTitle("Test asset title");
    $metadata->setDescription("Test asset description");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    // Insert the asset resource. Extract its unique asset ID from the API
    // response.
    $assetInsertResponse = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId = $assetInsertResponse['id'];

    // Create a territory owner with owner, ratio, type and territories
    // Set the asset's ownership data. This example identifies the content
    // owner associated with the authenticated user's account as the asset's
    // owner. It indicates that the content owner owns 100% of the asset
    // worldwide.
    $owners = new Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($contentOwnerId);
    $owners->setRatio(100);
    $owners->setType("exclude");
    $owners->setTerritories(array());

    // Create ownership with a territory owner
    $ownership = new Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral(array($owners));

    // Update the asset's ownership with the rights data defined above.
    $ownershipUpdateResponse = $youtubePartner->ownership->update($assetId, $ownership,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Define a monetization policy for the asset.
    $policy = new Google_Service_YouTubePartner_Policy();
    $policyRule = new Google_Service_YouTubePartner_PolicyRule();
    $policyRule->setAction("monetize");
    $policy->setRules(array($policyRule));

    // Create a claim resource. Identify the video being claimed, the asset
    // that represents the claimed content, the type of content being claimed,
    // and the policy that you want to apply to the claimed video.
    $claim = new Google_Service_YouTubePartner_Claim();
    $claim->setAssetId($assetId);
    $claim->setVideoId($videoId);
    $claim->setPolicy($policy);
    $claim->setContentType("audiovisual");

    // Insert the created claim.
    $claimInsertResponse = $youtubePartner->claims->insert($claim,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    # Enable ads for the video. This example enables the TrueView ad format.
    $option = new Google_Service_YouTubePartner_VideoAdvertisingOption();
    $option->setAdFormats(array("trueview_instream"));
    $setAdvertisingResponse = $youtubePartner->videoAdvertisingOptions->update(
        $videoId, $option, array('onBehalfOfContentOwner' => $contentOwnerId));


    $htmlBody .= "<h3>Video Uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s) for content owner %s</li>',
        $status['snippet']['title'],
        $videoId, $contentOwnerId);

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $assetId);

    $htmlBody .= "<h3>Claim uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s with policy "%s"</li>',
        $claimInsertResponse['id'], $claimInsertResponse['policy']['rules'][0]['action']);

    $htmlBody .= "<h3>Advertising Option Added</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $setAdvertisingResponse['adFormats'][0]);

    $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }
    ?>

    <!doctype html>
    <html>
    <head>
    <title>Claim Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

वीडियो अपलोड करें और उससे कमाई करें

यह कोड सैंपल, YouTube वीडियो को अपलोड करता है और उस पर कमाई करने की नीति लागू करता है. किसी वीडियो से कमाई करने के लिए, आपको उस वीडियो पर YouTube के राइट्स मैनेजमेंट सिस्टम से, किसी एसेट के साथ दावा करना होगा. यह सैंपल वीडियो अपलोड करता है, नई एसेट बनाता है, एसेट का इस्तेमाल करके वीडियो पर दावा करता है, और वीडियो पर कमाई करने से जुड़ी नीति लागू करता है.

कोड ये चरण चलाता है:

  1. यह कॉन्टेंट के मालिक के उस आईडी को हासिल करता है जिसके लिए अनुरोध करने की अनुमति देने वाले उपयोगकर्ता ने अनुरोध किया था. इसके लिए, यह youtubePartner.contentOwners.list एपीआई तरीके को कॉल करता है. इस तरीके में fetchMine पैरामीटर को true पर सेट किया जाता है.

  2. यह Data API के videos.insert तरीके का इस्तेमाल करके, किसी ऐसे चैनल पर वीडियो जोड़ता है जिसे कॉन्टेंट का मालिक मैनेज करता है. यह एपीआई कॉल, onBehalfOfContentOwner डेलिगेशन पैरामीटर को उस कॉन्टेंट के मालिक के आईडी पर सेट करता है जिसे पिछले चरण में हासिल किया गया था. यह सही चैनल की पहचान करने के लिए, onBehalfOfContentOwnerChannel डेलिगेशन पैरामीटर भी सेट करता है.

    अपलोड किए जाने वाले वीडियो को अपलोड करने के लिए, प्रोग्राम Google_MediaFileUpload क्लास का इस्तेमाल करता है, जिसमें resumable upload पैरामीटर को true पर सेट किया जाता है. अगर अपलोड में रुकावट आती है, तो बाद में की जाने वाली कोशिशें उस पॉइंट से अपलोड करना फिर से शुरू कर सकती हैं जहां पिछली कोशिश सफल नहीं हुई थी. यह सुविधा उन प्रोग्राम के लिए काम की है जिन्हें बड़े वीडियो अपलोड करने की ज़रूरत होती है.

  3. वीडियो कॉन्टेंट अपलोड होने के बाद, कोड को एक एसेट ऑब्जेक्ट बनाना होगा, ताकि कॉन्टेंट के मालिकाना हक वाले कॉन्टेंट की पहचान की जा सके. एसेट, YouTube के राइट मैनेजमेंट सिस्टम में बौद्धिक संपत्ति का एक हिस्सा दिखाती है. एसेट के मालिक, एसेट का इस्तेमाल करके, एसेट के कॉन्टेंट से मिलते-जुलते वीडियो को ट्रैक करने, उनसे कमाई करने या उन्हें ब्लॉक करने के लिए नीतियां सेट कर सकते हैं.

    यह कोड, अपलोड किए गए वीडियो का एसेट बनाने के लिए, youtubePartner.assets.insert एपीआई तरीके का इस्तेमाल करता है. इसके बाद, youtubePartner.ownership.update तरीके का इस्तेमाल करके मालिकाना हक तय करता है.

  4. कोड सैंपल के ज़रिए कमाई करने की एक नीति बनाई जाती है. इस नीति का इस्तेमाल करके वीडियो पर दावा किया जाता है.

  5. यह कोड, youtubePartner.claims.insert को कॉल करके, अपलोड किए गए वीडियो पर हाल ही में बनाई गई एसेट से मिलते-जुलते वीडियो का दावा करता है. यह दावा, वीडियो पर कमाई करने से जुड़ी उस नीति पर लागू होता है जिसके लिए पिछले चरण में बनाया गया था.

  6. आखिर में, कोड सैंपल youtubePartner.videoAdvertisingOptions.update तरीके का इस्तेमाल करता है, ताकि वीडियो के दौरान TrueView इनस्ट्रीम विज्ञापन दिखाए जा सकें.

youtubePartner.contentOwners.list तरीके को छोड़कर, YouTube Content ID API के सभी तरीके onBehalfOfContentOwner डेलिगेशन पैरामीटर का इस्तेमाल करते हैं. इस पैरामीटर में, अपनी वैल्यू को कॉन्टेंट के मालिक के आईडी पर सेट किया जाता है.

<?php

/**
 * This sample uploads, claims and monetizes a video by :
 *
 * 1. Finding the content owner ID via "youtubePartner.contentOwners.listContentOwners" method
 * 2. Uploading the video via "youtube.videos.insert" with utilizing "Google_MediaFileUpload"
 * 3. Creating an asset via "youtubePartner.assets.insert" method
 * 4. Creating ownership on the asset via "youtubePartner.ownership.update" method
 * 5. Claiming the video with the asset and a policy via "youtubePartner.claims.insert"
 * 6. Enabling the TrueView advertising on the video via "youtubePartner.videoAdvertisingOptions.update"
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google API Console <https://console.cloud.google.com/>
 * 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 = 'REPLACE ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtubepartner');
$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);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try{

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];

    // REPLACE this value with the path to the file you are uploading.
    $videoPath = "/path/to/file.mp4";

    // REPLACE this value with the ID that uniquely identifies the channel that
    // you are uploading to.
    $channelId = "CHANNEL_ID";

    // Create a snippet with title, description, tags and category ID
    // Create an asset resource and set its snippet metadata and type.
    // This example sets the video's title, description, keyword tags, and
    // video category.
    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test description");
    $snippet->setTags(array("tag1", "tag2"));

    // Numeric video category. See
    // https://developers.google.com/youtube/v3/docs/videoCategories/list
    $snippet->setCategoryId("22");

    // Set the video's status to "public". Valid statuses are "public",
    // "private" and "unlisted".
    $status = new Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = "public";

    // Associate the snippet and status objects with a new video resource.
    $video = new Google_Service_YouTube_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a request for the API's videos.insert method to create and upload the video.
    $insertRequest = $youtube->videos->insert("status,snippet", $video,
        array('onBehalfOfContentOwner' => $contentOwnerId,
            'onBehalfOfContentOwnerChannel' => $channelId));

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($videoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }

    fclose($handle);

    // Set defer back to false to be able to make other calls after the file upload.
    $client->setDefer(false);

    $videoId = $status['id'];

    // Create an asset resource and set its metadata and type. Assets support
    // many metadata fields, but this sample only sets a title and description.
    $asset = new Google_Service_YouTubePartner_Asset();
    $metadata = new Google_Service_YouTubePartner_Metadata();
    $metadata->setTitle("Test asset title");
    $metadata->setDescription("Test asset description");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    // Insert the asset resource. Extract its unique asset ID from the API
    // response.
    $assetInsertResponse = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId = $assetInsertResponse['id'];

    // Create a territory owner with owner, ratio, type and territories
    // Set the asset's ownership data. This example identifies the content
    // owner associated with the authenticated user's account as the asset's
    // owner. It indicates that the content owner owns 100% of the asset
    // worldwide.
    $owners = new Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($contentOwnerId);
    $owners->setRatio(100);
    $owners->setType("exclude");
    $owners->setTerritories(array());

    // Create ownership with a territory owner
    $ownership = new Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral(array($owners));

    // Update the asset's ownership with the rights data defined above.
    $ownershipUpdateResponse = $youtubePartner->ownership->update($assetId, $ownership,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Define a monetization policy for the asset.
    $policy = new Google_Service_YouTubePartner_Policy();
    $policyRule = new Google_Service_YouTubePartner_PolicyRule();
    $policyRule->setAction("monetize");
    $policy->setRules(array($policyRule));

    // Create a claim resource. Identify the video being claimed, the asset
    // that represents the claimed content, the type of content being claimed,
    // and the policy that you want to apply to the claimed video.
    $claim = new Google_Service_YouTubePartner_Claim();
    $claim->setAssetId($assetId);
    $claim->setVideoId($videoId);
    $claim->setPolicy($policy);
    $claim->setContentType("audiovisual");

    // Insert the created claim.
    $claimInsertResponse = $youtubePartner->claims->insert($claim,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    # Enable ads for the video. This example enables the TrueView ad format.
    $option = new Google_Service_YouTubePartner_VideoAdvertisingOption();
    $option->setAdFormats(array("trueview_instream"));
    $setAdvertisingResponse = $youtubePartner->videoAdvertisingOptions->update(
        $videoId, $option, array('onBehalfOfContentOwner' => $contentOwnerId));


    $htmlBody .= "<h3>Video Uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s) for content owner %s</li>',
        $status['snippet']['title'],
        $videoId, $contentOwnerId);

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $assetId);

    $htmlBody .= "<h3>Claim uploaded</h3><ul>";
    $htmlBody .= sprintf('<li>%s with policy "%s"</li>',
        $claimInsertResponse['id'], $claimInsertResponse['policy']['rules'][0]['action']);

    $htmlBody .= "<h3>Advertising Option Added</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $setAdvertisingResponse['adFormats'][0]);

    $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }

    $_SESSION['token'] = $client->getAccessToken();
    } else {
      // If the user hasn't authorized the app, initiate the OAuth flow
      $state = mt_rand();
      $client->setState($state);
      $_SESSION['state'] = $state;

      $authUrl = $client->createAuthUrl();
      $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
    }
    ?>

    <!doctype html>
    <html>
    <head>
    <title>Claim Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

एसेट लेबल बनाना, मैनेज करना, और इस्तेमाल करना

यह कोड सैंपल कई एपीआई कॉल की सीरीज़ बनाता है. इनमें बताया गया है कि एसेट लाइब्रेरी में मौजूद आइटम को कैटगरी में बांटने और खोजने के लिए, एसेट लेबल कैसे बनाए जाएं और उनका इस्तेमाल कैसे किया जाए.

<?php

/**
 * This sample creates, manages and uses asset labels by:
 *
 * 1. Finding the content owner ID with "youtubePartner.contentOwners.list" method
 * 2. Creating an asset label with "youtubePartner.assetLabels.insert" method
 * 3. Retrieving existing asset labels with "youtubePartner.assetLabels.list" method
 * 4. Creating an asset with "youtubePartner.assets.insert" method
 * 5. Setting labels of an existing asset with "youtubePartner.assets.update" method
 * 4. Searching assets based on their labels with "youtubePartner.assetSearch.list" method
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your local copy of the client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 service account name and private key file from the
 * Google API Console <https://console.cloud.google.com/>
 * For more information about using OAuth 2.0 Service Accounts to access Google APIs, please see:
 * <https://developers.google.com/accounts/docs/OAuth2ServiceAccount>
 * Please ensure that you have enabled the YouTube Data API and the YouTube Content ID API for
 * your project.
 */
$OAUTH2_SERVICE_ACCOUNT_NAME = 'REPLACE ME';

// Make sure that you keep your key.p12 file in a secure location and that the file isn't
// readable by others.
$OAUTH2_KEY_FILE = '/super/secret/path/to/key.p12';

$client = new Google_Client();

// Define an object that will be used to make Data API requests.
$youtube = new Google_Service_YouTube($client);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

/* Load the key in PKCS 12 format. You need to download the key from the
 * Google API Console when the service account is created.
 * Please read https://developers.google.com/youtube/partner/guides/oauth2_for_service_accounts
 * for info on configuration.
 */
$key = file_get_contents($OAUTH2_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
    $OAUTH2_SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/youtubepartner'),
    $key);
$client->setAssertionCredentials($cred);


if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

  try {

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];

    // Create an asset label and set its name.
    $assetLabel = new Google_Service_YouTubePartner_AssetLabel();
    $assetLabel->setLabelName("label1");

    try {
      // Insert the asset label resource. Extract its unique name from the API response.
      $assetLabelsInsertResponse = $youtubePartner->assetLabels->insert($assetLabel,
          array('onBehalfOfContentOwner' => $contentOwnerId));
      $assetLabelName = $assetLabelsInsertResponse['labelName'];
    } catch (Google_Service_Exception $e) {
      // This error indicates that there is already an asset label with the same name.
      if ($e->getCode() == 409) {
        $assetLabelName = "label1";
      } else {
        throw $e;
      }
    }

    // Retrieve asset labels that have been defined by the content owner.
    $assetLabelsListResponseBefore = $youtubePartner->assetLabels->listAssetLabels(
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Create an asset resource and set its metadata and type. Assets support
    // many metadata fields, but this sample only sets a title.
    $asset = new Google_Service_YouTubePartner_Asset();
    $metadata = new Google_Service_YouTubePartner_Metadata();
    $metadata->setTitle("asset1");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    // Call the assets.insert() method to create the asset resource. Extract its unique asset ID from the API
    // response.
    $assetInsertResponse1 = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId1 = $assetInsertResponse1['id'];

    // Modify the list of asset labels associated with the asset resource, then call
    // the assets.update() method to update the resource.
    $assetInsertResponse1['label'] = array($assetLabelName,"label2");
    $assetUpdateResponse1 = $youtubePartner->assets->update($assetId1, $assetInsertResponse1,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Call the assets.insert() method to create another asset.
    // This code reuses the $asset and $metadata variables created earlier,
    // but updates the title in the metadata before creating the asset.
    // The code then extracts the unique asset ID from the API response.
    $metadata->setTitle("asset2");
    $assetInsertResponse2 = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId2 = $assetInsertResponse2['id'];

    // Modify the list of asset labels associated with the asset resource, then call
    // the assets.update() method to update the resource.
    $assetInsertResponse2['label'] = array("label2");
    $assetUpdateResponse2 = $youtubePartner->assets->update($assetId2, $assetInsertResponse2,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Retrieve asset labels that have been defined by the content owner. This list of labels
    // can be compared to the list retrieved earlier to see the effect of the API call.
    $assetLabelsListResponseAfter = $youtubePartner->assetLabels->listAssetLabels(
        array('onBehalfOfContentOwner' => $contentOwnerId));

    /*
     * AssetSearch may not be able to return the expected results right away, as there is a delay
     * in indexing the assets with labels for the asset search after they are added.
     * If you run this code sample a second time, you should see the assets created in
     * the previous run.
     */
    // Search for assets having both 'label1' and 'label2' labels.
    // The results should include "asset1" after indexing is succesfully finished.
    $assetSearchResponse1 = $youtubePartner->assetSearch->listAssetSearch(
        array('labels' => "label1, label2", 'onBehalfOfContentOwner' => $contentOwnerId));

    // Search for assets having at least one of 'label1' and 'label2' labels.
    // The results should include "asset1" and "asset2" after indexing is succesfully finished.
    $assetSearchResponse2 = $youtubePartner->assetSearch->listAssetSearch(
        array('labels' => "label1, label2", 'includeAnyProvidedlabel' => true,
            'onBehalfOfContentOwner' => $contentOwnerId));


    $htmlBody .= "<h3>Content owner</h3><ul>";
    $htmlBody .= sprintf('<li>Content owner %s</li>',
        $contentOwnerId);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset label created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $assetLabelName);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset Labels Before</h3><ul>";
    foreach ($assetLabelsListResponseBefore['items'] as $labelItem) {
      $htmlBody .= sprintf('<li>%s</li>', $labelItem['labelName']);
    }
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>', $assetId1);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Added asset labels</h3><ul>";
    $htmlBody .= sprintf('<li>%s %s to %s</li>', $assetInsertResponse1['label'][0],
         $assetInsertResponse1['label'][1], $assetId1);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>', $assetId2);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Added asset labels</h3><ul>";
    $htmlBody .= sprintf('<li>%s to %s</li>', $assetInsertResponse2['label'][0], $assetId2);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset Labels After</h3><ul>";
    foreach ($assetLabelsListResponseAfter['items'] as $labelItem) {
      $htmlBody .= sprintf('<li>%s</li>', $labelItem['labelName']);
    }
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset labeled with label1 and label2 </h3><ul>";
    foreach ($assetSearchResponse1['items'] as $assetItem) {
      $htmlBody .= sprintf('<li>%s</li>', $assetItem['id']);
    }
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset labeled with label1 and/or label2 </h3><ul>";
    foreach ($assetSearchResponse2['items'] as $assetItem) {
      $htmlBody .= sprintf('<li>%s</li>', $assetItem['id']);
    }
    $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }

    ?>

    <!doctype html>
    <html>
    <head>
    <title>Assets Labels Example</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

पहचान फ़ाइल अपलोड करें (सेवा खाते की अनुमति देना)

ध्यान दें: इस उदाहरण में, सेवा खाते की अनुमति का इस्तेमाल किया गया है.

यह कोड सैंपल बताता है कि YouTube Content ID API का इस्तेमाल करके पहचान फ़ाइल को कैसे अपलोड किया जाता है. पहचान फ़ाइल, किसी ऐसेट के असल कॉन्टेंट के बारे में बताती है. YouTube, अपलोड किए गए नए वीडियो की तुलना, पहचान फ़ाइलों की लाइब्रेरी से करता है. इससे एसेट के मालिक(मालिकों) के लिए, अपने-आप दावे जनरेट होते हैं. पहचान फ़ाइल अपलोड करने के लिए, हमें पहले ऐसी एसेट बनानी होगी जो मालिकाना हक वाले डेटा और AssetMatchPolicy के बारे में बताती है.

ऐसा करने के लिए, नीचे दिया गया कोड नीचे दिए गए चरणों को पूरा करता है:

  1. यह कॉन्टेंट के मालिक के उस आईडी को हासिल करता है जिसके लिए अनुरोध करने की अनुमति देने वाले उपयोगकर्ता ने अनुरोध किया था. इसके लिए, यह youtubePartner.contentOwners.list एपीआई तरीके को कॉल करता है. इस तरीके में fetchMine पैरामीटर को true पर सेट किया जाता है.
  2. यह एसेट बनाने के लिए, youtubePartner.assets.insert तरीके को कॉल करता है.
  3. यह youtubePartner.ownership.update तरीके को कॉल करके, एसेट के मालिकाना हक का डेटा सेट करता है.
  4. यह एसेट के लिए, मिलते-जुलते वीडियो से जुड़ी नीति सेट करने के लिए youtubePartner.assetMatchPolicy.update को कॉल करता है.
  5. यह ऐसेट की पहचान फ़ाइल अपलोड करने के लिए, youtubePartner.references.insert तरीके को कॉल करता है. अपलोड किए जाने वाले वीडियो को अपलोड करने के लिए, यह प्रोग्राम Google_MediaFileUpload क्लास का इस्तेमाल करता है और resumable upload पैरामीटर को true पर सेट करता है. अगर अपलोड में रुकावट आती है, तो बाद में की जाने वाली कोशिशें उस पॉइंट से अपलोड करना फिर से शुरू कर सकती हैं जहां पिछली कोशिश सफल नहीं हुई थी. यह सुविधा उन प्रोग्राम के लिए काम की है जिन्हें बड़े वीडियो अपलोड करने की ज़रूरत होती है.

youtubePartner.contentOwners.list तरीके को छोड़कर, YouTube Content ID API के सभी तरीके onBehalfOfContentOwner डेलिगेशन पैरामीटर का इस्तेमाल करते हैं. इस पैरामीटर में, अपनी वैल्यू को कॉन्टेंट के मालिक के आईडी पर सेट किया जाता है.

<?php

/**
 * This sample creates an asset, asset ownership, match policy and uploads a reference video by:
 *
 * 1. Finding the content owner ID with "youtubePartner.contentOwners.list" method
 * 2. Creating an asset with "youtubePartner.assets.insert" method
 * 3. Configure ownership on the asset with "youtubePartner.ownership.update" method
 * 4. Configure the asset's match policy with "youtubePartner.assetMatchPolicy.update" method
 * 5. Creating a refererence with "youtubePartner.reference.insert" method
 * 6. Uploading a reference video with "youtube.videos.insert" utilizing "Google_MediaFileUpload"
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 service account name and private key file from the
 * Google API Console <https://console.cloud.google.com/>
 * For more information about using OAuth 2.0 Service Accounts to access Google APIs, please see:
 * <https://developers.google.com/accounts/docs/OAuth2ServiceAccount>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_SERVICE_ACCOUNT_NAME = 'REPLACE ME';

// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
$OAUTH2_KEY_FILE = '/super/secret/path/to/key.p12';

$client = new Google_Client();

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

/* Load the key in PKCS 12 format. You need to download this from the
 * Google API Console when the service account was created.
 * Please read https://developers.google.com/youtube/partner/guides/oauth2_for_service_accounts
 * for info on configuration.
 */
$key = file_get_contents($OAUTH2_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
    $OAUTH2_SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/youtubepartner'),
    $key);
$client->setAssertionCredentials($cred);


if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

  try{

    // REPLACE this value with the path to the file you are uploading
    // as a reference.
    $referenceVideoPath = "/path/to/file.mp4";

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];


    // Create an asset resource and set its metadata and type. Assets support
    // many metadata fields, but this sample only sets a title and description.
    $asset = new Google_Service_YouTubePartner_Asset();
    $metadata = new Google_Service_YouTubePartner_Metadata();
    $metadata->setTitle("Test asset title");
    $metadata->setDescription("Test asset description");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    // Insert the asset resource. Extract its unique asset ID from the API
    // response.
    $assetInsertResponse = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId = $assetInsertResponse['id'];

    // Set the asset's ownership data. This example identifies the content
    // owner associated with the authenticated user's account as the asset's
    // owner. It indicates that the content owner owns 100% of the asset in
    // Great Britain and Poland.
    $owners = new Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($contentOwnerId);
    $owners->setRatio(100);
    $owners->setType("include");
    $owners->setTerritories(array("PL","GB"));

    // Define the rights that the owner owns for the asset.
    $ownership = new Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral(array($owners));

    // Update the asset's ownership with the rights data defined above.
    $ownershipUpdateResponse = $youtubePartner->ownership->update($assetId,
        $ownership, array('onBehalfOfContentOwner' => $contentOwnerId));

    $requiredTerritories = new Google_Service_YouTubePartner_TerritoryCondition();
    $requiredTerritories->setTerritories(array());
    $requiredTerritories->setType("exclude");

    // Create a "track" policy for the asset. The policy specifies the
    // conditions when the policy will be applied by defining a duration,
    // territories where the policy applies, and the type of content that an
    // uploaded video must match.
    $everywherePolicyCondition = new Google_Service_YouTubePartner_Conditions();
    $everywherePolicyCondition->setContentMatchType(array("video"));
    $everywherePolicyCondition->setRequiredTerritories($requiredTerritories);
    $everywherePolicyCondition->setReferenceDuration(array("low" => 10));

    // Create a policy rule and associate the conditions with the rule.
    $trackEverywhereRule = new Google_Service_YouTubePartner_PolicyRule();
    $trackEverywhereRule->setAction("track");
    $trackEverywhereRule->setConditions($everywherePolicyCondition);

    // Associate the policy rule with an assetMatchPolicy resource.
    $assetMatchPolicy = new Google_Service_YouTubePartner_AssetMatchPolicy();
    $assetMatchPolicy->setRules(array($trackEverywhereRule));


    // Update the asset's match policy
    $youtubePartner->assetMatchPolicy->update($assetId, $assetMatchPolicy,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a reference resource. Set the asset ID associated with the
    // reference, and identify the type of reference content being uploaded.
    $reference = new Google_Service_YouTubePartner_Reference();
    $reference->setAssetId($assetId);
    $reference->setContentType("video");

    // Create a request for the API's references.insert method to insert the reference resource
    // while uploading the reference video.
    $insertRequest = $youtubePartner->references->insert($reference,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($referenceVideoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($referenceVideoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }

    fclose($handle);

    // Set defer back to false to be able to make other calls after the file upload.
    $client->setDefer(false);


    $htmlBody .= "<h3>Content owner</h3><ul>";
    $htmlBody .= sprintf('<li>Content owner %s</li>',
        $contentOwnerId);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $assetId);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset ownership has been created</h3>";

    $htmlBody .= "<h3>Asset match policy has been created</h3>";

    $htmlBody .= "<h3>Reference has been created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $status['id']);
    $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }

    ?>

    <!doctype html>
    <html>
    <head>
    <title>Reference Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

पहचान फ़ाइल अपलोड करें

यह कोड सैंपल बताता है कि YouTube Content ID API का इस्तेमाल करके पहचान फ़ाइल को कैसे अपलोड किया जाता है. पहचान फ़ाइल, किसी ऐसेट के असल कॉन्टेंट के बारे में बताती है. YouTube, अपलोड किए गए नए वीडियो की तुलना, पहचान फ़ाइलों की लाइब्रेरी से करता है. इससे एसेट के मालिक(मालिकों) के लिए, अपने-आप दावे जनरेट होते हैं. पहचान फ़ाइल अपलोड करने के लिए, हमें पहले ऐसी एसेट बनानी होगी जो मालिकाना हक वाले डेटा और AssetMatchPolicy के बारे में बताती है.

ऐसा करने के लिए, नीचे दिया गया कोड नीचे दिए गए चरणों को पूरा करता है:

  1. यह कॉन्टेंट के मालिक के उस आईडी को हासिल करता है जिसके लिए अनुरोध करने की अनुमति देने वाले उपयोगकर्ता ने अनुरोध किया था. इसके लिए, यह youtubePartner.contentOwners.list एपीआई तरीके को कॉल करता है. इस तरीके में fetchMine पैरामीटर को true पर सेट किया जाता है.
  2. यह एसेट बनाने के लिए, youtubePartner.assets.insert तरीके को कॉल करता है.
  3. यह youtubePartner.ownership.update तरीके को कॉल करके, एसेट के मालिकाना हक का डेटा सेट करता है.
  4. यह एसेट के लिए, मिलते-जुलते वीडियो से जुड़ी नीति सेट करने के लिए youtubePartner.assetMatchPolicy.update को कॉल करता है.
  5. यह ऐसेट की पहचान फ़ाइल अपलोड करने के लिए, youtubePartner.references.insert तरीके को कॉल करता है. अपलोड किए जाने वाले वीडियो को अपलोड करने के लिए, यह प्रोग्राम Google_MediaFileUpload क्लास का इस्तेमाल करता है और resumable upload पैरामीटर को true पर सेट करता है. अगर अपलोड में रुकावट आती है, तो बाद में की जाने वाली कोशिशें उस पॉइंट से अपलोड करना फिर से शुरू कर सकती हैं जहां पिछली कोशिश सफल नहीं हुई थी. यह सुविधा उन प्रोग्राम के लिए काम की है जिन्हें बड़े वीडियो अपलोड करने की ज़रूरत होती है.

youtubePartner.contentOwners.list तरीके को छोड़कर, YouTube Content ID API के सभी तरीके onBehalfOfContentOwner डेलिगेशन पैरामीटर का इस्तेमाल करते हैं. इस पैरामीटर में, अपनी वैल्यू को कॉन्टेंट के मालिक के आईडी पर सेट किया जाता है.

<?php

/**
 * This sample creates an asset, asset ownership, match policy and uploads a reference video by:
 *
 * 1. Finding the content owner ID with "youtubePartner.contentOwners.list" method
 * 2. Creating an asset with "youtubePartner.assets.insert" method
 * 3. Configure ownership on the asset with "youtubePartner.ownership.update" method
 * 4. Configure the asset's match policy with "youtubePartner.assetMatchPolicy.update" method
 * 5. Creating a refererence with "youtubePartner.reference.insert" method
 * 6. Uploading a reference video with "youtube.videos.insert" utilizing "Google_MediaFileUpload"
 *
 * @author Ibrahim Ulukaya
*/


// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google API Console <https://console.cloud.google.com/>
 * 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 = 'REPLACE ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtubepartner');
$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);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try{

    // REPLACE this value with the path to the file you are uploading
    // as a reference.
    $referenceVideoPath = "/path/to/file.mp4";

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];


    // Create an asset resource and set its metadata and type. Assets support
    // many metadata fields, but this sample only sets a title and description.
    $asset = new Google_Service_YouTubePartner_Asset();
    $metadata = new Google_Service_YouTubePartner_Metadata();
    $metadata->setTitle("Test asset title");
    $metadata->setDescription("Test asset description");
    $asset->setMetadata($metadata);
    $asset->setType("web");

    // Insert the asset resource. Extract its unique asset ID from the API
    // response.
    $assetInsertResponse = $youtubePartner->assets->insert($asset,
        array('onBehalfOfContentOwner' => $contentOwnerId));
    $assetId = $assetInsertResponse['id'];

    // Set the asset's ownership data. This example identifies the content
    // owner associated with the authenticated user's account as the asset's
    // owner. It indicates that the content owner owns 100% of the asset in
    // Great Britain and Poland.
    $owners = new Google_Service_YouTubePartner_TerritoryOwners();
    $owners->setOwner($contentOwnerId);
    $owners->setRatio(100);
    $owners->setType("include");
    $owners->setTerritories(array("PL","GB"));

    // Define the rights that the owner owns for the asset.
    $ownership = new Google_Service_YouTubePartner_RightsOwnership();
    $ownership->setGeneral(array($owners));

    // Update the asset's ownership with the rights data defined above.
    $ownershipUpdateResponse = $youtubePartner->ownership->update($assetId,
        $ownership, array('onBehalfOfContentOwner' => $contentOwnerId));

    $requiredTerritories = new Google_Service_YouTubePartner_TerritoryCondition();
    $requiredTerritories->setTerritories(array());
    $requiredTerritories->setType("exclude");

    // Create a "track" policy for the asset. The policy specifies the
    // conditions when the policy will be applied by defining a duration,
    // territories where the policy applies, and the type of content that an
    // uploaded video must match.
    $everywherePolicyCondition = new Google_Service_YouTubePartner_Conditions();
    $everywherePolicyCondition->setContentMatchType(array("video"));
    $everywherePolicyCondition->setRequiredTerritories($requiredTerritories);
    $everywherePolicyCondition->setReferenceDuration(array("low" => 10));

    // Create a policy rule and associate the conditions with the rule.
    $trackEverywhereRule = new Google_Service_YouTubePartner_PolicyRule();
    $trackEverywhereRule->setAction("track");
    $trackEverywhereRule->setConditions($everywherePolicyCondition);

    // Associate the policy rule with an assetMatchPolicy resource.
    $assetMatchPolicy = new Google_Service_YouTubePartner_AssetMatchPolicy();
    $assetMatchPolicy->setRules(array($trackEverywhereRule));


    // Update the asset's match policy
    $youtubePartner->assetMatchPolicy->update($assetId, $assetMatchPolicy,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a reference resource. Set the asset ID associated with the
    // reference, and identify the type of reference content being uploaded.
    $reference = new Google_Service_YouTubePartner_Reference();
    $reference->setAssetId($assetId);
    $reference->setContentType("video");

    // Create a request for the API's references.insert method to insert the reference resource
    // while uploading the reference video.
    $insertRequest = $youtubePartner->references->insert($reference,
        array('onBehalfOfContentOwner' => $contentOwnerId));

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($referenceVideoPath));


    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($referenceVideoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }

    fclose($handle);

    // Set defer back to false to be able to make other calls after the file upload.
    $client->setDefer(false);


    $htmlBody .= "<h3>Content owner</h3><ul>";
    $htmlBody .= sprintf('<li>Content owner %s</li>',
        $contentOwnerId);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $assetId);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>Asset ownership has been created</h3>";

    $htmlBody .= "<h3>Asset match policy has been created</h3>";

    $htmlBody .= "<h3>Reference has been created</h3><ul>";
    $htmlBody .= sprintf('<li>%s</li>',
        $status['id']);
    $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }

    $_SESSION['token'] = $client->getAccessToken();
    } else {
      // If the user hasn't authorized the app, initiate the OAuth flow
      $state = mt_rand();
      $client->setState($state);
      $_SESSION['state'] = $state;

      $authUrl = $client->createAuthUrl();
      $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
    }
    ?>

    <!doctype html>
    <html>
    <head>
    <title>Reference Uploaded</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

कॉन्टेंट के मालिक के मैनेज किए जा रहे चैनलों को वापस पाना (सेवा खाते की अनुमति देना)

ध्यान दें: इस उदाहरण में, सेवा खाते की अनुमति का इस्तेमाल किया गया है.

यह कोड सैंपल उन चैनलों को वापस पाने का तरीका बताता है जिन्हें कॉन्टेंट का मालिक मैनेज करता है.

कोड सैंपल तब शुरू होता है, जब youtubePartner.contentOwners.list एपीआई तरीके को कॉल किया जाता है. इसमें mine पैरामीटर को true पर सेट किया जाता है. यह अनुरोध, उस उपयोगकर्ता के कॉन्टेंट के मालिक के आईडी को फ़ेच करता है जिसे इसकी अनुमति है. इसके बाद, उस आईडी का इस्तेमाल करके कोड, Data API के youtube.channels.list तरीके को कॉल करता है, ताकि कॉन्टेंट के मालिक के मैनेज किए जाने वाले चैनलों को वापस लाया जा सके. यह कॉल, डेलिगेशन पैरामीटर का इस्तेमाल करता है. इसमें onBehalfOfContentOwner पैरामीटर को कॉन्टेंट के मालिक के आईडी और managedByMe पैरामीटर को true पर सेट किया जाता है.

<?php

/**
 * This sample lists channels that are managed by the authorized account's content ID by:
 *
 * 1. Finding the content owner ID with "youtubePartner.contentOwners.listContentOwners" method
 * 2. Listing channels with "youtube.channels.list" method and delegation parameters
 * 3. Utilizing pageToken to retrieve next set of results, repeating the process if necessary
 *
 * @author Ibrahim Ulukaya
 */

// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
require_once 'Google/Service/YouTubePartner.php';
session_start();

/*
 * You can acquire an OAuth 2.0 service account name and private key file from the
 * Google API Console <https://console.cloud.google.com/>
 * For more information about using OAuth 2.0 Service Accounts to access Google APIs, please see:
 * <https://developers.google.com/accounts/docs/OAuth2ServiceAccount>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_SERVICE_ACCOUNT_NAME = 'REPLACE ME';

// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
$OAUTH2_KEY_FILE = '/super/secret/path/to/key.p12';

$client = new Google_Client();

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// YouTube Partner object used to make Content ID API requests.
$youtubePartner = new Google_Service_YouTubePartner($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

/* Load the key in PKCS 12 format. You need to download this from the
 * Google API Console when the service account was created.
 * Please read https://developers.google.com/youtube/partner/guides/oauth2_for_service_accounts
 * for info on configuration.
 */
$key = file_get_contents($OAUTH2_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
    $OAUTH2_SERVICE_ACCOUNT_NAME,
    array('https://www.googleapis.com/auth/youtubepartner'),
    $key);
$client->setAssertionCredentials($cred);


if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

  try{

    // Call the contentOwners.list method to retrieve the ID of the content
    // owner associated with the currently authenticated user's account.
    $contentOwnersListResponse = $youtubePartner->contentOwners->listContentOwners(
        array('fetchMine' => true));
    $contentOwnerId = $contentOwnersListResponse['items'][0]['id'];

    // Call the YouTube Data API's channels.list method to retrieve a list of
    // channels that the content owner manages.
    $listResponse = $youtube->channels->listChannels("snippet", array('onBehalfOfContentOwner' => $contentOwnerId,
        'managedByMe' => true, 'maxResults' => 50));

    $channels = '';

    while (!empty($listResponse['items'])) {
      foreach ($listResponse['items'] as $listResult) {
            $channels .= sprintf('<li>%s (%s)</li>', $listResult['snippet']['title'],
            $listResult['id']);
      }

      // If the API response returns a pageToken, use that value to request the
      // next set of results.
      $pageToken = $listResponse['pageToken'];
      if(is_null($pageToken))
        break;
      $listResponse = $youtube->channels->listChannels("snippet", array('onBehalfOfContentOwner' => $contentOwnerId,
          'managedByMe' => true, 'maxResults' => 50, 'pageToken' => $pageToken));
    }

    $htmlBody .= <<<END
    <h3>Channels</h3>
    <ul>$channels</ul>
END;
  } catch (Google_Service_Exception $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }



?>

<!doctype html>
<html>
  <head>
    <title>My Managed Channels</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>