YouTube Reporting API - Get Bulk Data Reports

重要提示:每日 API 报告和回填报告将在生成之日后保留 60 天。历史数据报告自生成之日起 30 天内可用。

此政策适用于全球所有报告和报告作业。如需了解完整详情,请参阅 YouTube Reporting API 的修订历史记录

YouTube Reporting API 支持预定义报告,其中包含面向频道或内容所有者的一整套 YouTube 数据分析数据。您可以通过这些报告下载批量数据集,然后使用 YouTube Analytics API 或在 YouTube 工作室的数据分析部分中查询这些数据集。

该 API 还支持一组自动生成的由系统管理的报告,供有权访问“报告”菜单中相应报告的内容所有者使用。这些报告包含广告收入数据和 YouTube Premium 订阅收入数据。如需了解详情,请参阅系统管理的报告文档。

概览

这些报告中的报告字段分为维度和指标:

  • 维度是用于汇总数据的常用条件,例如操作发生的日期或用户所在的国家/地区。在报告中,每行数据都有唯一的维度值组合。
  • 指标是指与用户活动、广告效果或估算收入相关的具体衡量结果。用户活动指标包括视频观看次数和评分(顶和踩)等。

例如,渠道的基本用户活动报告包含以下维度:

  • day:活动发生的日期。
  • channel:与活动相关联的 YouTube 频道。
  • video:与活动相关联的 YouTube 视频。
  • liveOrOnDemand:一个值,表示观看者是否在观看直播视频。
  • subscribedStatus:一个值,表示观看者是否订阅了频道。
  • country:观看者所在的国家/地区。

该报告还包含许多指标,例如观看次数赞的次数平均观看时长。检索并导入报告后,应用可以根据常见的维度值进行许多不同的计算。

例如,要计算特定日期在德国的总观看次数,请将以下行的 views 指标值相加:country 列的值为 DEday 列的值是 YYYY-MM-DD 格式的日期。

获取 YouTube 数据分析报告

以下步骤说明了如何通过该 API 检索频道和内容所有者报告。有关如何获取这些报告的说明,请参阅系统管理的报告

第 1 步:检索授权凭据

所有 YouTube Reporting API 请求都必须获得授权。要通过 OAuth 2.0 协议检索授权令牌,请参阅授权指南

YouTube Reporting API 请求使用以下授权范围:

范围
https://www.googleapis.com/auth/yt-analytics.readonly 查看 YouTube 分析工具为您的 YouTube 内容出具的报告。此范围提供对用户活动指标(例如观看次数和评分次数)的访问权限。
https://www.googleapis.com/auth/yt-analytics-monetary.readonly 查看 YouTube 分析工具为您的 YouTube 内容出具的财务报告。此范围可让您访问用户活动指标以及估算的收入和广告效果指标。

第 2 步:确定要检索的报告

调用 API 的 reportTypes.list 方法,获取可为频道或内容所有者生成的报告列表。该方法会返回报告 ID 和名称的列表。获取要生成的报告的 id 属性值。例如,渠道的“基本用户活动”报告的 ID 为 channel_basic_a1

您也可以在定义受支持的频道报告内容所有者报告的文档中找到报告名称。

第 3 步:创建报告作业

在您为某个报告创建报告作业之前,YouTube 不会开始生成报告。(因此,系统只会为实际想要检索内容的频道和内容所有者生成报告。)

如需创建报告作业,请调用 API 的 jobs.create 方法。在请求正文中设置以下值:

  • reportTypeId 属性的值设置为您在第 2 步中检索到的报告 ID。
  • name 属性的值设置为要与报告关联的名称。

jobs.create 方法的 API 响应包含一个 Job 资源,该资源指定了用于唯一标识作业的 ID。您可以在创建作业后的 48 小时内开始检索报告,并且第一个可用的报告将涵盖您安排作业的当天。

例如,如果将作业安排在 9 月 1 日,则 9 月 1 日的报告将于 9 月 3 日生成。9 月 2 日的报告将于 9 月 4 日发布。

第 4 步:检索作业 ID

注意:如果您的应用存储了第 3 步中返回的作业 ID,则可以跳过此步骤。

调用 jobs.list 方法可检索计划的作业列表。每个返回的 Job 资源中的 reportTypeId 属性用于标识该作业生成的报告的类型。在下一步中,您的应用需要来自同一资源的 id 属性值。

第 5 步:检索报告的下载网址

调用 jobs.reports.list 方法可检索为作业创建的报告列表。在请求中,将 jobId 参数设置为要检索的报告的作业 ID。

提示:使用 createdAfter 参数指明 API 应仅返回在指定时间之后创建的报告。此参数可用于确保 API 仅返回您尚未处理的报告。

