YouTube Reporting API - Data Model

مهم: گزارش‌های API روزانه و گزارش‌های تکمیلی به مدت 60 روز از زمان تولید در دسترس هستند. گزارش های داده های تاریخی به مدت 30 روز از زمان تولید در دسترس هستند.

این خط مشی در سطح جهانی برای همه گزارش ها و مشاغل گزارش دهی اعمال می شود. برای جزئیات کامل، به سابقه بازبینی YouTube Reporting API مراجعه کنید.

YouTube Reporting API از گزارش‌های از پیش تعریف‌شده‌ای پشتیبانی می‌کند که حاوی مجموعه‌ای جامع از داده‌های YouTube Analytics برای یک کانال یا مالک محتوا است. این گزارش‌ها به شما امکان می‌دهد مجموعه‌های داده انبوهی را که می‌توانید با YouTube Analytics API یا در بخش Analytics در استودیوی سازندگان جستجو کنید، دانلود کنید.

API همچنین از مجموعه‌ای از گزارش‌های مدیریت‌شده توسط سیستم تولید شده به‌طور خودکار پشتیبانی می‌کند که در دسترس دارندگان محتوایی است که به گزارش‌های مربوطه در منوی گزارش‌ها دسترسی دارند. این گزارش‌ها حاوی داده‌های درآمد تبلیغات و داده‌های درآمد اشتراک YouTube Premium هستند. برای اطلاعات بیشتر به مستندات گزارش های مدیریت شده توسط سیستم مراجعه کنید.

بررسی اجمالی

فیلدهای گزارش در این گزارش ها به عنوان ابعاد یا معیارها مشخص می شوند:

  • ابعاد معیارهای رایجی هستند که برای جمع‌آوری داده‌ها استفاده می‌شوند، مانند تاریخی که یک اقدام در آن رخ داده یا کشوری که کاربران در آن قرار داشتند. در یک گزارش، هر ردیف از داده ها دارای ترکیبی منحصر به فرد از مقادیر ابعاد است.
  • معیارها اندازه گیری های فردی مربوط به فعالیت کاربر، عملکرد تبلیغات یا درآمد تخمینی هستند. معیارهای فعالیت کاربر شامل مواردی مانند تعداد بازدید و رتبه بندی ویدیو (پسندیدن و نپسندیدن) است.

به عنوان مثال، گزارش فعالیت اصلی کاربر برای کانال ها شامل ابعاد زیر است:

  • روز : تاریخی که در آن فعالیت انجام شده است.
  • کانال : کانال YouTube مرتبط با فعالیت.
  • ویدیو : ویدیوی YouTube مرتبط با فعالیت.
  • liveOrOnDemand : مقداری که نشان می‌دهد آیا بینندگان در حال تماشای جریان ویدیویی زنده هستند یا خیر.
  • subscribedStatus : مقداری که نشان می دهد بینندگان در کانال مشترک شده اند یا خیر.
  • کشور : کشوری که بینندگان در آن قرار داشتند.

این گزارش همچنین حاوی معیارهای زیادی است، مانند بازدیدها ، پسندیدن‌ها و میانگین مدت زمان مشاهده . پس از بازیابی و وارد کردن گزارش، یک برنامه کاربردی می تواند محاسبات مختلفی را بر اساس مقادیر ابعاد مشترک انجام دهد.

به عنوان مثال، برای محاسبه تعداد کل بازدیدها در آلمان در یک تاریخ خاص، مقادیر متریک بازدیدها را برای همه ردیف‌هایی که مقدار ستون کشور DE و مقدار ستون روز تاریخ در قالب YYYY-MM-DD است، جمع کنید.

بازیابی گزارش های YouTube Analytics

مراحل زیر نحوه بازیابی گزارش‌های مالک کانال و محتوا از طریق API را توضیح می‌دهد. برای دستورالعمل‌هایی درباره نحوه بازیابی آن گزارش‌ها، به مستندات گزارش‌های مدیریت‌شده توسط سیستم مراجعه کنید.

مرحله 1: اعتبارنامه مجوز را بازیابی کنید

همه درخواست‌های YouTube Reporting API باید مجاز باشند. راهنمای مجوز نحوه استفاده از پروتکل OAuth 2.0 برای بازیابی نشانه های مجوز را توضیح می دهد.

درخواست‌های YouTube Reporting API از حوزه‌های مجوز زیر استفاده می‌کنند:

محدوده ها
https://www.googleapis.com/auth/yt-analytics.readonly گزارش‌های YouTube Analytics را برای محتوای YouTube خود مشاهده کنید. این محدوده دسترسی به معیارهای فعالیت کاربر مانند تعداد بازدید و تعداد رتبه‌بندی را فراهم می‌کند.
https://www.googleapis.com/auth/yt-analytics-monetary.readonly گزارش های پولی YouTube Analytics را برای محتوای YouTube خود مشاهده کنید. این محدوده دسترسی به معیارهای فعالیت کاربر و معیارهای درآمد تخمینی و عملکرد تبلیغات را فراهم می کند.

مرحله 2: گزارش مورد نظر را برای بازیابی شناسایی کنید

با روش reportTypes.list API تماس بگیرید تا فهرستی از گزارش‌هایی را که می‌توان برای صاحب کانال یا محتوا ایجاد کرد، بازیابی کنید. این روش فهرستی از شناسه‌ها و نام‌های گزارش را برمی‌گرداند. مقدار ویژگی id را برای گزارش هایی که می خواهید ایجاد کنید، بگیرید. به عنوان مثال، شناسه گزارش اصلی فعالیت کاربر برای کانال ها channel_basic_a1 است.

همچنین می‌توانید نام گزارش‌ها را در اسنادی که گزارش‌های کانال پشتیبانی شده و گزارش‌های مالک محتوا را تعریف می‌کنند، بیابید.

مرحله 3: یک کار گزارش دهی ایجاد کنید

تا زمانی که یک کار گزارش برای آن گزارش ایجاد نکنید، YouTube شروع به تولید گزارش شما نمی کند. (به این ترتیب، گزارش‌ها فقط برای کانال‌ها و صاحبان محتوایی تولید می‌شوند که واقعاً می‌خواهند آنها را بازیابی کنند.)

برای ایجاد یک کار گزارش دهی، با متد jobs.create API تماس بگیرید. مقادیر زیر را در بدنه درخواست تنظیم کنید:

  • مقدار ویژگی reportTypeId را روی شناسه گزارشی که در مرحله 2 بازیابی کردید، تنظیم کنید.
  • مقدار ویژگی name را روی نامی که می‌خواهید با گزارش مرتبط کنید، تنظیم کنید.

پاسخ API به متد jobs.create حاوی یک منبع Job است که ID مشخص می کند که به طور منحصر به فرد کار را شناسایی می کند. می‌توانید ظرف 48 ساعت از زمان ایجاد کار شروع به بازیابی گزارش کنید و اولین گزارش موجود برای روزی است که کار را برنامه‌ریزی کرده‌اید.

