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

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

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

المتطلّبات

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

توضّح الخطوات التالية كيفية إنشاء نص برمجي لإرسال طلب عبر واجهة برمجة تطبيقات 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

تتطلّب واجهة برمجة التطبيقات Content ID في YouTube استخدام ملف 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 لحسابك في صفحة إعدادات الحساب ضمن حسابك في نظام إدارة المحتوى. وتظهر القيمة على أنها 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)