ध्यान दें: YouTube Data API का इस्तेमाल, YouTube के कॉन्टेंट पार्टनर कर सकते हैं. यह सभी डेवलपर या YouTube के सभी उपयोगकर्ताओं के लिए उपलब्ध नहीं है. इसे ऐक्सेस करने के लिए, YouTube Content Manager खाते की ज़रूरत होती है. अगर आपके पास YouTube Content Manager खाता है, लेकिन आपको Google Cloud console में YouTube Data API, सेवाओं की सूची में नहीं दिख रहा है, तो अपने पार्टनर मैनेजर या पार्टनर सहायता टीम से संपर्क करें.
इस कोड सैंपल में, YouTube वीडियो अपलोड करने और उस पर कमाई करने की नीति लागू करने का तरीका बताया गया है. किसी वीडियो से कमाई करने के लिए, आपको YouTube के अधिकार प्रबंधन सिस्टम में asset का इस्तेमाल करके, उस वीडियो पर दावा करना होगा. इस सैंपल में, वीडियो अपलोड किया जाता है, नई ऐसेट बनाई जाती है, ऐसेट का इस्तेमाल करके वीडियो पर दावा किया जाता है, और वीडियो पर कमाई करने से जुड़ी नीति लागू की जाती है.
इस उदाहरण में, कोड के ज़रूरी सेक्शन के साथ-साथ, इसमें शामिल चरणों की सीरीज़ भी दिखाई गई है. आपको पूरी स्क्रिप्ट इस पेज के आखिर में मिलेगी. यह कोड Python में लिखा गया है. अन्य लोकप्रिय प्रोग्रामिंग भाषाओं के लिए भी क्लाइंट लाइब्रेरी उपलब्ध हैं.
ज़रूरी शर्तें
- Python 3.7 या इसके बाद का वर्शन
- google-api-python-client
पहला चरण: सामान्य रखरखाव के फ़ंक्शन
कोड सैंपल के पहले सेक्शन में, सामान्य हाउसकीपिंग फ़ंक्शन शामिल होते हैं. ये फ़ंक्शन, कई स्क्रिप्ट में इस्तेमाल किए जाते हैं: कमांड लाइन पार्स करना, उपयोगकर्ता की पुष्टि करना, और ज़रूरी एपीआई सेवाएं पाना.
कमांड लाइन को पार्स करना
parse_options तरीके में, Python क्लाइंट लाइब्रेरी से OptionParser का इस्तेमाल किया जाता है. इससे एक options ऑब्जेक्ट बनाया जाता है, जिसमें हर कमांड-लाइन आर्ग्युमेंट को प्रॉपर्टी के तौर पर शामिल किया जाता है. इसके बाद के तरीके, ज़रूरत के मुताबिक options ऑब्जेक्ट से वैल्यू वापस पाते हैं.
सैंपल स्क्रिप्ट के कमांड-लाइन आर्ग्युमेंट यहां दिए गए हैं. पहले दो (file और channelId) ज़रूरी हैं; बाकी ज़रूरी नहीं हैं.
-
file: अपलोड की जाने वाली वीडियो फ़ाइल का नाम और जगह.Example: --file="/home/path/to/file.mov"
-
channelId: वह YouTube चैनल जिस पर आपको वीडियो अपलोड करना है. चैनल को, पुष्टि किए गए उपयोगकर्ता के YouTube Content Manager खाते से मैनेज किया जाना चाहिए. चैनल आईडी को, पुष्टि किए गए उपयोगकर्ता के लिए YouTube खाते की सेटिंग में जाकर याchannels.listतरीके का इस्तेमाल करके वापस पाया जा सकता है.Example: --channelId="UC_x5XG1OV2P6uZZ5FSM9Ttw"
-
title: अपलोड किए जा रहे वीडियो का टाइटल. डिफ़ॉल्ट वैल्यूTest titleहै.Example: --title="Summer vacation in California"
-
description: अपलोड किए जा रहे वीडियो का ब्यौरा. डिफ़ॉल्ट वैल्यूTest descriptionहै.Example: --description="Had a great time surfing in Santa Cruz"
-
category: वीडियो से जुड़ी YouTube वीडियो कैटगरी का कैटगरी आईडी. डिफ़ॉल्ट वैल्यू22होती है, जिसका मतलबPeople & Blogsकैटगरी से है.Example: --category=22
-
keywords: वीडियो से जुड़े कीवर्ड की कॉमा लगाकर अलग की गई सूची. डिफ़ॉल्ट वैल्यू, खाली स्ट्रिंग होती है.Example: --keywords="surfing, beach volleyball"
-
privacyStatus: वीडियो की निजता की स्थिति. अपलोड किए गए वीडियो के लिए, डिफ़ॉल्ट तौर पर यह सेटिंग होती है कि वह सार्वजनिक तौर पर दिखे (public). टेस्ट वीडियो अपलोड करते समय, हो सकता है कि आपको--privacyStatusआर्ग्युमेंट की वैल्यू तय करनी पड़े, ताकि यह पक्का किया जा सके कि वे वीडियो निजी या 'सबके लिए मौजूद नहीं' के तौर पर सेट हों. मान्य वैल्यूpublic,private, औरunlistedहैं.Example: --privacyStatus="private"
-
policyId: अपलोड किए गए वीडियो पर लागू होने वाली कमाई करने की नीति. नीति, पुष्टि किए गए उपयोगकर्ता के YouTube कॉन्टेंट मैनेजर खाते से जुड़ी होनी चाहिए. डिफ़ॉल्ट रूप से, YouTube पर "कमाई करने" से जुड़ी स्टैंडर्ड नीति लागू होती है.Example: --policyId="S309961703555739"
def parse_options(): parser = argparse.ArgumentParser( description="Uploads and claims a video on YouTube.") parser.add_argument("--file", required=True, help="Video file to upload") parser.add_argument("--title", default="Test Title", help="Video title") parser.add_argument("--description", default="Test Description", help="Video description") parser.add_argument("--category", default="22", help="Numeric video category. See https://developers.google.com/youtube/v3/docs/videoCategories/list") parser.add_argument("--keywords", default="", help="Video keywords, comma separated") parser.add_argument("--privacyStatus", default="public", choices=["public", "private", "unlisted"], help="Video privacy status: public, private or unlisted") parser.add_argument("--policyId", help="Optional id of a saved claim policy") parser.add_argument("--channelId", required=True, help="Id of the channel to upload to. Must be managed by your CMS account") return parser.parse_args()
अनुरोध को अनुमति देना
इस चरण में, हम स्क्रिप्ट में OAuth 2.0 ऑथराइज़ेशन को शामिल करते हैं. इससे स्क्रिप्ट चलाने वाला उपयोगकर्ता, स्क्रिप्ट को यह अनुमति दे पाता है कि वह उपयोगकर्ता के खाते से जुड़े एपीआई अनुरोधों को पूरा कर सके.
client_secrets.json फ़ाइल बनाना
सैंपल में दिखाए गए अनुमति के टाइप के लिए, client_secrets.json फ़ाइल की ज़रूरत होती है. इसमें Google Cloud Console से मिली जानकारी होती है. आपको अपने ऐप्लिकेशन को रजिस्टर भी करना होगा. अनुमति देने की प्रोसेस के बारे में ज़्यादा जानकारी के लिए, अनुमति देने से जुड़ी गाइड देखें. ध्यान दें कि इस सैंपल के लिए, आपके प्रोजेक्ट में Cloud Console में YouTube Data API V3 और YouTube Content ID API सेवा, दोनों को कॉन्फ़िगर करना ज़रूरी है.
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } }
स्क्रिप्ट में ऑथराइज़ेशन कोड
उपयोगकर्ता की पुष्टि करने और उसे अनुमति देने के लिए, स्क्रिप्ट में ये import स्टेटमेंट शामिल हैं:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
इसके बाद, get_authenticated_services तरीके से, पिछले चरण में कॉन्फ़िगर की गई client_secrets.json फ़ाइल के डेटा का इस्तेमाल करके FLOW ऑब्जेक्ट बनाया जाता है. अगर उपयोगकर्ता हमारे ऐप्लिकेशन को अपनी ओर से एपीआई अनुरोध सबमिट करने की अनुमति देता है, तो मिले हुए क्रेडेंशियल को बाद में इस्तेमाल करने के लिए, Storage ऑब्जेक्ट में सेव किया जाता है. क्रेडेंशियल की समयसीमा खत्म होने पर, उपयोगकर्ता को हमारे ऐप्लिकेशन को फिर से अनुमति देनी होगी.
YOUTUBE_SCOPES = ( # An OAuth 2 access scope that allows for full read/write access. "https://www.googleapis.com/auth/youtube", # A scope that grants access to YouTube Partner API functionality. "https://www.googleapis.com/auth/youtubepartner") flow = flow_from_clientsecrets( CLIENT_SECRETS_FILE, scope=" ".join(YOUTUBE_SCOPES), message=MISSING_CLIENT_SECRETS_MESSAGE ) storage = Storage(CACHED_CREDENTIALS_FILE) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(flow, storage)
सेवाएं पाना
अनुमति मिलने के बाद, हम उन कार्रवाइयों के लिए ज़रूरी सेवाएं पाते हैं जिन्हें हमें पूरा करना है. इस सैंपल में, वीडियो अपलोड करने के लिए YouTube Data API का इस्तेमाल किया गया है. साथ ही, ऐसेट बनाने और वीडियो पर दावा करने के लिए YouTube Content ID API का इस्तेमाल किया गया है. हम दो एपीआई की सुविधाओं को ऐक्सेस करने की अनुमति देने के लिए, अलग-अलग सेवाएं बनाते हैं.
from googleapiclient.discovery import build import httplib2 YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" YOUTUBE_CONTENT_ID_API_SERVICE_NAME = "youtubePartner" YOUTUBE_CONTENT_ID_API_VERSION = "v1" youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) youtube_partner = build(YOUTUBE_CONTENT_ID_API_SERVICE_NAME, YOUTUBE_CONTENT_ID_API_VERSION, http=credentials.authorize(httplib2.Http()), static_discovery=False) return (youtube, youtube_partner)
दूसरा चरण: कॉन्टेंट के मालिक की पहचान करना
ऐसेट बनाने और दावे करने के लिए, पुष्टि किए गए उपयोगकर्ता के पास YouTube Content Manager खाता होना चाहिए. Content Manager खाते में, एक या उससे ज़्यादा कॉन्टेंट मालिकों के लिए, अधिकारों को मैनेज करने वाले ऑब्जेक्ट होते हैं. कॉन्टेंट का मालिक, कॉपीराइट का अधिकार रखने वाला व्यक्ति या इकाई होता है. उसके पास यह तय करने का अधिकार होता है कि किसी वीडियो से कमाई करनी है, उसे ट्रैक करना है या ब्लॉक करना है.
get_content_owner तरीके से, पुष्टि किए गए उपयोगकर्ता के कॉन्टेंट मैनेजर खाते में कॉन्टेंट के मालिक का आईडी मिलता है. ज़्यादातर खातों में, कॉन्टेंट का एक ही मालिक होता है. यह पुष्टि किया गया उपयोगकर्ता होता है. हालांकि, अगर खाते में कॉन्टेंट के कई मालिक हैं, तो यह तरीका पहले मालिक की जानकारी दिखाता है.
def get_content_owner_id(youtube_partner): try: content_owners_list_response = youtube_partner.contentOwners().list( fetchMine=True ).execute() except HttpError as e: if INVALID_CREDENTIALS in e.content: logging.error("The request is not authorized by a Google Account that " "is linked to a YouTube content owner. Please delete '%s' and " "re-authenticate with a YouTube content owner account." % CACHED_CREDENTIALS_FILE) exit(1) else: raise # This returns the CMS user id of the first entry returned # by youtubePartner.contentOwners.list() # See https://developers.google.com/youtube/partner/reference/rest/v1/contentOwners/list # Normally this is what you want, but if you authorize with a Google Account # that has access to multiple YouTube content owner accounts, you need to # iterate through the results. return content_owners_list_response["items"][0]["id"]
तीसरा चरण: वीडियो अपलोड करना
वीडियो अपलोड करने के लिए, हम वीडियो को दिखाने वाले JSON संसाधन का एक हिस्सा बनाते हैं और उसे videos.insert तरीके से पास करते हैं. हम वीडियो मेटाडेटा को सेट करने के लिए, options ऑब्जेक्ट की वैल्यू का इस्तेमाल करते हैं. यह ऑब्जेक्ट, कमांड लाइन को पार्स करने के दौरान बनाया जाता है. मीडिया फ़ाइल के लिए, हम MediaFileUpload का इस्तेमाल करते हैं, ताकि फिर से शुरू किए जा सकने वाले अपलोड का इस्तेमाल किया जा सके. ज़्यादा जानकारी के लिए, वीडियो अपलोड करना लेख पढ़ें.
upload तरीके से, नए वीडियो का आईडी मिलता है. स्क्रिप्ट को इस वैल्यू को बाद के चरणों में अन्य तरीकों से पास करना होता है.
def upload(youtube, content_owner_id, options): if options.keywords: tags = options.keywords.split(",") else: tags = None insert_request = youtube.videos().insert( onBehalfOfContentOwner=content_owner_id, onBehalfOfContentOwnerChannel=options.channelId, part="snippet,status", body=dict( snippet=dict( title=options.title, description=options.description, tags=tags, categoryId=options.category ), status=dict( privacyStatus=options.privacyStatus ) ), # chunksize=-1 means that the entire file will be uploaded in a single # HTTP request. (If the upload fails, it will still be retried where it # left off.) media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True) ) response = None error = None retry = 0 duration_seconds=0 while response is None: try: logging.debug("Uploading file...") start_seconds = time.time() status, response = insert_request.next_chunk() delta_seconds = time.time() - start_seconds duration_seconds += delta_seconds if "id" in response: return (response["id"], duration_seconds) else: logging.error("The upload failed with an unexpected response: %s" % response) exit(1) except HttpError as e: if e.resp.status in RETRIABLE_STATUS_CODES: error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: raise except RETRIABLE_EXCEPTIONS as e: error = "A retriable error occurred: %s" % e if error is not None: logging.error(error) retry += 1 if retry > MAX_RETRIES: logging.error("No longer attempting to retry.") exit(1) max_sleep = 2 ** retry sleep_seconds = random.random() * max_sleep logging.debug("Sleeping %f seconds and then retrying..." % sleep_seconds) time.sleep(sleep_seconds)
चौथा चरण: ऐसेट बनाना
YouTube वीडियो से कमाई करने के लिए, आपको पहले उसे किसी ऐसेट से लिंक करना होगा. create_asset तरीके से, अपलोड किए गए नए वीडियो के लिए एक नई ऐसेट बनाई जाती है.
हमने वीडियो के लिए जिस तरह से काम किया था उसी तरह से, हम एक ऐसा JSON संसाधन बनाते हैं जो यह पहचान करता है कि किस तरह की ऐसेट बनानी है (वेब वीडियो). साथ ही, नई ऐसेट के लिए टाइटल और ब्यौरा देता है. हम JSON रिसॉर्स को assets.insert तरीके से पास करते हैं. इससे ऐसेट बनती है और उसका यूनीक आईडी मिलता है. स्क्रिप्ट को बाद के चरणों में, उस वैल्यू को अन्य तरीकों से पास करना होगा.
def create_asset(youtube_partner, content_owner_id, title, description): # This creates a new asset corresponding to a video on the web. # The asset is linked to the corresponding YouTube video via a # claim that will be created later. body = dict( type="web", metadata=dict( title=title, description=description ) ) assets_insert_response = youtube_partner.assets().insert( onBehalfOfContentOwner=content_owner_id, body=body ).execute() return assets_insert_response["id"]
पांचवां चरण: मालिकाना हक अपडेट करना
किसी वीडियो से कमाई करने से पहले, YouTube को यह पता होना चाहिए कि उससे जुड़ी ऐसेट का मालिकाना हक किसके पास है. इसलिए, ऐसेट बनाने के बाद, अब हम ऐसेट के ownership को कॉन्फ़िगर करते हैं. इस सैंपल में, हमने बताया है कि कॉन्टेंट के मालिक के पास ऐसेट का मालिकाना हक दुनिया भर के लिए है.
def set_asset_ownership(youtube_partner, content_owner_id, asset_id): # This specifies that content_owner_id owns 100% of the asset worldwide. # Adjust as needed. body = dict( general=[dict( owner=content_owner_id, ratio=100, type="exclude", territories=[] )] ) youtube_partner.ownership().update( onBehalfOfContentOwner=content_owner_id, assetId=asset_id, body=body ).execute()
छठा चरण: वीडियो पर दावा करना
इसके बाद, अपलोड किए गए वीडियो को उससे जुड़ी ऐसेट से लिंक करने के लिए, वीडियो पर दावा करें. दावे से, वीडियो और YouTube के अधिकारों को मैनेज करने वाले सिस्टम के बीच लिंक बनता है. इससे वीडियो के मालिकाना हक की पुष्टि होती है. साथ ही, मालिक को कमाई करने की नीति सेट करने की सुविधा मिलती है.
claim_video तरीके से, ऑडियो-विज़ुअल के अधिकारों का दावा किया जाता है. अगर आपने कमांड लाइन में policyId पैरामीटर शामिल किया है, तो यह तरीका वीडियो पर बताई गई नीति लागू करता है. अगर आपने पैरामीटर शामिल नहीं किया है, तो यह तरीका "कमाई करें" की स्टैंडर्ड नीति लागू करता है.
def claim_video(youtube_partner, content_owner_id, asset_id, video_id, policy_id): # policy_id can be set to the id of an existing policy, which can be obtained # via youtubePartner.policies.list() # See https://developers.google.com/youtube/partner/reference/rest/v1/policies/list # If you later update that existing policy, the claim will also be updated. if policy_id: policy = dict( id=policy_id ) # If policy_id is not provided, a new inline policy is created. else: policy = dict( rules=[dict( action="monetize" )] ) body = dict( assetId=asset_id, videoId=video_id, policy=policy, contentType="audiovisual" ) youtube_partner.claims().insert( onBehalfOfContentOwner=content_owner_id, body=body ).execute()
सातवां चरण: विज्ञापन दिखाने के विकल्प सेट करना
हमने वीडियो पर दावा किया है और उस पर कमाई करने की नीति लागू की है. आखिरी चरण में, यह तय करना होता है कि वीडियो में किस तरह के विज्ञापन दिखाए जाएं. जब भी "कमाई करना" नीति लागू होती है, तब YouTube विज्ञापन दिखाने के विकल्पों की जांच करता है. इसके बाद, वह सबसे ज़्यादा रेवेन्यू देने वाले विज्ञापन दिखाता है.
इस सैंपल से YouTube को यह पता चलता है कि इस वीडियो के साथ इन-स्ट्रीम TrueView विज्ञापन दिखाने हैं.
def set_advertising_options(youtube_partner, content_owner_id, video_id): # This enables the TrueView ad format for the given video. # Adjust as needed. body = dict( adFormats=["trueview_instream"] ) youtube_partner.videoAdvertisingOptions().update( videoId=video_id, onBehalfOfContentOwner=content_owner_id, body=body ).execute()
पूरा कोड सैंपल
काम करने वाले पूरे सैंपल upload_monetize_video_example.py की सूची यहां दी गई है:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simple command-line sample for Youtube Partner API. Command-line application that creates an asset, uploads and claims a video for that asset. Usage: $ python3 upload_monetize_video_example.py --file=VIDEO_FILE --channelId=CHANNEL_ID \\ [--title=VIDEO_TITLE] [--description=VIDEO_DESCRIPTION] [--category=CATEGORY_ID] \\ [--keywords=KEYWORDS] [--privacyStatus=PRIVACY_STATUS] [--policyId=POLICY_ID] You can also get help on all the command-line flags the program understands by running: $ python3 upload_monetize_video_example.py --help """ __author__ = 'jeffy+pub@google.com (Jeffrey Posnick)' import argparse import http.client as httplib import httplib2 import logging import os import random import sys import time from apiclient.discovery import build from apiclient.errors import HttpError from apiclient.http import MediaFileUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run # Explicitly tell the underlying HTTP transport library not to retry, since # we are handling retry logic ourselves. httplib2.RETRIES = 1 # Maximum number of times to retry before giving up. MAX_RETRIES = 10 # Always retry when these exceptions are raised. RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected, httplib.IncompleteRead, httplib.ImproperConnectionState, httplib.CannotSendRequest, httplib.CannotSendHeader, httplib.ResponseNotReady, httplib.BadStatusLine,) # Always retry when an apiclient.errors.HttpError with one of these status # codes is raised. RETRIABLE_STATUS_CODES = (500, 502, 503, 504,) # The message associated with the HTTP 401 error that's returned when a request # is authorized by a user whose account is not associated with a YouTube # content owner. INVALID_CREDENTIALS = "Invalid Credentials" # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the Google Cloud console at # https://console.cloud.google.com/. # See the "Registering your application" instructions for an explanation # of how to find these values: # https://developers.google.com/youtube/partner/guides/registering_an_application # For more information about using OAuth2 to access Google APIs, please visit: # https://developers.google.com/accounts/docs/OAuth2 # For more information about the client_secrets.json file format, please visit: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = "client_secrets.json" # The local file used to store the cached OAuth 2 credentials after going # through a one-time browser-based login. CACHED_CREDENTIALS_FILE = "%s-oauth2.json" % sys.argv[0] YOUTUBE_SCOPES = ( # An OAuth 2 access scope that allows for full read/write access. "https://www.googleapis.com/auth/youtube", # A scope that grants access to YouTube Partner API functionality. "https://www.googleapis.com/auth/youtubepartner",) YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" YOUTUBE_CONTENT_ID_API_SERVICE_NAME = "youtubePartner" YOUTUBE_CONTENT_ID_API_VERSION = "v1" # Helpful message to display if the CLIENT_SECRETS_FILE is missing. MISSING_CLIENT_SECRETS_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you need to populate the client_secrets.json file at: %s with information from the Cloud console https://console.cloud.google.com/ For more information about the client_secrets.json file format, please visit: https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ % os.path.abspath(os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)) def parse_options(): parser = OptionParser() parser.add_option("--file", dest="file", help="Video file to upload") parser.add_option("--title", dest="title", help="Video title", default="Test Title") parser.add_option("--description", dest="description", help="Video description", default="Test Description") parser.add_option("--category", dest="category", help="Numeric video category. " + "See https://developers.google.com/youtube/v3/docs/videoCategories/list", default="22") parser.add_option("--keywords", dest="keywords", help="Video keywords, comma separated", default="") parser.add_option("--privacyStatus", dest="privacyStatus", help="Video privacy status: public, private or unlisted", default="public") parser.add_option("--policyId", dest="policyId", help="Optional id of a saved claim policy") parser.add_option("--channelId", dest="channelId", help="Id of the channel to upload to. Must be managed by your CMS account") (options, args) = parser.parse_args() return options def get_authenticated_services(): flow = flow_from_clientsecrets( CLIENT_SECRETS_FILE, scope=" ".join(YOUTUBE_SCOPES), message=MISSING_CLIENT_SECRETS_MESSAGE ) storage = Storage(CACHED_CREDENTIALS_FILE) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(flow, storage) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) youtube_partner = build(YOUTUBE_CONTENT_ID_API_SERVICE_NAME, YOUTUBE_CONTENT_ID_API_VERSION, http=credentials.authorize(httplib2.Http()), static_discovery=False) return (youtube, youtube_partner) def get_content_owner_id(youtube_partner): try: content_owners_list_response = youtube_partner.contentOwners().list( fetchMine=True ).execute() except HttpError, e: if INVALID_CREDENTIALS in e.content: logging.error("Your request is not authorized by a Google Account that " "is associated with a YouTube content owner. Please delete '%s' and " "re-authenticate with an account that is associated " "with a content owner." % CACHED_CREDENTIALS_FILE) exit(1) else: raise # This returns the CMS user id of the first entry returned # by youtubePartner.contentOwners.list() # See https://developers.google.com/youtube/partner/reference/rest/v1/contentOwners/list # Normally this is what you want, but if you authorize with a Google Account # that has access to multiple YouTube content owner accounts, you need to # iterate through the results. return content_owners_list_response["items"][0]["id"] def upload(youtube, content_owner_id, options): if options.keywords: tags = options.keywords.split(",") else: tags = None insert_request = youtube.videos().insert( onBehalfOfContentOwner=content_owner_id, onBehalfOfContentOwnerChannel=options.channelId, part="snippet,status", body=dict( snippet=dict( title=options.title, description=options.description, tags=tags, categoryId=options.category ), status=dict( privacyStatus=options.privacyStatus ) ), # chunksize=-1 means that the entire file will be uploaded in a single # HTTP request. (If the upload fails, it will still be retried where it # left off.) This is usually a best practice, but if you're using Python # older than 2.6 or if you're running on App Engine, you should set the # chunksize to something like 1024 * 1024 (1 megabyte). media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True) ) response = None error = None retry = 0 duration_seconds=0 while response is None: try: logging.debug("Uploading file...") start_seconds = time.time() status, response = insert_request.next_chunk() delta_seconds = time.time() - start_seconds duration_seconds += delta_seconds if "id" in response: return (response["id"], duration_seconds) else: logging.error("The upload failed with an unexpected response: %s" % response) exit(1) except HttpError, e: if e.resp.status in RETRIABLE_STATUS_CODES: error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: raise except RETRIABLE_EXCEPTIONS, e: error = "A retriable error occurred: %s" % e if error is not None: logging.error(error) retry += 1 if retry > MAX_RETRIES: logging.error("No longer attempting to retry.") exit(1) max_sleep = 2 ** retry sleep_seconds = random.random() * max_sleep logging.debug("Sleeping %f seconds and then retrying..." % sleep_seconds) time.sleep(sleep_seconds) def create_asset(youtube_partner, content_owner_id, title, description): # This creates a new asset corresponding to a video on the web. # The asset is linked to the corresponding YouTube video via a # claim that will be created later. body = dict( type="web", metadata=dict( title=title, description=description ) ) assets_insert_response = youtube_partner.assets().insert( onBehalfOfContentOwner=content_owner_id, body=body ).execute() return assets_insert_response["id"] def set_asset_ownership(youtube_partner, content_owner_id, asset_id): # This specifies that content_owner_id owns 100% of the asset worldwide. # Adjust as needed. body = dict( general=[dict( owner=content_owner_id, ratio=100, type="exclude", territories=[] )] ) youtube_partner.ownership().update( onBehalfOfContentOwner=content_owner_id, assetId=asset_id, body=body ).execute() def claim_video(youtube_partner, content_owner_id, asset_id, video_id, policy_id): # policy_id can be set to the id of an existing policy, which can be obtained # via youtubePartner.policies.list() # See https://developers.google.com/youtube/partner/reference/rest/v1/policies/list # If you later update that existing policy, the claim will also be updated. if policy_id: policy = dict( id=policy_id ) # If policy_id is not provided, a new inline policy is created. else: policy = dict( rules=[dict( action="monetize" )] ) body = dict( assetId=asset_id, videoId=video_id, policy=policy, contentType="audiovisual" ) claims_insert_response = youtube_partner.claims().insert( onBehalfOfContentOwner=content_owner_id, body=body ).execute() return claims_insert_response["id"] def set_advertising_options(youtube_partner, content_owner_id, video_id): # This enables the true view ad format for the given video. # Adjust as needed. body = dict( adFormats=["trueview_instream"] ) youtube_partner.videoAdvertisingOptions().update( videoId=video_id, onBehalfOfContentOwner=content_owner_id, body=body ).execute() if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) options = parse_options() if options.file is None or not os.path.exists(options.file): logging.error("Please specify a valid file using the --file= parameter.") exit(1) # The channel ID looks something like "UC..." and needs to correspond to a # channel managed by the YouTube content owner authorizing the request. # youtube.channels.list(part="snippet", managedByMe=true, # onBehalfOfContentOwner=*CONTENT_OWNER_ID*) # can be used to retrieve a list of managed channels and their channel IDs. # See https://developers.google.com/youtube/v3/docs/channels/list if options.channelId is None: logging.error("Please specify a channel ID via the --channelId= parameter.") exit(1) (youtube, youtube_partner) = get_authenticated_services() content_owner_id = get_content_owner_id(youtube_partner) logging.info("Authorized by content owner ID '%s'." % content_owner_id) (video_id, duration_seconds) = upload(youtube, content_owner_id, options) logging.info("Successfully uploaded video ID '%s'." % video_id) file_size_bytes = os.path.getsize(options.file) logging.debug("Uploaded %d bytes in %0.2f seconds (%0.2f megabytes/second)." % (file_size_bytes, duration_seconds, (file_size_bytes / (1024 * 1024)) / duration_seconds)) asset_id = create_asset(youtube_partner, content_owner_id, options.title, options.description) logging.info("Created new asset ID '%s'." % asset_id) set_asset_ownership(youtube_partner, content_owner_id, asset_id) logging.info("Successfully set asset ownership.") claim_id = claim_video(youtube_partner, content_owner_id, asset_id, video_id, options.policyId) logging.info("Successfully claimed video.") set_advertising_options(youtube_partner, content_owner_id, video_id) logging.info("Successfully set advertising options.") logging.info("All done!")