به عنوان مثال، اگر یک کار را در 1 سپتامبر برنامه ریزی کنید، گزارش 1 سپتامبر در 3 سپتامبر آماده می شود. گزارش 2 سپتامبر در 4 سپتامبر ارسال می شود و غیره.

مرحله 4: شناسه شغلی را بازیابی کنید

توجه: اگر برنامه شما شناسه شغلی بازگردانده شده در مرحله 3 را ذخیره کرده است، می توانید از این مرحله رد شوید.

برای بازیابی لیستی از کارهای برنامه ریزی شده، متد jobs.list را فراخوانی کنید. ویژگی reportTypeId در هر منبع Job برگشتی، نوع گزارشی را که آن شغل ایجاد می کند، مشخص می کند. برنامه شما به مقدار ویژگی id از همان منبع در مرحله زیر نیاز دارد.

مرحله 5: URL دانلود گزارش را بازیابی کنید

روش jobs.reports.list را برای بازیابی لیستی از گزارش‌های ایجاد شده برای کار فراخوانی کنید. در درخواست، پارامتر jobId را روی شناسه شغلی گزارشی که می خواهید بازیابی کنید، تنظیم کنید.

نکته: از پارامتر createdAfter استفاده کنید تا نشان دهید که API فقط باید گزارش‌های ایجاد شده را پس از یک زمان مشخص بازگرداند. از این پارامتر می‌توان برای اطمینان از اینکه API فقط گزارش‌هایی را که قبلاً پردازش نکرده‌اید برمی‌گرداند استفاده کرد.

پاسخ API حاوی لیستی از منابع Report برای آن کار است. هر منبع به گزارشی اشاره دارد که حاوی داده هایی برای یک دوره 24 ساعته منحصر به فرد است. توجه داشته باشید که YouTube برای روزهایی که هیچ داده‌ای در دسترس نبود، گزارش‌های قابل دانلود تولید می‌کند. این گزارش ها حاوی یک ردیف سرصفحه هستند اما حاوی داده های اضافی نیستند.

  • ویژگی های startTime و endTime منبع، دوره زمانی را که داده های گزارش پوشش می دهد، مشخص می کند.
  • ویژگی downloadUrl منبع، نشانی اینترنتی را که می توان گزارش را از آن دریافت کرد، مشخص می کند.
  • ویژگی createTime منبع، تاریخ و زمان تولید گزارش را مشخص می کند. برنامه شما باید این مقدار را ذخیره کند و از آن برای تعیین اینکه آیا گزارش های دانلود شده قبلی تغییر کرده است یا خیر استفاده کند.

مرحله 6: گزارش را دانلود کنید

برای بازیابی گزارش، یک درخواست HTTP GET را به downloadUrl به دست آمده در مرحله 5 ارسال کنید.

با فعال کردن فشرده‌سازی gzip در درخواست‌های دانلود، می‌توانید پهنای باند مورد نیاز برای دانلود گزارش‌ها را کاهش دهید. در حالی که برنامه شما برای فشرده سازی پاسخ های API به زمان CPU اضافی نیاز دارد، مزایای مصرف کمتر منابع شبکه معمولاً بیشتر از این هزینه است.

برای دریافت پاسخ کدگذاری شده با gzip، هدر درخواست HTTP Accept-Encoding همانطور که در مثال زیر نشان داده شده است، روی gzip تنظیم کنید:

Accept-Encoding: gzip

پردازش گزارش ها

بهترین شیوه ها

برنامه‌هایی که از YouTube Reporting API استفاده می‌کنند باید همیشه از این روش‌ها پیروی کنند:

  • از ردیف سرصفحه گزارش برای تعیین ترتیب ستون های گزارش استفاده کنید. برای مثال، تصور نکنید که بازدیدها اولین معیاری هستند که در یک گزارش بازگردانده می‌شوند، فقط به این دلیل که اولین معیار ذکر شده در توضیحات گزارش است. در عوض، از ردیف سرصفحه گزارش برای تعیین اینکه کدام ستون حاوی آن داده است استفاده کنید.

  • گزارش هایی را که دانلود کرده اید ثبت کنید تا از پردازش مکرر همان گزارش جلوگیری کنید. لیست زیر چند راه را برای انجام این کار پیشنهاد می کند.

    • هنگام فراخوانی متد reports.list ، از پارامتر createAfter استفاده کنید تا فقط گزارش های ایجاد شده پس از یک تاریخ مشخص را بازیابی کنید. (در اولین باری که گزارش ها را بازیابی می کنید، پارامتر createdAfter را حذف کنید.)

      هر بار که گزارش‌ها را بازیابی می‌کنید و با موفقیت پردازش می‌کنید، مهر زمانی مربوط به تاریخ و زمانی که جدیدترین گزارش ایجاد شده است را ذخیره کنید. سپس، مقدار پارامتر createdAfter را در هر فراخوانی متوالی به روش reports.list به‌روزرسانی کنید تا اطمینان حاصل کنید که هر بار که با API تماس می‌گیرید، فقط گزارش‌های جدید، از جمله گزارش‌های جدید با داده‌های پرشده را بازیابی می‌کنید.

      به عنوان حفاظت، قبل از بازیابی گزارش، همچنین بررسی کنید که شناسه گزارش قبلاً در پایگاه داده شما فهرست نشده باشد.

    • شناسه هر گزارشی را که دانلود و پردازش کرده اید ذخیره کنید. همچنین می‌توانید اطلاعات اضافی مانند تاریخ و زمان ایجاد هر گزارش یا startTime و endTime گزارش را ذخیره کنید، که با هم دوره‌ای را که گزارش حاوی داده است، مشخص می‌کند. توجه داشته باشید که هر شغل احتمالاً گزارش های زیادی خواهد داشت زیرا هر گزارش حاوی داده هایی برای یک دوره 24 ساعته است.

      از شناسه گزارش برای شناسایی گزارش هایی که هنوز باید دانلود و وارد کنید استفاده کنید. با این حال، اگر دو گزارش جدید دارای مقادیر startTime و endTime یکسان هستند، گزارش را فقط با مقدار createTime جدیدتر وارد کنید.

  • گزارش‌ها حاوی شناسه‌های مرتبط با منابع YouTube هستند و می‌توانید از YouTube Data API برای بازیابی فراداده‌های اضافی برای آن منابع استفاده کنید. همانطور که در خط‌مشی‌های توسعه‌دهنده سرویس‌های YouTube API (بخش‌های III.E.4.b تا III.E.4.d) ذکر شده است، مشتریان API باید پس از 30 روز ابرداده‌های منبع ذخیره‌شده را از آن API حذف یا تازه‌سازی کنند.

گزارش مشخصات

