동영상 업로드 및 소유권 주장

참고: YouTube Content ID API는 YouTube 콘텐츠 파트너가 사용하도록 설계되었으며 일부 개발자나 YouTube 사용자는 액세스할 수 없습니다. Google API 콘솔에 나열된 서비스 중 하나로 YouTube Content ID API가 표시되지 않으면 YouTube 고객센터에서 YouTube 파트너 프로그램에 대해 자세히 알아보세요.

이 코드 샘플은 YouTube 동영상을 업로드하고 동영상에 수익 창출 정책을 적용하는 방법을 보여줍니다. 동영상으로 수익을 창출하려면 YouTube 권한 관리 시스템에서 asset를 사용해 동영상에 대한 소유권을 주장해야 합니다. 샘플은 동영상을 업로드하고 새 저작물을 만들며 이 저작물을 통해 동영상에 대한 소유권을 주장하고 동영상에 수익 창출 정책을 적용합니다.

이 예는 코드의 관련 섹션과 관련된 일련의 단계로 표시됩니다. 이 페이지의 끝에서 전체 스크립트를 확인할 수 있습니다. 코드는 Python으로 작성됩니다. 기타 많이 사용되는 프로그래밍 언어의 클라이언트 라이브러리도 제공됩니다.

요구사항

1단계: 일반적인 관리 기능

코드 샘플의 첫 번째 섹션에서는 많은 스크립트에 공통으로 사용되는 기본 관리 기능(명령줄 파싱, 사용자 인증 및 필요한 API 서비스 가져오기)을 수행합니다.

명령줄 파싱

parse_options 메서드는 Python 클라이언트 라이브러리의 OptionParser를 사용하여 각 명령줄 인수를 속성으로 포함하는 options 객체를 만듭니다. 필요에 따라 후속 메서드는 options 객체에서 값을 검색합니다.

샘플 스크립트의 명령줄 인수는 다음과 같습니다. 처음 2개 (file, channelId)는 필수이고 나머지는 선택사항입니다.

  • file: 업로드할 동영상 파일의 이름 및 위치입니다.

    Example: --file="/home/path/to/file.mov"
  • channelId: 동영상을 업로드할 YouTube 채널입니다. 채널은 인증된 사용자의 YouTube 콘텐츠 관리자 계정에서 관리해야 합니다. 인증된 사용자의 YouTube 계정 설정에서 또는 channels.list 메서드를 사용하여 채널 ID를 검색할 수 있습니다.

    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 동영상 카테고리의 카테고리 ID입니다. 기본값은 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 = 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

요청 승인

이 단계에서는 OAuth 2.0 승인을 스크립트에 통합합니다. 그러면 사용자가 스크립트를 실행하여 사용자의 계정에 따른 API 요청을 수행하도록 스크립트를 인증할 수 있습니다.

client_secrets.json 파일 만들기

샘플에 표시된 승인 유형의 경우 승인을 수행하려면 Google API 콘솔의 정보가 포함된 client_secrets.json 파일이 필요합니다. 또한 애플리케이션을 등록해야 합니다. 승인 방식에 대한 자세한 설명은 승인 가이드를 참조하세요. 이 샘플을 사용하려면 프로젝트의 API 콘솔에서 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 객체를 만듭니다. 애플리케이션이 사용자를 대신하여 API 요청을 제출하도록 사용자가 승인하면 이에 따른 사용자 인증 정보는 나중에 사용할 수 있도록 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를 사용하여 저작물을 만들고 동영상의 소유권을 주장합니다. Google은 두 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)

2단계: 콘텐츠 소유자 확인

저작물을 만들고 소유권을 주장하려면 인증된 사용자에게 YouTube 콘텐츠 관리자 계정이 있어야 합니다. 콘텐츠 관리자 계정은 1명 이상의 콘텐츠 소유자에 대한 권한 관리 객체를 보유합니다. 콘텐츠 소유자는 동영상의 수익 창출, 추적 또는 차단 여부를 결정할 수 있는 저작권 소유자입니다.

get_content_owner 메서드는 인증된 사용자의 콘텐츠 관리자 계정에서 콘텐츠 소유자의 ID를 가져옵니다. 대부분의 계정에는 단일 콘텐츠 소유자(인증된 사용자)가 있지만 계정에 여러 명의 콘텐츠 소유자가 있는 경우 메소드가 첫 번째 콘텐츠 소유자의 를 반환합니다.

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

3단계: 동영상 업로드

동영상을 업로드하기 위해 동영상을 나타내는 부분 JSON 리소스를 빌드하여 videos.insert 메서드에 전달합니다. 명령줄을 파싱할 때 만든 options 객체의 값을 사용하여 동영상 메타데이터를 설정합니다. 미디어 파일 자체의 경우 재개 가능한 업로드를 사용할 수 있도록 MediaFileUpload를 사용합니다. 자세한 내용은 동영상 업로드를 참조하세요.

upload 메서드는 새 동영상의 동영상 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)

4단계: 확장 소재 만들기

YouTube 동영상으로 수익을 창출하려면 먼저 동영상을 저작물에 연결해야 합니다. create_asset 메서드는 새로 업로드한 동영상의 새 애셋을 만듭니다.

동영상에서와 마찬가지로 생성할 저작물의 유형 (웹 동영상)을 식별하는 부분 JSON 리소스를 빌드하고 새 저작물의 제목과 설명을 제공합니다. 저작물을 만들고 고유 ID를 반환하는 assets.insert 메서드에 JSON 리소스를 전달합니다. 이번에도 스크립트는 이후 단계에서 다른 메서드에 해당 값을 전달해야 합니다.

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

5단계: 소유권 업데이트

동영상으로 수익을 창출하려면 먼저 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()

6단계: 동영상 소유권 주장

다음 단계는 동영상의 소유권을 주장하여 업로드한 동영상을 해당 저작물과 연결하는 것입니다. 소유권을 주장하면 동영상의 소유권을 결정하고 소유자가 수익 창출 정책을 설정하도록 하는 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()

7단계: 광고 옵션 설정

동영상에 대한 소유권을 주장하고 동영상에 수익 창출 정책을 적용했습니다. 마지막 단계는 동영상에 표시할 광고 유형을 지정하는 것입니다. '수익 창출' 정책을 적용할 때마다 YouTube는 광고 옵션을 확인하고 사용할 수 있는 광고 유형 중 가장 수익이 높은 유형을 표시합니다.

샘플은 이 동영상과 함께 인스트림 TrueView 광고를 표시하도록 YouTube에 지시합니다.

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/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!")