API 响应包含该作业的 Report 资源列表。每项资源都会引用一份报告,其中包含 24 小时内的唯一数据。请注意,YouTube 会针对没有数据的日子生成可下载的报告。这些报告包含标题行,但不包含其他数据。

  • 资源的 startTimeendTime 属性用于标识报表数据涵盖的时间段。
  • 资源的 downloadUrl 属性用于标识可从中提取报告的网址。
  • 资源的 createTime 属性用于指定报告生成的日期和时间。您的应用应存储此值,并使用此值来确定之前下载的报告是否已发生更改。

第 6 步:下载报告

向第 5 步中获得的 downloadUrl 发送 HTTP GET 请求,以检索报告。

您可以通过对下载请求启用 gzip 压缩来减少下载报告所需的带宽。虽然您的应用需要额外的 CPU 时间来解压缩 API 响应,但节省网络资源的好处通常会超过这一成本。

如需接收 gzip 编码的响应,请将 Accept-Encoding HTTP 请求标头设置为 gzip,如以下示例所示:

Accept-Encoding: gzip

处理报告

最佳做法

使用 YouTube Reporting API 的应用应始终遵循以下做法:

  • 如需确定报告列的排序,请使用报告的标题行。例如,不要仅仅假设“浏览次数”是报告说明中列出的第一个指标,就假定它在报告中返回的第一个指标。而应使用报告的标题行来确定哪列包含相应数据。

  • 为避免重复处理同一报告,请记录已下载的报告。以下列表提供了几种实现方法。

    • 调用 reports.list 方法时,使用 createdAfter 参数可仅检索在特定日期之后创建的报告。(首次检索报告时,请省略 createdAfter 参数。)

      每次检索并成功处理报告时,请存储与这些报告最新创建时的日期和时间相对应的时间戳。然后,在每次连续调用 reports.list 方法时更新 createdAfter 参数值,以确保每次调用 API 时都仅检索新报告(包括包含回填数据的新报告)。

      为安全起见,在检索报告之前,还应检查以确保报告的 ID 未已列入数据库中。

    • 存储您已下载和处理的每个报告的 ID。您还可以存储其他信息,例如每个报告的生成日期和时间,或报告的 startTimeendTime,这两者共同用于确定报告包含数据的时间段。请注意,每个作业都可能会有多个报告,因为每份报告都包含 24 小时内的数据。

      使用报告 ID 来识别您仍然需要下载和导入的报告。不过,如果两个新报告具有相同的 startTimeendTime 属性值,则仅导入具有较新 createTime 值的报告。

  • 报告包含与 YouTube 资源相关联的 ID。如需检索这些资源的其他元数据,请使用 YouTube Data API。如 YouTube API 服务开发者政策(III.E.4.b 至 III.E.4.d 部分)中所述,API 客户端必须在 30 天后从该 API 中删除或刷新存储的资源元数据。

报告特征

API 报告是具有以下特征的版本化 .csv(英文逗号分隔值)文件:

  • 每份报告包含一个 24 小时的独特时间段的数据,该时间段从太平洋标准时间 (UTC-8) 凌晨 12:00 到晚上 11:59 结束。因此,在任何给定报告中,维度值始终相同。

  • 报告每天更新一次。

  • 对于没有数据的日期,YouTube 会生成可下载的报告。这些报告将包含标题行,但不包含其他数据。

  • API 报告自生成之日起 60 天内可用,但为新报告作业生成的历史数据除外。报告生成超过 60 天后将无法访问。
  • 包含历史数据的报告自生成之日起 30 天内可用。对于包含历史数据的报告,如果报告已超过 30 天,则无法访问。
  • 系统不会过滤报告数据。因此,频道报告包含频道中视频或播放列表的所有数据,但下文中与已删除的资源相关的数据除外。同样,内容所有者报告包含内容所有者频道的所有数据(视频、播放列表、广告效果等),但存在以下例外情况。

    虽然报告数据不会经过过滤,但报告中不会包含对在报告生成日期前至少 30 天前删除的 YouTube 资源的任何引用。

  • 报告数据未排序。

  • 报告会忽略不含指标的行。换言之,没有任何指标的行会从报告中排除。例如,如果某个视频在特定日期没有在阿尔巴尼亚获得任何观看次数,那么当天的报告中将不会包含阿尔巴尼亚对应的行。

  • 报告中不包含提供指标摘要数据的行,例如某个频道中所有视频的总观看次数。您可以将这些总值计算为报告中值的总和,但如上所述,此总和可能不包含已删除视频的指标。您还可以使用 YouTube Analytics API 来检索总计数据。YouTube Analytics API 会返回包含已删除资源指标的总值,即使 API 响应中未明确引用这些资源也是如此。

回填数据

回填数据是指用于替换之前投放的数据集的数据集。当有回填数据报告可用时,您的应用应检索新报告并更新存储的数据,以与经过修改的数据集相匹配。例如,您的应用可能会删除报告所涵盖时段的先前数据,然后导入新的数据集。