گزارش‌های API فایل‌های .csv (مقادیر جدا شده با کاما) نسخه‌بندی‌شده هستند که ویژگی‌های زیر را دارند:

  • هر گزارش حاوی داده هایی برای یک دوره 24 ساعته منحصر به فرد است که از ساعت 12:00 صبح تا 11:59 بعد از ظهر به وقت اقیانوس آرام ادامه دارد. به این ترتیب، در هر گزارش داده شده، مقدار بعد روز همیشه یکسان است.

  • گزارش ها روزانه به روز می شوند.

  • یوتیوب برای روزهایی که هیچ داده ای در دسترس نبود، گزارش های قابل بارگیری تولید می کند. این گزارش ها حاوی یک ردیف سرصفحه خواهند بود اما حاوی داده های اضافی نیستند.

  • گزارش‌های API به‌مدت 60 روز از زمان تولید در دسترس هستند، به استثنای داده‌های تاریخی تولید شده برای مشاغل گزارش‌دهی جدید. گزارش ها پس از گذشت بیش از 60 روز از دسترس خارج می شوند. که در حال حاضر بیش از 60 روز از عمر آنها می گذرد.
  • گزارش‌های حاوی داده‌های تاریخی به مدت 30 روز از زمان تولید در دسترس هستند. گزارش‌هایی که حاوی داده‌های تاریخی هستند، پس از گذشت بیش از 30 روز، قابل دسترس نیستند.
  • داده های گزارش فیلتر نمی شوند. به این ترتیب، گزارش کانال شامل تمام داده‌های ویدیوها یا فهرست‌های پخش یک کانال است، به استثنای ذکر شده در پاراگراف زیر مربوط به منابع حذف‌شده. به طور مشابه، گزارش مالک محتوا شامل تمام داده‌های کانال‌های مالک محتوا (ویدئوها، فهرست‌های پخش، عملکرد تبلیغات و غیره) به استثنای زیر است.

    اگرچه داده‌های گزارش فیلتر نمی‌شوند، اما گزارش‌ها حاوی هیچ ارجاعی به منابع YouTube نیستند که حداقل 30 روز قبل از تاریخ تولید گزارش حذف شده‌اند.

  • داده های گزارش مرتب نشده اند.

  • گزارش‌ها ردیف‌هایی را که معیار ندارند حذف می‌کنند. به عبارت دیگر، ردیف هایی که هیچ معیاری ندارند از گزارش حذف می شوند. برای مثال، اگر ویدیویی در یک روز خاص در آلبانی هیچ بازدیدی نداشته باشد، گزارش آن روز حاوی ردیف‌هایی برای آلبانی نخواهد بود.

  • گزارش‌ها حاوی ردیف‌هایی نیستند که داده‌های خلاصه‌ای را برای معیارها ارائه کنند، مانند تعداد کل بازدیدها برای همه ویدیوهای یک کانال. می‌توانید مجموع مقادیر را به‌عنوان مجموع مقادیر در گزارش محاسبه کنید، اما این مجموع ممکن است شامل معیارهایی برای ویدیوهای حذف‌شده نباشد، همانطور که در بالا ذکر شد. همچنین می‌توانید از YouTube Analytics API برای بازیابی تعداد کل استفاده کنید. API YouTube Analytics مجموع مقادیر را برمی‌گرداند که شامل معیارهایی برای منابع حذف شده است، حتی اگر آن منابع به صراحت در پاسخ‌های API ارجاع داده نشده باشند.

پر کردن داده ها

داده های Backfill به مجموعه داده ای اشاره دارد که جایگزین مجموعه ای که قبلا تحویل داده شده است. هنگامی که یک گزارش داده پرشده در دسترس است، برنامه شما باید گزارش جدید را بازیابی کند و داده های ذخیره شده شما را برای مطابقت با مجموعه داده های اصلاح شده به روز کند. برای مثال، برنامه شما می‌تواند داده‌های قبلی را برای دوره زمانی تحت پوشش گزارش حذف کند و سپس مجموعه داده‌های جدید را وارد کند.

اگر YouTube داده‌های تکمیلی داشته باشد، گزارش جدیدی با شناسه گزارش جدید ایجاد می‌کند. در این صورت، مقادیر ویژگی startTime و endTime گزارش با زمان شروع و پایان گزارشی که قبلاً در دسترس بوده و ممکن است قبلاً دانلود کرده باشید مطابقت دارد.

گزارش‌های تکمیلی حاوی هیچ ارجاعی به منابع YouTube نیست که حداقل 30 روز قبل از تاریخ تولید گزارش حذف شده‌اند.

داده های تاریخی

وقتی یک کار گزارش‌دهی جدید را برنامه‌ریزی می‌کنید، YouTube از آن روز به بعد گزارش‌های تاریخی تولید می‌کند و گزارش‌هایی را تولید می‌کند که دوره 30 روزه قبل از زمانی که کار را ایجاد کرده‌اید را پوشش می‌دهد. بنابراین، در این مستندات، داده های تاریخی به گزارشی اطلاق می شود که حاوی داده هایی برای یک دوره زمانی قبل از برنامه ریزی کار گزارش است.

گزارش های تاریخی به محض در دسترس قرار گرفتن پست می شوند. به طور معمول، تمام داده های تاریخی برای یک شغل در عرض چند روز ارسال می شود. همانطور که در بخش ویژگی های گزارش توضیح داده شد، گزارش های حاوی داده های تاریخی به مدت 30 روز از زمان تولید در دسترس هستند. گزارش هایی که حاوی داده های غیر تاریخی هستند به مدت 60 روز در دسترس هستند.

ناشناس سازی داده ها

برای اطمینان از ناشناس ماندن بینندگان YouTube، مقادیر برای برخی از ابعاد تنها در صورتی برگردانده می‌شوند که معیاری در همان ردیف به آستانه خاصی برسد.

برای مثال، در گزارش منبع ترافیک ویدیویی برای کانال‌ها، هر ردیف شامل تعدادی ابعاد، از جمله trafficSourceType و trafficSourceDetail است. هر ردیف همچنین دارای معیارهای مختلفی از جمله نماها است. در ردیف‌هایی که ترافیک ناشی از جستجوی YouTube را توصیف می‌کنند، بعد trafficSourceDetail عبارت جستجویی را که منجر به ترافیک شده است، مشخص می‌کند.

در این مثال، قوانین زیر اعمال می شود:

  • گزارش منبع ترافیک، عبارت جستجو ( trafficSourceDetail ) را تنها در صورتی شناسایی می‌کند که منجر به حداقل تعداد معینی بازدید از یک ویدیوی خاص در یک روز خاص شود. در این مورد، بازدیدها معیار، ویدیو بعد جمع‌آوری و ترافیکSourceDetail بعد ناشناس است.

  • این گزارش شامل یک ردیف اضافی است که سنجه‌ها را برای همه مقادیر trafficSourceDetail که آستانه تعداد بازدید را برآورده نمی‌کنند، جمع‌آوری می‌کند. آن ردیف تعداد کل بازدیدهای مرتبط با آن عبارات پرس و جو را گزارش می دهد اما خود اصطلاحات را مشخص نمی کند.

