Tải lên và xác nhận quyền sở hữu video

Lưu ý: Content ID của YouTube dành cho các đối tác nội dung của YouTube và không phải nhà phát triển hoặc người dùng YouTube nào cũng có thể truy cập được. Nếu bạn không thấy YouTube Content ID API trong danh sách các dịch vụ trong Google API Console, hãy truy cập vào Trung tâm trợ giúp của YouTube để tìm hiểu thêm về Chương trình Đối tác YouTube.

Mã mẫu này minh hoạ cách tải một video lên YouTube và áp dụng chính sách kiếm tiền cho video đó. Để kiếm tiền từ video, bạn phải xác nhận quyền sở hữu video đó bằng asset trong hệ thống quản lý quyền của YouTube. Mẫu này sẽ tải video lên, tạo tài sản mới, xác nhận quyền sở hữu video bằng tài sản đó và áp dụng một chính sách kiếm tiền cho video.

Ví dụ này được trình bày dưới dạng một loạt các bước có liên quan cùng với các phần có liên quan của mã. Bạn có thể tìm thấy toàn bộ tập lệnh ở cuối trang này. Mã này được viết bằng Python. Ngoài ra, chúng tôi cũng cung cấp thư viện ứng dụng cho các ngôn ngữ lập trình phổ biến khác.

Yêu cầu

Bước 1: Các chức năng dọn phòng phổ biến

Phần đầu tiên của mã mẫu sẽ thực hiện các chức năng quản lý cơ bản phổ biến đối với nhiều tập lệnh: phân tích cú pháp dòng lệnh, xác thực người dùng và lấy các dịch vụ API cần thiết.

Phân tích cú pháp dòng lệnh

Phương thức parse_options sử dụng OptionParser trong thư viện ứng dụng Python để tạo một đối tượng options chứa mỗi đối số dòng lệnh dưới dạng một thuộc tính. Các phương thức tiếp theo sẽ truy xuất giá trị của đối tượng options khi cần.

Dưới đây là danh sách các đối số dòng lệnh của tập lệnh mẫu. Hai thuộc tính đầu tiên (filechannelId) là bắt buộc; các thuộc tính còn lại là không bắt buộc.

  • file: Tên và vị trí của tệp video cần tải lên.

    Example: --file="/home/path/to/file.mov"
  • channelId: Kênh YouTube mà bạn muốn tải video lên. Kênh phải do tài khoản Trình quản lý nội dung trên YouTube của người dùng đã xác thực quản lý. Bạn có thể lấy mã nhận dạng kênh trong phần cài đặt tài khoản YouTube của người dùng đã xác thực hoặc bằng cách sử dụng phương thức channels.list.

    Example: --channelId="UC_x5XG1OV2P6uZZ5FSM9Ttw"
  • title: Tiêu đề của video mà bạn đang tải lên. Giá trị mặc định là Test title.

    Example: --title="Summer vacation in California"
  • description: Nội dung mô tả về video mà bạn đang tải lên. Giá trị mặc định là Test description.

    Example: --description="Had a great time surfing in Santa Cruz"
  • category: Mã danh mục cho danh mục video trên YouTube liên kết với video. Giá trị mặc định là 22, đề cập đến danh mục People & Blogs.

    Example: --category=22
  • keywords: Danh sách các từ khoá được phân tách bằng dấu phẩy có liên kết với video. Giá trị mặc định là một chuỗi trống.

    Example: --keywords="surfing, beach volleyball"
  • privacyStatus: Trạng thái quyền riêng tư của video. Hành vi mặc định là để video tải lên hiển thị công khai (public). Khi tải video thử nghiệm lên, bạn có thể muốn chỉ định giá trị đối số --privacyStatus để đảm bảo rằng những video đó ở chế độ riêng tư hoặc không công khai. Các giá trị hợp lệ là public, privateunlisted.

    Example: --privacyStatus="private"
  • policyId: Chính sách kiếm tiền áp dụng cho video đã tải lên. Chính sách đó phải được liên kết với tài khoản Trình quản lý nội dung trên YouTube của người dùng đã xác thực. Lựa chọn mặc định là chính sách "kiếm tiền" tiêu chuẩn của YouTube.

    Example: --policyId="S309961703555739"
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

Uỷ quyền yêu cầu

Trong bước này, chúng ta kết hợp việc uỷ quyền OAuth 2.0 vào tập lệnh. Điều này cho phép người dùng đang chạy tập lệnh cho phép tập lệnh thực hiện các yêu cầu API được phân bổ cho tài khoản của người dùng.

Tạo tệp client_secrets.json

Loại uỷ quyền hiển thị trong mẫu cần có tệp client_secrets.json, chứa thông tin từ Google API Console để thực hiện uỷ quyền. Bạn cũng cần đăng ký ứng dụng của mình. Để xem nội dung giải thích đầy đủ hơn về cách hoạt động của tính năng uỷ quyền, hãy xem hướng dẫn về cách uỷ quyền. Xin lưu ý rằng mẫu này yêu cầu bạn phải định cấu hình cả YouTube Data API phiên bản 3 và dịch vụ YouTube Content ID API trong Bảng điều khiển API cho dự án của mình.

 {
  "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"
  }
}

Mã uỷ quyền trong tập lệnh

Tập lệnh bao gồm các câu lệnh import sau để bật tính năng xác thực và uỷ quyền người dùng:

from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

