إرسال الطلب الأول

ملاحظة: إنّ واجهة برمجة تطبيقات Content ID في YouTube مخصّصة للاستخدام من قِبل شركاء المحتوى في YouTube، ولا يمكن لبعض المطوّرين أو جميع مستخدمي YouTube الوصول إليها. إذا لم تظهر لك واجهة برمجة التطبيقات YouTube Content ID API كإحدى الخدمات المدرَجة في وحدة تحكّم Google API، يمكنك الانتقال إلى مركز مساعدة YouTube للاطّلاع على مزيد من المعلومات حول "برنامج شركاء YouTube".

يشرح هذا الدليل التعليمي المفصّل كيفية إنشاء نص برمجي يتصل بخدمة ContentOwnersService ويسترجع معلومات عن مالك محتوى معيّن. يتم توفير نموذج رمز كامل في نهاية البرنامج التعليمي. على الرغم من أنّ هذا الرمز مكتوب بلغة Python، تتوفّر أيضًا مكتبات عملاء بلغات برمجة شائعة أخرى.

المتطلبات

إنشاء نص برمجي لإرسال طلبات البيانات من واجهة برمجة التطبيقات

توضّح الخطوات التالية كيفية إنشاء نص برمجي لإرسال طلب من واجهة برمجة التطبيقات Content ID في YouTube:

الخطوة 1: إنشاء النص البرمجي الأساسي

يقبل النص البرمجي التالي معلَمات سطر الأوامر التالية ويضبط القيم على متغيّر FLAGS العام:

  • المَعلمة content_owner_id مطلوبة وتحدِّد مالك محتوى CMS الذي يتم استرداد معلومات عنه.
  • تحدّد المَعلمة logging_level مستوى تفاصيل التسجيل للنص البرمجي.
  • تؤدي المَعلمة help إلى إخراج النص البرمجي لقائمة بالمَعلمات التي يفهمها.
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-

import gflags
import logging
import sys
import os

from datetime import *

# Define flags. The gflags module makes it easy to define command-line params
# for an application. Run this program with the '--help' argument to see all
# of the flags that it understands.
FLAGS = gflags.FLAGS
gflags.DEFINE_string('content_owner_id', None, ('Required flag. '
     'Identifies the content owner whose details are printed out.'))
gflags.MarkFlagAsRequired('content_owner_id')
gflags.DEFINE_enum('logging_level', 'ERROR',
    ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
    'Set the level of logging detail.')


def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)

  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))

if __name__ == '__main__':
  main(sys.argv)

الخطوة 2: تفعيل مصادقة المستخدم وتفويضه

في هذه الخطوة، سندمج تفويض OAuth 2.0 في النص البرمجي. يتيح ذلك للمستخدم الذي يشغّل النص البرمجي تفويض النص البرمجي لتنفيذ طلبات واجهة برمجة التطبيقات المنسوبة إلى حساب المستخدم.

الخطوة 2(أ): إنشاء ملف client_secrets.json

تتطلّب واجهة برمجة التطبيقات YouTube Content ID استخدام ملف client_secrets.json يحتوي على معلومات من وحدة تحكّم واجهة برمجة التطبيقات لإجراء المصادقة. يجب أيضًا تسجيل طلبك. للحصول على شرح أكثر شمولاً حول آلية عمل المصادقة، يمكنك الاطّلاع على دليل المصادقة.

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

الخطوة 2(ب): إضافة رمز المصادقة إلى النص البرمجي

لتفعيل مصادقة المستخدمين وتفويضهم، عليك إضافة عبارات import التالية:

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

بعد ذلك، سننشئ كائن FLOW باستخدام أسرار العميل التي تم ضبطها في الخطوة 2 (أ). إذا فوّض المستخدم تطبيقنا بإرسال طلبات من واجهة برمجة التطبيقات نيابةً عن المستخدم، يتم تخزين بيانات الاعتماد الناتجة في عنصر Storage لاستخدامها لاحقًا. على المستخدم إعادة تفويض تطبيقنا إذا انتهت صلاحية بيانات الاعتماد.

أضِف الرمز التالي إلى نهاية الدالة main:

  # Set up a Flow object to be used if we need to authenticate.
  FLOW = flow_from_clientsecrets('client_secrets.json',
      scope='https://www.googleapis.com/auth/youtubepartner',
      message='error message')

  # The Storage object stores the credentials. If it doesn't exist, or if
  # the credentials are invalid or expired, run through the native client flow.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()
  
  if (credentials is None or credentials.invalid or
      credentials.token_expiry <= datetime.now()):
    credentials = run(FLOW, storage)

الخطوة 2 (ج): إنشاء عنصر httplib2 وإرفاق بيانات الاعتماد

بعد أن يفوّض المستخدم النص البرمجي، ننشئ عنصر httplib2.Http يعالج طلبات البيانات من واجهة برمجة التطبيقات، ثم نرفق بيانات اعتماد التفويض بذلك العنصر.

أضِف بيان الاستيراد التالي:

  import httplib2