جداول زیر این قوانین را نشان می دهد. جدول اول شامل مجموعه ای فرضی از داده های خام است که YouTube از آنها برای تولید گزارش منبع ترافیک استفاده می کند و جدول دوم شامل خود گزارش است. در این مثال، آستانه تعداد بازدید 10 است، به این معنی که گزارش فقط در صورتی یک عبارت جستجو را شناسایی می‌کند که منجر به حداقل 10 بازدید از یک ویدیوی خاص در یک روز خاص شود. (آستانه های واقعی ممکن است تغییر کنند.)

داده‌های خام ترافیک جستجوی YouTube برای یک ویدیو

فرض کنید داده های زیر ترافیک جستجوی YouTube را به یک ویدیوی خاص در یک روز خاص توصیف می کند.

عبارت جستجو دیدگاه ها دقایق تخمینی تماشا
سبک گانگنام 100 200
روانی 15 25
psy gangnam 9 15
اوپا گنگنام 5 8
رقص اسب سواری 2 5

نمونه گزارش منبع ترافیک

جدول زیر گزیده ای از گزارش منبع ترافیک را نشان می دهد که YouTube برای داده های خام در بخش قبل ایجاد می کند. (گزارش واقعی شامل ابعاد و معیارهای بیشتری خواهد بود.) در این مثال، گزارش فقط در صورتی عبارات جستجو را شناسایی می کند که حداقل به 10 بازدید منجر شود. آستانه های واقعی در معرض تغییر هستند.

در سطر سوم گزارش، مقدار بعد trafficSourceDetail NULL است. views و معیارهای estimatedMinutesWatched شامل بازدیدها و دقیقه‌های تماشا شده برای سه عبارت جستجو شده است که کمتر از 10 بازدید ایجاد کرده‌اند.

TrafficSourceDetail دیدگاه ها تخمین زده شده Minutes Watched
سبک گانگنام 100 200
روانی 15 25
خالی 16 28

ابعاد مشمول ناشناس شدن هستند

جدول زیر مقادیر ابعادی را مشخص می‌کند که اگر مقادیر متریک مرتبط با آستانه مشخصی نرسند، ناشناس می‌شوند. در هر مورد، مقدار متریک در بعد دیگری جمع می‌شود. به‌عنوان مثال، اگر معیار، بازدیدها و بعد جمع‌آوری ویدیو باشد، مقدار بعد بی‌نام می‌شود، مگر اینکه ویدیو چند بار مشاهده شده باشد.

متریک بعد (های) جمع آوری بعد ناشناس ارزش ناشناس
مشترکین به دست آمده کانال کشور ZZ
مشترکین به دست آمده کانال استان US-ZZ
مشترکین گم شده کانال کشور ZZ
مشترکین گم شده کانال استان US-ZZ
نظرات ویدئو کشور ZZ
نظرات ویدئو استان US-ZZ
دوست دارد ویدئو کشور ZZ
دوست دارد ویدئو استان US-ZZ
دوست ندارد ویدئو کشور ZZ
دوست ندارد ویدئو استان US-ZZ
دیدگاه ها ویدئو گروه سنی NULL
دیدگاه ها ویدئو جنسیت NULL
دیدگاه ها ویدئو و ترافیکSourceDetail TrafficSourceDetail NULL
تعداد مشترکین کانال کانال وضعیت مشترک NULL

نمونه کد

نمونه کد زیر نحوه استفاده از API برای ایجاد یک کار گزارش دهی و سپس بازیابی گزارش برای آن کار را نشان می دهد. دو نمونه کد برای هر زبان ارائه شده است:

  1. اولین نمونه کد نحوه بازیابی لیستی از انواع گزارش های موجود و سپس ایجاد یک کار گزارش جدید را نشان می دهد.

  2. نمونه کد دوم نحوه بازیابی گزارش برای یک کار خاص را نشان می دهد. شما می توانید در عرض 48 ساعت از زمان ایجاد کار شروع به بازیابی گزارش کنید.

توجه: نمونه کد زیر ممکن است نشان دهنده همه زبان های برنامه نویسی پشتیبانی شده نباشد. برای فهرستی از زبان های پشتیبانی شده، به مستندات کتابخانه های سرویس گیرنده مراجعه کنید.

جاوا

نمونه های زیر از کتابخانه سرویس گیرنده جاوا استفاده می کنند:

مثال 1: یک کار گزارش دهی ایجاد کنید

نمونه کد زیر متد reportTypes.list را برای بازیابی لیستی از انواع گزارش های موجود فراخوانی می کند. سپس متد jobs.create را برای ایجاد یک کار گزارش‌دهی جدید فراخوانی می‌کند.

/*
 * Copyright (c) 2015 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.
 */

package com.google.api.services.samples.youtube.cmdline.reporting;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtubereporting.YouTubeReporting;
import com.google.api.services.youtubereporting.model.Job;
import com.google.api.services.youtubereporting.model.ListReportTypesResponse;
import com.google.api.services.youtubereporting.model.ReportType;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * This sample creates a reporting job by:
 *
 * 1. Listing the available report types using the "reportTypes.list" method.
 * 2. Creating a reporting job using the "jobs.create" method.
 *
 * @author Ibrahim Ulukaya
 */
public class CreateReportingJob {

    /**
     * Define a global instance of a YouTube Reporting object, which will be used to make
     * YouTube Reporting API requests.
     */
    private static YouTubeReporting youtubeReporting;


    /**
     * Create a reporting job.
     *
     * @param args command line args (not used).
     */
    public static void main(String[] args) {

        /*
         * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
         * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
         * use this scope.
         */
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");

        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes, "createreportingjob");

            // This object is used to make YouTube Reporting API requests.
            youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-createreportingjob-sample").build();

            // Prompt the user to specify the name of the job to be created.
            String name = getNameFromUser();