Tiếp theo, phương thức get_authenticated_services tạo một đối tượng FLOW bằng cách sử dụng dữ liệu từ tệp client_secrets.json đã định cấu hình ở bước trước. Nếu người dùng cho phép ứng dụng thay mặt người dùng gửi yêu cầu API, thì thông tin xác thực thu được sẽ được lưu trữ trong đối tượng Storage để sử dụng sau này. Người dùng cần uỷ quyền lại cho ứng dụng nếu thông tin đăng nhập hết hạn.

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)

Yêu cầu dịch vụ

Sau khi uỷ quyền thành công, chúng tôi có được các dịch vụ cần thiết cho các hoạt động mà chúng tôi muốn thực hiện. Mẫu này sử dụng YouTube Data API để tải video lên và sử dụng Content ID API của YouTube để tạo tài sản và xác nhận quyền sở hữu video. Chúng tôi tạo các dịch vụ riêng biệt để cấp quyền truy cập được phép vào chức năng của hai API này.

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)

Bước 2: Xác định chủ sở hữu nội dung

Để tạo tài sản và xác nhận quyền sở hữu, người dùng đã xác thực phải có tài khoản Trình quản lý nội dung trên YouTube. Tài khoản Trình quản lý nội dung là các đối tượng quản lý quyền của một hoặc nhiều chủ sở hữu nội dung. Chủ sở hữu nội dung là chủ bản quyền và có quyền quyết định kiếm tiền, theo dõi hoặc chặn video.

Phương thức get_content_owner truy xuất mã nhận dạng của chủ sở hữu nội dung trong tài khoản Trình quản lý nội dung của người dùng đã xác thực. Hầu hết các tài khoản đều có một chủ sở hữu nội dung duy nhất (người dùng đã xác thực), nhưng nếu tài khoản có nhiều chủ sở hữu nội dung, phương thức này sẽ trả về chủ sở hữu đầu tiên.

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("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"]

Bước 3: Tải video lên

Để tải video lên, chúng ta tạo một tài nguyên JSON một phần đại diện cho video và truyền video đó đến phương thức videos.insert. Chúng ta đặt siêu dữ liệu video bằng cách sử dụng các giá trị từ đối tượng options được tạo khi phân tích cú pháp dòng lệnh. Đối với chính tệp nội dung nghe nhìn, chúng ta sử dụng MediaFileUpload để có thể sử dụng tính năng tải lên tiếp nối. Hãy xem bài viết Tải video lên để biết thêm chi tiết.

Phương thức upload trả về mã video cho video mới, và tập lệnh cần truyền giá trị đó cho các phương thức khác ở các bước sau.

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)

Bước 4: Tạo thành phần

Để kiếm tiền từ video trên YouTube, trước tiên, bạn phải liên kết video đó với một tài sản. Phương thức create_asset sẽ tạo thành phần mới cho video mới tải lên.

Giống như đối với video, chúng tôi tạo một phần tài nguyên JSON giúp xác định loại tài sản cần tạo (video trên web) và cung cấp tiêu đề cũng như thông tin mô tả cho tài sản mới. Chúng ta truyền tài nguyên JSON đến phương thức assets.insert. Phương thức này sẽ tạo tài sản và trả về mã nhận dạng duy nhất của tài sản. Xin nhắc lại rằng tập lệnh cần truyền giá trị đó sang các phương thức khác ở các bước sau.

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"]

Bước 5: Cập nhật quyền sở hữu

Trước khi bạn có thể kiếm tiền từ video, YouTube phải biết ai sở hữu tài sản được liên kết. Bây giờ, với thành phần đã tạo, chúng ta sẽ định cấu hình ownership của thành phần đó. Trong mẫu, chúng tôi chỉ rõ rằng chủ sở hữu nội dung có quyền sở hữu tài sản đó trên toàn thế giới.

  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()

Bước 6: Xác nhận quyền sở hữu video

Bước tiếp theo là liên kết video đã tải lên với tài sản tương ứng bằng cách xác nhận quyền sở hữu video. Thông báo xác nhận quyền sở hữu cung cấp mối liên kết giữa video và hệ thống quản lý quyền của YouTube, qua đó thiết lập quyền sở hữu video và cho phép chủ sở hữu đặt chính sách kiếm tiền.

Phương thức claim_video xác nhận quyền sở hữu âm thanh và hình ảnh. Nếu bạn đưa tham số policyId vào dòng lệnh, phương thức này sẽ áp dụng chính sách đã chỉ định cho video; nếu bạn không đưa tham số này vào, phương thức này sẽ áp dụng chính sách "kiếm tiền" tiêu chuẩn.

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()

Bước 7: Đặt các lựa chọn quảng cáo

Chúng tôi đã xác nhận quyền sở hữu và áp dụng chính sách kiếm tiền cho video đó. Bước cuối cùng là chọn loại quảng cáo sẽ hiển thị trong video. Bất cứ khi nào áp dụng chính sách "kiếm tiền", YouTube sẽ kiểm tra các lựa chọn quảng cáo và hiển thị loại quảng cáo mang lại doanh thu cao nhất hiện có.

Mẫu này yêu cầu YouTube hiển thị quảng cáo TrueView trong luồng cùng với video này.

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()

Mã mẫu hoàn chỉnh

Dưới đây là mẫu hoạt động hoàn chỉnh upload_monetize_video_example.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Google Inc.
#
# 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:
  $ python 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:

  $ python upload_monetize_video_example.py --help
"""

__author__ = '[email protected] (Jeffrey Posnick)'

import 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.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from optparse import OptionParser


# 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 API 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 API 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!")