ونضيف هذا الرمز إلى نهاية الدالة main:

  # Create httplib2.Http object to handle HTTP requests and
  # attach auth credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

الخطوة 3: الحصول على خدمة

تعمل دالة build في مكتبة عملاء Python على إنشاء مورد يمكنه التفاعل مع واجهة برمجة التطبيقات. بعد أن يمنح المستخدم تطبيقنا الإذن، ننشئ عنصر service الذي يقدّم طُرقًا للتفاعل مع ContentOwnerService.

أضف عبارة الاستيراد التالية:

from apiclient.discovery import build

وأضف هذا الرمز في نهاية الدالة main:

  service = build("youtubePartner", "v1", http=http, static_discovery=False)
  contentOwnersService = service.contentOwners()

الخطوة 4: تنفيذ طلب بيانات من واجهة برمجة التطبيقات

والآن، سننشئ طلب خدمة وننفذه. ينشئ الرمز التالي طلب contentOwnersService.get() وينفّذه، والذي يسترد معلومات حول مالك المحتوى المحدّد.

أضِف هذا الرمز في نهاية الدالة main:

  # Create and execute get request.
  request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id)
  content_owner_doc = request.execute(http)
  print ('Content owner details: id: %s, name: %s, '
         'notification email: %s') % (
              content_owner_doc['id'], content_owner_doc['displayName'],
              content_owner_doc['disputeNotificationEmails'])

إكمال الطلب

يعرض هذا القسم التطبيق الكامل مع بعض معلومات الترخيص والتعليقات الإضافية في النص البرمجي. هناك طريقتان لتشغيل البرنامج:

  • يُطلق هذا الأمر نافذة متصفّح يمكنك من خلالها المصادقة، إذا لزم الأمر، وتفويض التطبيق لإرسال طلبات واجهة برمجة التطبيقات. إذا فوّضت التطبيق، سيتم ترحيل بيانات الاعتماد تلقائيًا إلى النص البرمجي.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.

    ملاحظة: يمكنك العثور على القيمة CONTENT_OWNER_ID لحسابك في صفحة إعدادات الحساب في حساب نظام إدارة المحتوى (CMS). يتم إدراج القيمة على أنّها Partner Code في قسم معلومات الحساب في تلك الصفحة.

  • يعرض هذا الأمر عنوان URL يمكنك فتحه في متصفّح، ويطلب منك أيضًا إدخال رمز التفويض. عند الانتقال إلى عنوان URL، تتيح لك هذه الصفحة تفويض التطبيق لإرسال طلبات من واجهة برمجة التطبيقات نيابةً عنك. إذا منحت هذا الإذن، ستعرض الصفحة رمز التفويض الذي تحتاج إلى إدخاله عند ظهور الطلب لإكمال عملية منح الإذن.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.

    ملاحظة: تتعرّف وحدة oauth2client على المَعلمة noauth_local_webserver حتى لو لم يتم ذكر المَعلمة في النص البرمجي.

client_secrets.json

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

yt_partner_api.py

#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# 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 Content ID API.

Command-line application that retrieves the information
about given content owner.

Usage:
  $ python yt_partner_api.py --content_owner_id=[contentOwnerId]
  $ python yt_partner_api.py --content_owner_id=[contentOwnerId] --noauth_local_webserver

You can also get help on all the command-line flags the program understands
by running:

  $ python yt_partner_api.py --help

To get detailed log output run:

  $ python yt_partner_api.py --logging_level=DEBUG \
    --content_owner_id=[contentOwnerId]
"""

import gflags
import httplib2
import logging
import sys
import os

from datetime import *
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

# Define flags. The gflags module makes it easy to define command-line options
# for an application. Run this program with the '--help' argument to see all
# of the flags that it understands.
FLAGS = gflags.FLAGS
gflags.DEFINE_string('content_owner_id', None, ('Required flag. '
     'Identifies the content owner id whose details are printed out.'))
gflags.MarkFlagAsRequired('content_owner_id')
gflags.DEFINE_enum('logging_level', 'ERROR',
    ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
    'Set the level of logging detail.')

  
def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)
  
  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
  
  # Set up a Flow object to be used if we need to authenticate.
  FLOW = flow_from_clientsecrets('client_secrets.json',
      scope='https://www.googleapis.com/auth/youtubepartner',
      message='error message')

  # The Storage object stores the credentials. If the credentials are invalid
  # or expired and the script isn't working, delete the file specified below
  # and run the script again.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()

  if (credentials is None or credentials.invalid or
      credentials.token_expiry <= datetime.now()):
    credentials = run(FLOW, storage)

  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("youtubePartner", "v1", http=http)
  contentOwnersService = service.contentOwners()

  # Create and execute get request.
  request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id)
  content_owner_doc = request.execute(http)
  print ('Content owner details: id: %s, name: %s, '
         'notification email: %s') % (
              content_owner_doc['id'], content_owner_doc['displayName'],
              content_owner_doc['disputeNotificationEmails'])

if __name__ == '__main__':
  main(sys.argv)