            if (listReportTypes()) {
              createReportingJob(getReportTypeIdFromUser(), name);
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode()
                    + " : " + e.getDetails().getMessage());
            e.printStackTrace();

        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());
            t.printStackTrace();
        }
    }

    /**
     * Lists report types. (reportTypes.listReportTypes)
     * @return true if at least one report type exists
     * @throws IOException
     */
    private static boolean listReportTypes() throws IOException {
        // Call the YouTube Reporting API's reportTypes.list method to retrieve report types.
        ListReportTypesResponse reportTypesListResponse = youtubeReporting.reportTypes().list()
            .execute();
        List<ReportType> reportTypeList = reportTypesListResponse.getReportTypes();

        if (reportTypeList == null || reportTypeList.isEmpty()) {
          System.out.println("No report types found.");
          return false;
        } else {
            // Print information from the API response.
            System.out.println("\n================== Report Types ==================\n");
            for (ReportType reportType : reportTypeList) {
                System.out.println("  - Id: " + reportType.getId());
                System.out.println("  - Name: " + reportType.getName());
                System.out.println("\n-------------------------------------------------------------\n");
           }
        }
        return true;
    }

    /**
     * Creates a reporting job. (jobs.create)
     *
     * @param reportTypeId Id of the job's report type.
     * @param name name of the job.
     * @throws IOException
     */
    private static void createReportingJob(String reportTypeId, String name)
        throws IOException {
        // Create a reporting job with a name and a report type id.
        Job job = new Job();
        job.setReportTypeId(reportTypeId);
        job.setName(name);

        // Call the YouTube Reporting API's jobs.create method to create a job.
        Job createdJob = youtubeReporting.jobs().create(job).execute();

        // Print information from the API response.
        System.out.println("\n================== Created reporting job ==================\n");
        System.out.println("  - ID: " + createdJob.getId());
        System.out.println("  - Name: " + createdJob.getName());
        System.out.println("  - Report Type Id: " + createdJob.getReportTypeId());
        System.out.println("  - Create Time: " + createdJob.getCreateTime());
        System.out.println("\n-------------------------------------------------------------\n");
    }

    /*
     * Prompt the user to enter a name for the job. Then return the name.
     */
    private static String getNameFromUser() throws IOException {

        String name = "";

        System.out.print("Please enter the name for the job [javaTestJob]: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        name = bReader.readLine();

        if (name.length() < 1) {
            // If nothing is entered, defaults to "javaTestJob".
          name = "javaTestJob";
        }

        System.out.println("You chose " + name + " as the name for the job.");
        return name;
    }

    /*
     * Prompt the user to enter a report type id for the job. Then return the id.
     */
    private static String getReportTypeIdFromUser() throws IOException {

        String id = "";

        System.out.print("Please enter the reportTypeId for the job: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        id = bReader.readLine();

        System.out.println("You chose " + id + " as the report type Id for the job.");
        return id;
    }
}

مثال 2: بازیابی گزارش

نمونه کد متد jobs.list را برای بازیابی لیستی از مشاغل گزارش شده فراخوانی می کند. سپس متد reports.list را با پارامتر jobId که روی یک شناسه شغلی خاص تنظیم شده است فراخوانی می‌کند تا گزارش‌های ایجاد شده توسط آن شغل را بازیابی کند. در نهایت، نمونه URL دانلود هر گزارش را چاپ می کند.

/*
 * Copyright (c) 2015 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.
 */

package com.google.api.services.samples.youtube.cmdline.reporting;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.GenericUrl;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtubereporting.YouTubeReporting;
import com.google.api.services.youtubereporting.YouTubeReporting.Media.Download;
import com.google.api.services.youtubereporting.model.Job;
import com.google.api.services.youtubereporting.model.ListJobsResponse;
import com.google.api.services.youtubereporting.model.ListReportsResponse;
import com.google.api.services.youtubereporting.model.Report;

import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import javax.print.attribute.standard.Media;

/**
 * This sample retrieves reports created by a specific job by:
 *
 * 1. Listing the jobs using the "jobs.list" method.
 * 2. Retrieving reports using the "reports.list" method.
 *
 * @author Ibrahim Ulukaya
 */
public class RetrieveReports {

    /**
     * Define a global instance of a YouTube Reporting object, which will be used to make
     * YouTube Reporting API requests.
     */
    private static YouTubeReporting youtubeReporting;


    /**
     * Retrieve reports.
     *
     * @param args command line args (not used).
     */
    public static void main(String[] args) {

        /*
         * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
         * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
         * use this scope.
         */
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");

        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes, "retrievereports");

            // This object is used to make YouTube Reporting API requests.
            youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-retrievereports-sample").build();

            if (listReportingJobs()) {
              if(retrieveReports(getJobIdFromUser())) {
                downloadReport(getReportUrlFromUser());
              }
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode()
                    + " : " + e.getDetails().getMessage());
            e.printStackTrace();

        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());
            t.printStackTrace();
        }
    }

    /**
     * Lists reporting jobs. (jobs.listJobs)
     * @return true if at least one reporting job exists
     * @throws IOException
     */
    private static boolean listReportingJobs() throws IOException {
        // Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
        ListJobsResponse jobsListResponse = youtubeReporting.jobs().list().execute();
        List<Job> jobsList = jobsListResponse.getJobs();

        if (jobsList == null || jobsList.isEmpty()) {
          System.out.println("No jobs found.");
          return false;
        } else {
            // Print information from the API response.
            System.out.println("\n================== Reporting Jobs ==================\n");
            for (Job job : jobsList) {
                System.out.println("  - Id: " + job.getId());
                System.out.println("  - Name: " + job.getName());
                System.out.println("  - Report Type Id: " + job.getReportTypeId());
                System.out.println("\n-------------------------------------------------------------\n");
            }
        }
        return true;
    }

    /**
     * Lists reports created by a specific job. (reports.listJobsReports)
     *
     * @param jobId The ID of the job.
     * @throws IOException
     */
    private static boolean retrieveReports(String jobId)
        throws IOException {
        // Call the YouTube Reporting API's reports.list method
        // to retrieve reports created by a job.
        ListReportsResponse reportsListResponse = youtubeReporting.jobs().reports().list(jobId).execute();
        List<Report> reportslist = reportsListResponse.getReports();

        if (reportslist == null || reportslist.isEmpty()) {
            System.out.println("No reports found.");
            return false;
        } else {
            // Print information from the API response.
            System.out.println("\n============= Reports for the job " + jobId + " =============\n");
            for (Report report : reportslist) {
                System.out.println("  - Id: " + report.getId());
                System.out.println("  - From: " + report.getStartTime());
                System.out.println("  - To: " + report.getEndTime());
                System.out.println("  - Download Url: " + report.getDownloadUrl());
                System.out.println("\n-------------------------------------------------------------\n");
            }
        }
        return true;
    }

    /**
     * Download the report specified by the URL. (media.download)
     *
     * @param reportUrl The URL of the report to be downloaded.
     * @throws IOException
     */
    private static boolean downloadReport(String reportUrl)
        throws IOException {
        // Call the YouTube Reporting API's media.download method to download a report.
        Download request = youtubeReporting.media().download("");
        FileOutputStream fop = new FileOutputStream(new File("report"));
        request.getMediaHttpDownloader().download(new GenericUrl(reportUrl), fop);
        return true;
    }

    /*
     * Prompt the user to enter a job id for report retrieval. Then return the id.
     */
    private static String getJobIdFromUser() throws IOException {

        String id = "";

        System.out.print("Please enter the job id for the report retrieval: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        id = bReader.readLine();

        System.out.println("You chose " + id + " as the job Id for the report retrieval.");
        return id;
    }

    /*
     * Prompt the user to enter a URL for report download. Then return the URL.
     */
    private static String getReportUrlFromUser() throws IOException {

        String url = "";

        System.out.print("Please enter the report URL to download: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        url = bReader.readLine();

        System.out.println("You chose " + url + " as the URL to download.");
        return url;
    }}

PHP

نمونه های زیر از کتابخانه مشتری PHP استفاده می کنند.

مثال 1: یک کار گزارش دهی ایجاد کنید

نمونه کد زیر متد reportTypes.list را برای بازیابی لیستی از انواع گزارش های موجود فراخوانی می کند. سپس متد jobs.create را برای ایجاد یک کار گزارش‌دهی جدید فراخوانی می‌کند.

<?php

/**
 * This sample creates a reporting job by:
 *
 * 1. Listing the available report types using the "reportTypes.list" method.
 * 2. Creating a reporting job using the "jobs.create" method.
 *
 * @author Ibrahim Ulukaya
 */

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);