如果 YouTube 有回填数据,则会生成一个新报告,并为其分配新的报告 ID。在这种情况下,该报告的 startTimeendTime 属性值将与之前可用且您之前可能下载的报告的开始时间和结束时间一致。

回填报告不会提及在报告生成日期之前至少 30 天被删除的 YouTube 资源。

历史数据

当您安排新的报告作业时,YouTube 会生成从当天开始的历史报告,并生成涵盖您创建该作业之前的 30 天的报告。因此,在本文档中,历史数据是指报告包含安排报告作业之前一段时间的数据。

历史报告一旦生成,便会立即发布。通常,招聘信息的所有历史数据都会在几天之内发布。如报告特性部分所述,包含历史数据的报告自生成之日起 30 天内可用。包含非历史数据的报告可以保留 60 天。

数据匿名化

为确保 YouTube 观看者的匿名性,仅当同一行中的指标达到特定阈值时,系统才会返回某些维度的值。

例如,在频道的视频流量来源报告中,每行都包含许多维度,包括 trafficSourceTypetrafficSourceDetail。每行还包含各种指标,包括观看次数。在用于描述来自 YouTube 搜索的流量的行中,trafficSourceDetail 维度用于标识带来了流量的搜索字词。

在此示例中,适用以下规则:

  • 只有当某个查询字词在特定日期为特定视频带来了至少一定数量的观看次数时,流量来源报告才会识别该查询字词 (trafficSourceDetail)。在本例中,“观看次数”是指标,“视频”是汇总维度,而“trafficSourceDetail”是匿名化维度。

  • 该报告中会新增一行,用于汇总未达到观看次数阈值的所有 trafficSourceDetail 值的指标。该行会报告与这些搜索字词相关联的总浏览次数,但不会指明这些字词本身。

下表说明了这些规则。第一个表格包含一组假设的原始数据,YouTube 会使用这些数据生成流量来源报告,而第二个表格包含该报告本身。在此示例中,观看次数阈值为 10,表示仅当某个搜索字词在某一天促成至少 10 次观看时,报告才会识别该搜索字词。(实际阈值可能会发生变化。)

视频的原始 YouTube 搜索流量数据

假设以下数据描述了某一天某个特定视频的 YouTube 搜索流量。

搜索字词 观看次数 估计观看时长
江南 Style 100 200
psy 15 25
psy gangnam 9 15
奥帕江南 5 8
骑马舞蹈 2 5

流量来源报告示例

下表摘录了 YouTube 为上一部分中的原始数据生成的流量来源报告。(实际报告将包含更多维度和指标。)在本例中,只有当搜索字词带来了至少 10 次观看时,报告才会识别该字词。实际阈值可能会发生变化。

在报告的第三行中,trafficSourceDetail 维度值为 NULL。“views”和“estimatedMinutesWatched”指标包含所产生观看次数少于 10 次的三个搜索字词的观看时长和总观看时长。

trafficSourceDetail 观看次数 estimatedMinutesWatched
Gangnam Style 100 200
psy 15 25
NULL 16 28

需要匿名处理的维度

下表列出了在关联指标值未达到特定阈值时匿名化的维度值。在每种情况下,指标的值都是按另一个维度进行汇总的。例如,如果指标是观看次数,而汇总维度是视频,那么除非视频的观看次数达到一定数量,否则维度值将经过匿名化处理。

指标 汇总维度 匿名化维度 匿名化值
subscribersGained channel country ZZ
subscribersGained channel province US-ZZ
subscribersLost channel country ZZ
subscribersLost channel province US-ZZ
评论 视频 country ZZ
comments 视频 province US-ZZ
视频 country ZZ
video province US-ZZ
不喜欢 视频 country ZZ
不喜欢 视频 province US-ZZ
观看次数 视频 ageGroup NULL
观看次数 视频 gender [适用性别] NULL
观看次数 videotrafficSourceDetail trafficSourceDetail NULL
频道订阅人数 channel subscribedStatus NULL

代码示例

以下代码示例演示了如何使用该 API 创建报告作业,然后检索该作业的报告。我们针对每种语言提供了两个代码示例:

  1. 第一个代码示例展示了如何检索可用报告类型的列表,然后创建新的报告作业。

  2. 第二个代码示例展示了如何检索特定作业的报告。您可以在创建作业后的 48 小时内开始检索报表。

注意:以下代码示例可能并未列出所有受支持的编程语言。如需查看受支持的语言列表,请参阅客户端库

Java

以下示例使用 Java 客户端库

示例 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 参数设置为特定作业 ID,以检索该作业创建的报告。最后,示例会输出每个报告的下载网址。

/*
 * 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 参数设为特定作业 ID,以检索该作业创建的报告。最后,示例会输出每个报告的下载网址。

<?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);
  }
}

?>

Python

以下示例使用 Python 客户端库

示例 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 参数设为特定作业 ID,以检索该作业创建的报告。最后,该示例会输出每个报告的下载网址。

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