/*
 * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
 * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
 * use this scope.
 */
$client->setScopes('https://www.googleapis.com/auth/yt-analytics-monetary.readonly');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// YouTube Reporting object used to make YouTube Reporting API requests.
$youtubeReporting = new Google_Service_YouTubeReporting($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  // This code executes if the user enters a name in the form
  // and submits the form. Otherwise, the page displays the form above.
  try {
    if (empty(listReportTypes($youtubeReporting, $htmlBody))) {
      $htmlBody .= sprintf('<p>No report types found.</p>');
    } else if ($_GET['reportTypeId']){
      createReportingJob($youtubeReporting, $_GET['reportTypeId'], $_GET['jobName'], $htmlBody);
    }
  } catch (Google_Service_Exception $e) {
    $htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
        htmlspecialchars($e->getMessage()));
  }
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}


/**
 * Creates a reporting job. (jobs.create)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param string $reportTypeId Id of the job's report type.
 * @param string $name name of the job.
 * @param $htmlBody - html body.
 */
function createReportingJob(Google_Service_YouTubeReporting $youtubeReporting, $reportTypeId,
    $name, &$htmlBody) {
  # Create a reporting job with a name and a report type id.
  $reportingJob = new Google_Service_YouTubeReporting_Job();
  $reportingJob->setReportTypeId($reportTypeId);
  $reportingJob->setName($name);

  // Call the YouTube Reporting API's jobs.create method to create a job.
  $jobCreateResponse = $youtubeReporting->jobs->create($reportingJob);

  $htmlBody .= "<h2>Created reporting job</h2><ul>";
  $htmlBody .= sprintf('<li>"%s" for reporting type "%s" at "%s"</li>',
      $jobCreateResponse['name'], $jobCreateResponse['reportTypeId'], $jobCreateResponse['createTime']);
  $htmlBody .= '</ul>';
}


/**
 * Returns a list of report types. (reportTypes.listReportTypes)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param $htmlBody - html body.
 */
function listReportTypes(Google_Service_YouTubeReporting $youtubeReporting, &$htmlBody) {
  // Call the YouTube Reporting API's reportTypes.list method to retrieve report types.
  $reportTypes = $youtubeReporting->reportTypes->listReportTypes();

  $htmlBody .= "<h3>Report Types</h3><ul>";
  foreach ($reportTypes as $reportType) {
    $htmlBody .= sprintf('<li>id: "%s", name: "%s"</li>', $reportType['id'], $reportType['name']);
  }
  $htmlBody .= '</ul>';

  return $reportTypes;
}
?>

<!doctype html>
<html>
<head>
<title>Create a reporting job</title>
</head>
<body>
  <form method="GET">
    <div>
      Job Name: <input type="text" id="jobName" name="jobName" placeholder="Enter Job Name">
    </div>
    <br>
    <div>
      Report Type Id: <input type="text" id="reportTypeId" name="reportTypeId" placeholder="Enter Report Type Id">
    </div>
    <br>
    <input type="submit" value="Create!">
  </form>
  <?=$htmlBody?>
</body>
</html>

مثال 2: بازیابی گزارش

نمونه کد متد jobs.list را برای بازیابی لیستی از مشاغل گزارش شده فراخوانی می کند. سپس متد reports.list را با پارامتر jobId که روی یک شناسه شغلی خاص تنظیم شده است فراخوانی می‌کند تا گزارش‌های ایجاد شده توسط آن شغل را بازیابی کند. در نهایت، نمونه URL دانلود هر گزارش را چاپ می کند.

<?php

/**
 * This sample supports the following use cases:
 *
 * 1. Retrieve reporting jobs by content owner:
 *    Ex: php retrieve_reports.php  --contentOwner=="CONTENT_OWNER_ID"
 *    Ex: php retrieve_reports.php  --contentOwner=="CONTENT_OWNER_ID" --includeSystemManaged==True
 * 2. Retrieving list of downloadable reports for a particular job:
 *    Ex: php retrieve_reports.php  --contentOwner=="CONTENT_OWNER_ID" --jobId="JOB_ID"
 * 3. Download a report:
 *    Ex: php retrieve_reports.php  --contentOwner=="CONTENT_OWNER_ID" --downloadUrl="DOWNLOAD_URL" --outputFile="report.txt"
 */

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';
session_start();


define('CREDENTIALS_PATH', '~/.credentials/youtube-php.json');

$longOptions = array(
  'contentOwner::',
  'downloadUrl::',
  'includeSystemManaged::',
  'jobId::',
  'outputFile::',
);

$options = getopt('', $longOptions);

$CONTENT_OWNER_ID = ($options['contentOwner'] ? $options['contentOwner'] : '');
$DOWNLOAD_URL = (array_key_exists('downloadUrl', $options) ?
                 $options['downloadUrl'] : '');
$INCLUDE_SYSTEM_MANAGED = (array_key_exists('includeSystemManaged', $options) ?
                           $options['includeSystemManaged'] : '');
$JOB_ID = (array_key_exists('jobId', $options) ? $options['jobId'] : '');
$OUTPUT_FILE = (array_key_exists('outputFile', $options) ?
                $options['outputFile'] : '');

/*
 * You can obtain an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
function getClient() {
  $client = new Google_Client();
  $client->setAuthConfigFile('client_secrets_php.json');
  $client->addScope(
      'https://www.googleapis.com/auth/yt-analytics-monetary.readonly');
  $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf('Open the following link in your browser:\n%s\n', $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->authenticate($authCode);
    $refreshToken = $client->getRefreshToken();

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf('Credentials saved to %s\n', $credentialsPath);

    //fclose($fp);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }

  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

/**
 * Returns a list of reporting jobs. (jobs.listJobs)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param string $onBehalfOfContentOwner A content owner ID.
 */
function listReportingJobs(Google_Service_YouTubeReporting $youtubeReporting,
    $onBehalfOfContentOwner = '', $includeSystemManaged = False) {
  $reportingJobs = $youtubeReporting->jobs->listJobs(
      array('onBehalfOfContentOwner' => $onBehalfOfContentOwner,
            'includeSystemManaged' => $includeSystemManaged));
  print ('REPORTING JOBS' . PHP_EOL . '**************' . PHP_EOL);
  foreach ($reportingJobs as $job) {
    print($job['reportTypeId'] . ':' . $job['id'] . PHP_EOL);
  }
  print(PHP_EOL);
}

/**
 * Lists reports created by a specific job. (reports.listJobsReports)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param string $jobId The ID of the job.
 * @param string $onBehalfOfContentOwner A content owner ID.
 */
function listReportsForJob(Google_Service_YouTubeReporting $youtubeReporting,
    $jobId, $onBehalfOfContentOwner = '') {
  $reports = $youtubeReporting->jobs_reports->listJobsReports($jobId,
      array('onBehalfOfContentOwner' => $onBehalfOfContentOwner));
  print ('DOWNLOADABLE REPORTS' . PHP_EOL . '********************' . PHP_EOL);
  foreach ($reports['reports'] as $report) {
    print('Created: ' . date('d M Y', strtotime($report['createTime'])) .
          ' (' . date('d M Y', strtotime($report['startTime'])) .
          ' to ' . date('d M Y', strtotime($report['endTime'])) . ')' .
          PHP_EOL .  '    ' . $report['downloadUrl'] . PHP_EOL . PHP_EOL);
  }
}

/**
 * Download the report specified by the URL. (media.download)
 *
 * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object.
 * @param string $reportUrl The URL of the report to be downloaded.
 * @param string $outputFile The file to write the report to locally.
 * @param $htmlBody - html body.
 */
function downloadReport(Google_Service_YouTubeReporting $youtubeReporting,
    $reportUrl, $outputFile) {
  $client = $youtubeReporting->getClient();
  // Setting the defer flag to true tells the client to return a request that
  // can be called with ->execute(); instead of making the API call immediately.
  $client->setDefer(true);

  // Call YouTube Reporting API's media.download method to download a report.
  $request = $youtubeReporting->media->download('', array('alt' => 'media'));
  $request = $request->withUri(new \GuzzleHttp\Psr7\Uri($reportUrl));
  $responseBody = '';
  try {
    $response = $client->execute($request);
    $responseBody = $response->getBody();
  } catch (Google_Service_Exception $e) {
    $responseBody = $e->getTrace()[0]['args'][0]->getResponseBody();
  }
  file_put_contents($outputFile, $responseBody);
  $client->setDefer(false);
}

// Define an object that will be used to make all API requests.
$client = getClient();
// YouTube Reporting object used to make YouTube Reporting API requests.
$youtubeReporting = new Google_Service_YouTubeReporting($client);

if ($CONTENT_OWNER_ID) {
  if (!$DOWNLOAD_URL && !$JOB_ID) {
    listReportingJobs($youtubeReporting, $CONTENT_OWNER_ID,
                      $INCLUDE_SYSTEM_MANAGED);
  } else if ($JOB_ID) {
    listReportsForJob($youtubeReporting, $JOB_ID, $CONTENT_OWNER_ID);
  } else if ($DOWNLOAD_URL && $OUTPUT_FILE) {
    downloadReport($youtubeReporting, $DOWNLOAD_URL, $OUTPUT_FILE);
  }
}

?>

پایتون

نمونه های زیر از کتابخانه کلاینت پایتون استفاده می کنند.

مثال 1: یک کار گزارش دهی ایجاد کنید

نمونه کد زیر متد reportTypes.list را برای بازیابی لیستی از انواع گزارش های موجود فراخوانی می کند. سپس متد jobs.create را برای ایجاد یک کار گزارش‌دهی جدید فراخوانی می‌کند.

#!/usr/bin/python

# Create a reporting job for the authenticated user's channel or
# for a content owner that the user's account is linked to.
# Usage example:
# python create_reporting_job.py --name='<name>'
# python create_reporting_job.py --content-owner='<CONTENT OWNER ID>'
# python create_reporting_job.py --content-owner='<CONTENT_OWNER_ID>' --report-type='<REPORT_TYPE_ID>' --name='<REPORT_NAME>'

import argparse
import os

import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow


# 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://cloud.google.com/console }}.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = 'client_secret.json'

# This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
# authenticated user's account. Any request that retrieves earnings or ad performance metrics must
# use this scope.
SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly']
API_SERVICE_NAME = 'youtubereporting'
API_VERSION = 'v1'

# Authorize the request and store authorization credentials.
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

# Remove keyword arguments that are not set.
def remove_empty_kwargs(**kwargs):
  good_kwargs = {}
  if kwargs is not None:
    for key, value in kwargs.iteritems():
      if value:
        good_kwargs[key] = value
  return good_kwargs

# Call the YouTube Reporting API's reportTypes.list method to retrieve report types.
def list_report_types(youtube_reporting, **kwargs):
  # Provide keyword arguments that have values as request parameters.
  kwargs = remove_empty_kwargs(**kwargs)
  results = youtube_reporting.reportTypes().list(**kwargs).execute()
  reportTypes = results['reportTypes']

  if 'reportTypes' in results and results['reportTypes']:
    reportTypes = results['reportTypes']
    for reportType in reportTypes:
      print 'Report type id: %s\n name: %s\n' % (reportType['id'], reportType['name'])
  else:
    print 'No report types found'
    return False

  return True


# Call the YouTube Reporting API's jobs.create method to create a job.
def create_reporting_job(youtube_reporting, report_type_id, **kwargs):
  # Provide keyword arguments that have values as request parameters.
  kwargs = remove_empty_kwargs(**kwargs)

  reporting_job = youtube_reporting.jobs().create(
    body=dict(
      reportTypeId=args.report_type,
      name=args.name
    ),
    **kwargs
  ).execute()

  print ('Reporting job "%s" created for reporting type "%s" at "%s"'
         % (reporting_job['name'], reporting_job['reportTypeId'],
             reporting_job['createTime']))


# Prompt the user to enter a report type id for the job. Then return the id.
def get_report_type_id_from_user():
  report_type_id = raw_input('Please enter the reportTypeId for the job: ')
  print ('You chose "%s" as the report type Id for the job.' % report_type_id)
  return report_type_id

# Prompt the user to set a job name
def prompt_user_to_set_job_name():
  job_name = raw_input('Please set a name for the job: ')
  print ('Great! "%s" is a memorable name for this job.' % job_name)
  return job_name


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # The 'name' option specifies the name that will be used for the reporting job.
  parser.add_argument('--content-owner', default='',
      help='ID of content owner for which you are retrieving jobs and reports.')
  parser.add_argument('--include-system-managed', default=False,
      help='Whether the API response should include system-managed reports')
  parser.add_argument('--name', default='',
    help='Name for the reporting job. The script prompts you to set a name ' +
         'for the job if you do not provide one using this argument.')
  parser.add_argument('--report-type', default=None,
    help='The type of report for which you are creating a job.')
  args = parser.parse_args()

  youtube_reporting = get_authenticated_service()

  try:
    # Prompt user to select report type if they didn't set one on command line.
    if not args.report_type:
      if list_report_types(youtube_reporting,
                           onBehalfOfContentOwner=args.content_owner,
                           includeSystemManaged=args.include_system_managed):
        args.report_type = get_report_type_id_from_user()
    # Prompt user to set job name if not set on command line.
    if not args.name:
      args.name = prompt_user_to_set_job_name()
    # Create the job.
    if args.report_type:
      create_reporting_job(youtube_reporting,
                           args,
                           onBehalfOfContentOwner=args.content_owner)
  except HttpError, e:
    print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)

مثال 2: بازیابی گزارش

نمونه کد متد jobs.list را برای بازیابی لیستی از مشاغل گزارش شده فراخوانی می کند. سپس متد reports.list را با پارامتر jobId که روی یک شناسه شغلی خاص تنظیم شده است فراخوانی می‌کند تا گزارش‌های ایجاد شده توسط آن شغل را بازیابی کند. در نهایت، نمونه URL دانلود هر گزارش را چاپ می کند.

#!/usr/bin/python

###
#
# This script retrieves YouTube Reporting API reports. Use cases:
# 1. If you specify a report URL, the script downloads that report.
# 2. Otherwise, if you specify a job ID, the script retrieves a list of
#    available reports for that job and prompts you to select a report.
#    Then it retrieves that report as in case 1.
# 3. Otherwise, the list retrieves a list of jobs for the user or,
#    if specified, the content owner that the user is acting on behalf of.
#    Then it prompts the user to select a job, and then executes case 2 and
#    then case 1.
# Usage examples:
# python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --local_file=<LOCAL_FILE>
# python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --job_id=<JOB_ID> --local_file=<LOCAL_FILE>
# python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --report_url=<REPORT_URL> --local_file=<LOCAL_FILE>
#
###

import argparse
import os

import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from io import FileIO


# 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://cloud.google.com/console }}.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = 'client_secret.json'

# This OAuth 2.0 access scope allows for read access to YouTube Analytics
# monetary reports for the authenticated user's account. Any request that
# retrieves earnings or ad performance metrics must use this scope.
SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly']
API_SERVICE_NAME = 'youtubereporting'
API_VERSION = 'v1'

# Authorize the request and store authorization credentials.
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

# Remove keyword arguments that are not set.
def remove_empty_kwargs(**kwargs):
  good_kwargs = {}
  if kwargs is not None:
    for key, value in kwargs.iteritems():
      if value:
        good_kwargs[key] = value
  return good_kwargs

# Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
def list_reporting_jobs(youtube_reporting, **kwargs):
  # Only include the onBehalfOfContentOwner keyword argument if the user
  # set a value for the --content_owner argument.
  kwargs = remove_empty_kwargs(**kwargs)

  # Retrieve the reporting jobs for the user (or content owner).
  results = youtube_reporting.jobs().list(**kwargs).execute()

  if 'jobs' in results and results['jobs']:
    jobs = results['jobs']
    for job in jobs:
      print ('Reporting job id: %s\n name: %s\n for reporting type: %s\n'
        % (job['id'], job['name'], job['reportTypeId']))
  else:
    print 'No jobs found'
    return False

  return True

# Call the YouTube Reporting API's reports.list method to retrieve reports created by a job.
def retrieve_reports(youtube_reporting, **kwargs):
  # Only include the onBehalfOfContentOwner keyword argument if the user
  # set a value for the --content_owner argument.
  kwargs = remove_empty_kwargs(**kwargs)

  # Retrieve available reports for the selected job.
  results = youtube_reporting.jobs().reports().list(
    **kwargs
  ).execute()

  if 'reports' in results and results['reports']:
    reports = results['reports']
    for report in reports:
      print ('Report dates: %s to %s\n       download URL: %s\n'
        % (report['startTime'], report['endTime'], report['downloadUrl']))


# Call the YouTube Reporting API's media.download method to download the report.
def download_report(youtube_reporting, report_url, local_file):
  request = youtube_reporting.media().download(
    resourceName=' '
  )
  request.uri = report_url
  fh = FileIO(local_file, mode='wb')
  # Stream/download the report in a single request.
  downloader = MediaIoBaseDownload(fh, request, chunksize=-1)

  done = False
  while done is False:
    status, done = downloader.next_chunk()
    if status:
      print 'Download %d%%.' % int(status.progress() * 100)
  print 'Download Complete!'


# Prompt the user to select a job and return the specified ID.
def get_job_id_from_user():
  job_id = raw_input('Please enter the job id for the report retrieval: ')
  print ('You chose "%s" as the job Id for the report retrieval.' % job_id)
  return job_id

# Prompt the user to select a report URL and return the specified URL.
def get_report_url_from_user():
  report_url = raw_input('Please enter the report URL to download: ')
  print ('You chose "%s" to download.' % report_url)
  return report_url

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--content_owner', default='',
      help='ID of content owner for which you are retrieving jobs and reports')
  parser.add_argument('--job_id', default=None,
      help='ID of the job for which you are retrieving reports. If not ' +
           'provided AND report_url is also not provided, then the script ' +
           'calls jobs.list() to retrieve a list of jobs.')
  parser.add_argument('--report_url', default=None,
      help='URL of the report to retrieve. If not specified, the script ' +
           'calls reports.list() to retrieve a list of reports for the ' +
           'selected job.')
  parser.add_argument('--local_file', default='yt_report.txt',
      help='The name of the local file where the downloaded report will be written.')
  args = parser.parse_args()

  youtube_reporting = get_authenticated_service()
  try:
    # If the user has not specified a job ID or report URL, retrieve a list
    # of available jobs and prompt the user to select one.
    if not args.job_id and not args.report_url:
      if list_reporting_jobs(youtube_reporting,
                             onBehalfOfContentOwner=args.content_owner):
        args.job_id = get_job_id_from_user()

    # If the user has not specified a report URL, retrieve a list of reports
    # available for the specified job and prompt the user to select one.
    if args.job_id and not args.report_url:
      retrieve_reports(youtube_reporting,
                       jobId=args.job_id,
                       onBehalfOfContentOwner=args.content_owner)
      args.report_url = get_report_url_from_user()

    # Download the selected report.
    if args.report_url:
      download_report(youtube_reporting, args.report_url, args.local_file)
  except HttpError, e:
    print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)