### PHP Example: Localhost Setup Source: https://developers.google.com/youtube/partner/guides/auth/server-side-web-apps Commands to set up a local PHP development environment for Google API examples. This includes creating a directory and installing the Google API Client Library via Composer. ```Shell mkdir ~/php-oauth2-example cd ~/php-oauth2-example ``` ```Shell composer require google/apiclient:"^2.15.0" ``` ```Shell php -S localhost:8080 ~/php-oauth2-example ``` -------------------------------- ### Set up Node.js OAuth 2.0 Example Source: https://developers.google.com/youtube/partner/guides/auth/server-side-web-apps Instructions for setting up a Node.js environment to run an OAuth 2.0 example, including directory creation and dependency installation. ```bash mkdir ~/nodejs-oauth2-example cd ~/nodejs-oauth2-example npm install googleapis ``` -------------------------------- ### Run Node.js OAuth 2.0 Example Source: https://developers.google.com/youtube/partner/guides/auth/server-side-web-apps Command to execute the Node.js OAuth 2.0 example after setup. ```bash node .\main.js ``` -------------------------------- ### Cobalt Installation Slot Paths Example Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/doc/evergreen/cobalt_evergreen_overview Illustrates the file paths for Cobalt installation slots on a Raspberry Pi, including the read-only system image slot and writable additional slots. ```text /home/pi//app/cobalt (system image installation SLOT_0) (read-only) /home/pi/.cobalt_storage/installation_1 (SLOT_1) /home/pi/.cobalt_storage/installation_2 (SLOT_2) ... /home/pi/.cobalt_storage/installation_N (SLOT_N) ``` -------------------------------- ### Load Video by ID with Argument Syntax Source: https://developers.google.com/youtube/iframe_api_reference This example shows how to load a video using the `loadVideoById` function with the argument syntax. It specifies the video ID and start time. ```javascript loadVideoById("bHQqvYy5KYo", 5, "large") ``` -------------------------------- ### Complete YouTube Partner API Upload and Monetization Example Source: https://developers.google.com/youtube/partner/guides/upload A full Python script demonstrating video upload, claiming, and monetization setup using the YouTube Partner API. Includes command-line argument parsing and retry logic. ```python #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simple command-line sample for Youtube Partner API. Command-line application that creates an asset, uploads and claims a video for that asset. Usage: $ python upload_monetize_video_example.py --file=VIDEO_FILE --channelID=CHANNEL_ID \ [--title=VIDEO_TITLE] [--description=VIDEO_DESCRIPTION] [--category=CATEGORY_ID] \ [--keywords=KEYWORDS] [--privacyStatus=PRIVACY_STATUS] [--policyId=POLICY_ID] You can also get help on all the command-line flags the program understands by running: $ python upload_monetize_video_example.py --help """ __author__ = 'jeffy+pub@google.com (Jeffrey Posnick)' import httplib import httplib2 import logging import os import random import sys import time from apiclient.discovery import build from apiclient.errors import HttpError from apiclient.http import MediaFileUpload from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run from optparse import OptionParser # Explicitly tell the underlying HTTP transport library not to retry, since # we are handling retry logic ourselves. httplib2.RETRIES = 1 # Maximum number of times to retry before giving up. MAX_RETRIES = 10 # Always retry when these exceptions are raised. RETRIABLE_EXCEPTIONS = ( httplib2.HttpLib2Error, IOError, httplib.NotConnected, httplib.IncompleteRead, httplib.ImproperConnectionState, httplib.CannotSendRequest, httplib.CannotSendHeader, httplib.ResponseNotReady, httplib.BadStatusLine,) # Always retry when an apiclient.errors.HttpError with one of these status # codes is raised. RETRIABLE_STATUS_CODES = (500, 502, 503, 504,) # The message associated with the HTTP 401 error that's returned when a request # is authorized by a user whose account is not associated with a YouTube # content owner. INVALID_CREDENTIALS = "Invalid Credentials" # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from ``` -------------------------------- ### YouTube Content ID API Sample Usage Source: https://developers.google.com/youtube/partner/guides/migration_xml_to_api?hl=th Demonstrates how to run the command-line application to retrieve content owner information. Includes examples for basic usage, getting help, and enabling detailed logging. ```bash python yt_partner_api.py --file="/path/to/reference/file" ``` ```bash python yt_partner_api.py --help ``` ```bash python yt_partner_api.py --logging_level=DEBUG \ --file="/path/to/reference/file" ``` -------------------------------- ### Install Google API Client Library (npm) Source: https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps This command installs the Google API Client Library for Node.js using npm. Ensure you have Node.js installed before running this command. ```bash npm install googleapis ``` -------------------------------- ### SbImageDecode and SbImageIsDecodeSupported Example Source: https://developers.google.com/youtube/cobalt/docs/reference/starboard/modules/15/image Example demonstrating how to check for decode support and then perform image decoding. ```APIDOC ## SbImageIsDecodeSupported and SbImageDecode Example ```c SbDecodeTargetProvider* provider = GetProviderFromSomewhere(); void* data = GetCompressedJPEGFromSomewhere(); int data_size = GetCompressedJPEGSizeFromSomewhere(); const char* mime_type = "image/jpeg"; SbDecodeTargetFormat format = kSbDecodeTargetFormat1PlaneRGBA; if (!SbImageIsDecodeSupported(mime_type, format)) { return; } SbDecodeTarget result_target = SbImageDecode(provider, data, data_size, mime_type, format); ``` ``` -------------------------------- ### Example Compilation Command Source: https://developers.google.com/youtube/cobalt/docs/development/setup-windows An example of compiling Cobalt for the 'win-win32' platform with a 'debug' build type, targeting the 'cobalt' executable. ```bash ninja -C out/win-win32_debug cobalt ``` -------------------------------- ### Example Compilation Command Source: https://developers.google.com/youtube/cobalt/docs/development/setup-linux An example of compiling the Cobalt debug configuration for the linux-x64x11 platform, targeting the 'cobalt' executable. ```bash ninja -C out/linux-x64x11_debug cobalt ``` -------------------------------- ### Install Google API Client Library for Python Source: https://developers.google.com/youtube/analytics/v1/reference/reports/query Installs the Google API Client Library for Python and related authentication libraries using pip. Ensure you have Python and pip installed. ```bash pip install --upgrade google-api-python-client pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 ``` -------------------------------- ### Install Pre-commit Hooks and Create Branch Source: https://developers.google.com/youtube/cobalt/docs/development/setup-linux Install pre-commit hooks for various Git actions and create a new Git branch from origin/master. ```bash pre-commit install -t post-checkout -t pre-commit -t pre-push --allow-missing-config git checkout -b origin/master ``` -------------------------------- ### Example of a partial response with fields parameter Source: https://developers.google.com/youtube/partner/guides/performance This example demonstrates a request using the `fields` parameter and its corresponding partial response, showing only the requested data. ```http https://www.googleapis.com/demo/v1?**fields=kind,items(title,characteristics/length)** ``` ```http **200 OK** ``` ```json { "kind": "demo", "items": [ { "title": "First title", "characteristics": { "length": "short" } }, { "title": "Second title", "characteristics": { "length": "long" } }, ... ] } ``` -------------------------------- ### Install Crashpad Handler in Main Function (Linux Example) Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/doc/crash_handlers Call the InstallCrashpadHandler hook after installing system signal handlers. This example demonstrates the setup on Linux, including installing signal handlers and providing the CA certificates path. ```c++ #include "third_party/crashpad/crashpad/wrapper/wrapper.h" int main(int argc, char** argv) { ... starboard::shared::signal::InstallCrashSignalHandlers(); starboard::shared::signal::InstallSuspendSignalHandlers(); std::string ca_certificates_path = starboard::common::GetCACertificatesPath(); third_party::crashpad::wrapper::InstallCrashpadHandler(ca_certificates_path); int result = application.Run(argc, argv); ... } ``` -------------------------------- ### Playlist Performance by Traffic Source in a Country Source: https://developers.google.com/youtube/analytics/sample-requests Get playlist views, watch time, and starts for a specific country, aggregated by traffic source. This example uses 'US' as the country. ```text dimensions=insightTrafficSourceType metrics=views,estimatedMinutesWatched,playlistStarts,playlistViews filters=country==US ``` -------------------------------- ### Example: Configuring for a Memory-Plentiful Platform Source: https://developers.google.com/youtube/cobalt/docs/gen/cobalt/doc/memory_tuning Shows how to allocate significant memory for image cache and set high limits for CPU and GPU usage on a memory-rich platform. ```bash cobalt --max_cobalt_cpu_usage=500MB --max_cobalt_gpu_usage=500MB --image_cache_size_in_bytes=80MB ``` -------------------------------- ### Create Toolchain Directory and Navigate Source: https://developers.google.com/youtube/cobalt/docs/development/setup-raspi Sets up the directory for the cross-compiling toolchain and navigates into it. Ensure `$RASPI_HOME` is set and added to your `.bashrc`. ```bash $ mkdir -p $RASPI_HOME $ cd $RASPI_HOME ``` -------------------------------- ### Example: Configuring for a Memory-Restricted Platform Source: https://developers.google.com/youtube/cobalt/docs/gen/cobalt/doc/memory_tuning Demonstrates setting memory configurations for a restricted platform, including image cache, Skia atlas, and max CPU usage. ```bash cobalt --max_cobalt_cpu_usage=160MB ``` -------------------------------- ### GET Request with `fields` Parameter Source: https://developers.google.com/youtube/partner/guides/performance This example shows how to use the `fields` parameter in a GET request to specify exactly which fields should be returned, significantly reducing the response size. ```HTTP https://www.googleapis.com/demo/v1?**fields=kind,items(title,characteristics/length)** ``` -------------------------------- ### Main Execution Block Source: https://developers.google.com/youtube/partner/code_samples/python Sets up logging, parses command-line arguments, authenticates services, and orchestrates the video upload, asset creation, claiming, and advertising setup process. ```python if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) args = parse_args() if args.file is None or not os.path.exists(args.file): logging.error("Please specify a valid file using the --file= parameter.") exit(1) # The channel ID value has a format like "UC..." and must identify a channel # managed by the YouTube content owner associated with the authenticated user. # You can use the YouTube Data API's youtube.channels.list method to # retrieve a list of managed channels and their IDs. (To do so, set the # "part" parameter value to "snippet", the "managedByMe" parameter value to # "true" and the "onBehalfOfContentOwner" parameter to the content owner ID. # The "get_content_owner_id" method in this code sample shows how # to retrieve the content owner ID. if args.channelId is None: logging.error("Please specify a channel ID via the --channelId= parameter.") exit(1) (youtube, youtube_partner) = get_authenticated_services(args) content_owner_id = get_content_owner_id(youtube_partner) logging.info("Authenticated as content owner ID '%s'." % content_owner_id) (video_id, duration_seconds) = upload(youtube, content_owner_id, args) logging.info("Successfully uploaded video ID '%s'." % video_id) file_size_bytes = os.path.getsize(args.file) logging.debug("Uploaded %d bytes in %0.2f seconds (%0.2f megabytes/second)." % (file_size_bytes, duration_seconds, (file_size_bytes / (1024 * 1024)) / duration_seconds)) asset_id = create_asset(youtube_partner, content_owner_id, args.title, args.description) logging.info("Created new asset ID '%s'." % asset_id) set_asset_ownership(youtube_partner, content_owner_id, asset_id) logging.info("Successfully set asset ownership.") claim_id = claim_video(youtube_partner, content_owner_id, asset_id, video_id, args.policyId) logging.info("Created new claim ID '%s'." % claim_id) set_advertising_options(youtube_partner, content_owner_id, video_id) logging.info("Successfully set advertising options.") logging.info("All done!") ``` -------------------------------- ### Simple GET Request (No `fields` parameter) Source: https://developers.google.com/youtube/partner/guides/performance This example demonstrates a basic HTTP GET request without the `fields` parameter, which results in the server returning the full resource. ```HTTP https://www.googleapis.com/demo/v1 ``` -------------------------------- ### HTTP GET Request with Authorization Header Source: https://developers.google.com/youtube/reporting/guides/authorization/client-side-web-apps An example of an HTTP GET request to the YouTube Analytics API using the 'Authorization: Bearer' header. This is the preferred method for including access tokens. ```http GET /youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views HTTP/1.1 Host: www.googleapis.com Authorization: Bearer access_token ``` -------------------------------- ### Example Command-Line Arguments for Video Upload Source: https://developers.google.com/youtube/partner/guides/upload Illustrates the format for various command-line arguments used when uploading a video, including required and optional parameters like file path, channel ID, title, description, category, keywords, privacy status, and monetization policy ID. ```bash Example: --file="/home/path/to/file.mov" ``` ```bash Example: --channelId="UC_x5XG1OV2P6uZZ5FSM9Ttw" ``` ```bash Example: --title="Summer vacation in California" ``` ```bash Example: --description="Had a great time surfing in Santa Cruz" ``` ```bash Example: --category=22 ``` ```bash Example: --keywords="surfing, beach volleyball" ``` ```bash Example: --privacyStatus="private" ``` ```bash Example: --policyId="S309961703555739" ``` -------------------------------- ### Set Up Evergreen Build Arguments Source: https://developers.google.com/youtube/cobalt/docs/development/setup-linux Configure environment variables and generate build arguments for Evergreen builds using gn. Ensure these match the prebuilt binary specifications. ```bash export EG_PLATFORM=evergreen-x64 export EG_BUILD_TYPE=qa export SB_API_VER=16 export EVERGREEN_DIR=out/${EG_PLATFORM}_${EG_BUILD_TYPE} gn gen $EVERGREEN_DIR --args="target_platform=\"$EG_PLATFORM\" use_asan=false build_type=\"$EG_BUILD_TYPE\" sb_api_version=$SB_API_VER" ``` -------------------------------- ### Get Current Playback Time Source: https://developers.google.com/youtube/iframe_api_reference Returns the elapsed time in seconds since the video started playing. ```javascript player.getCurrentTime(); ``` -------------------------------- ### Build and Run Tests Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/tools/doc/testing Use the `-b` flag to build unit test binaries, or use `-br` to build and then immediately run them. ```bash python test_runner.py -b ``` ```bash python test_runner.py -br ``` -------------------------------- ### HTTP GET Request with Access Token Query Parameter Source: https://developers.google.com/youtube/reporting/guides/authorization/client-side-web-apps An example of an HTTP GET request to the YouTube Analytics API using the 'access_token' query string parameter. While functional, using query strings for tokens is less secure than headers. ```http GET https://www.googleapis.com/youtube/analytics/v1/reports?access_token=access_token&ids=channel%3D%3DMINE&start-date=2016-05-01&end-date=2016-06-30&metrics=views ``` -------------------------------- ### Main Execution Block Source: https://developers.google.com/youtube/partner/guides/upload Sets up logging, parses command-line options, authenticates services, and orchestrates the video upload and asset management process. Exits if required parameters are missing. ```python if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) options = parse_options() if options.file is None or not os.path.exists(options.file): logging.error("Please specify a valid file using the --file= parameter.") exit(1) # The channel ID looks something like "UC..." and needs to correspond to a # channel managed by the YouTube content owner authorizing the request. # youtube.channels.list(part="snippet", managedByMe=true, # onBehalfOfContentOwner=*CONTENT_OWNER_ID*) # can be used to retrieve a list of managed channels and their channel IDs. # See https://developers.google.com/youtube/v3/docs/channels/list if options.channelId is None: logging.error("Please specify a channel ID via the --channelId= parameter.") exit(1) (youtube, youtube_partner) = get_authenticated_services() content_owner_id = get_content_owner_id(youtube_partner) logging.info("Authorized by content owner ID '%s'." % content_owner_id) (video_id, duration_seconds) = upload(youtube, content_owner_id, options) logging.info("Successfully uploaded video ID '%s'." % video_id) file_size_bytes = os.path.getsize(options.file) logging.debug("Uploaded %d bytes in %0.2f seconds (%0.2f megabytes/second)." % (file_size_bytes, duration_seconds, (file_size_bytes / (1024 * 1024)) / duration_seconds)) asset_id = create_asset(youtube_partner, content_owner_id, options.title, options.description) logging.info("Created new asset ID '%s'." % asset_id) set_asset_ownership(youtube_partner, content_owner_id, asset_id) logging.info("Successfully set asset ownership.") claim_id = claim_video(youtube_partner, content_owner_id, asset_id, video_id, options.policyId) logging.info("Successfully claimed video.") set_advertising_options(youtube_partner, content_owner_id, video_id) logging.info("Successfully set advertising options.") logging.info("All done!") ``` -------------------------------- ### HTTP Request Example Source: https://developers.google.com/youtube/partner/reference/rest/v1/whitelists/list This is the base HTTP GET request to list whitelisted channels. It requires the `id` and `onBehalfOfContentOwner` query parameters. ```http GET https://youtubepartner.googleapis.com/youtube/partner/v1/whitelists?id=CHANNEL_ID_1,CHANNEL_ID_2&onBehalfOfContentOwner=CONTENT_OWNER_ID ``` -------------------------------- ### HTTP Request Example Source: https://developers.google.com/youtube/partner/reference/rest/v1/musicChangeRequests/list This is the base URL for making a GET request to list music change requests. You can append query parameters to filter and paginate the results. ```HTTP GET https://youtubepartner.googleapis.com/youtube/partner/v1/music/changeRequests ``` -------------------------------- ### Main Execution Block Source: https://developers.google.com/youtube/partner/code_samples/python?hl=de Sets up logging, authenticates the YouTube Partner service, retrieves the content owner ID, and then proceeds to create, list, update, and search for assets and labels. Includes a note about potential delays in asset indexing for search results. ```python if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) args = argparser.parse_args() youtube_partner = get_authenticated_service(args) content_owner_id = get_content_owner_id(youtube_partner) logging.info("Authenticated as CMS user ID '%s'." % content_owner_id) asset_label_name = create_asset_label(youtube_partner, content_owner_id, "label1"); list_asset_labels(youtube_partner, content_owner_id) asset1 = create_asset(youtube_partner, content_owner_id, "asset1") logging.info("Created new asset ID '%s'." % asset1["id"]) asset1 = update_asset(youtube_partner, content_owner_id, asset1, [asset_label_name, "label3"]) logging.info("Added asset labels '%s %s' to '%s'." % (asset1["label"][0], asset1["label"][1], asset1["id"])) asset2 = create_asset(youtube_partner, content_owner_id, "asset2") logging.info("Created new asset ID '%s'." % asset2["id"]) asset2 = update_asset(youtube_partner, content_owner_id, asset2, ["label3"]) logging.info("Added asset label '%s' to '%s'." % (asset2["label"][0], asset2["id"])) list_asset_labels(youtube_partner, content_owner_id) # AssetSearch may not be able to return the expected results right away, as there is a delay # in indexing the assets with labels for the asset search after they are added. # Second run of the code sample after this delay will return the expected assets # of the previous run. search_asset(youtube_partner, content_owner_id, "label1, label3", None) search_asset(youtube_partner, content_owner_id, "label1, label3", True) logging.info("All done!") ``` -------------------------------- ### Run YouTube Analytics API Quickstart Script Source: https://developers.google.com/youtube/analytics/reference/reports/query Executes the YouTube Analytics API quickstart script. Ensure the CLIENT_SECRETS_FILE variable is updated with the correct path to your downloaded credentials file. ```bash python yt_analytics_v2.py ``` -------------------------------- ### HTTP GET Request with Authorization Header Source: https://developers.google.com/youtube/partner/guides/auth/client-side-web-apps Example of calling the YouTube Content ID API using the Authorization: Bearer header. This method is preferred over query parameters for security. ```http GET /youtubepartner/v1/contentOwners?fetchMine=true HTTP/1.1 Host: www.googleapis.com Authorization: Bearer access_token ``` -------------------------------- ### Example elf_loader_sandbox paths Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/doc/starboard_16_posix Illustrates the relative paths expected by the elf_loader_sandbox for its library and content. ```text .../elf_loader_sandbox .../content/app/nplb/lib/libnplb.so .../content/app/nplb/content ``` -------------------------------- ### HTTP/REST Request for Incremental Authorization Source: https://developers.google.com/youtube/partner/guides/auth/server-side-web-apps This example shows an HTTP GET request to the Google OAuth 2.0 authorization server that includes `include_granted_scopes=true` to request incremental authorization for YouTube Analytics data. ```http GET https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly& access_type=offline& response_type=code& state=security_token%3D138rk%3Btarget_url%3Dhttp...index& redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback& client_id=client_id& **include_granted_scopes=true** ``` -------------------------------- ### JavaScript CORS Request to Google API Source: https://developers.google.com/youtube/partner/guides/auth/client-side-web-apps Example using XMLHttpRequest to make a GET request to a Google API with an access token. This snippet does not use the Google APIs Client Library for JavaScript. ```javascript var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://www.googleapis.com/youtube/partner/v1/contentOwners?fetchMine=true' + 'access_token=' + params['access_token']); xhr.onreadystatechange = function (e) { console.log(xhr.response); }; xhr.send(null); ``` -------------------------------- ### Install and Launch nplb Test APK Source: https://developers.google.com/youtube/cobalt/docs/development/setup-android Installs the nplb test APK onto the device and then launches it with specific arguments for running tests. The --esa flag is used to pass arguments, including the library and content paths, and the gtest output configuration. ```bash adb install out/android-arm_devel/nplb_evergreen_loader.apk adb shell "am start --esa args '--evergreen_library=app/cobalt/lib/libnplb.so,--evergreen_content=app/cobalt/content' dev.cobalt.coat" ``` -------------------------------- ### PHP Authentication and Client Setup Source: https://developers.google.com/youtube/reporting/v1/reference/rest/v1/jobs/list?hl=id Sets up the Google API client for YouTube Reporting, handling authentication and token management. It loads existing credentials or guides the user through the OAuth 2.0 authorization flow. ```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: * * 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); } ``` -------------------------------- ### Create Package Directory and Download Content Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/doc/evergreen/cobalt_evergreen_reference_port_raspi2 Sets up the directory structure for Cobalt Evergreen and downloads the latest Evergreen package. This is for the 2-slot configuration. ```bash ## Create package directory for Cobalt Evergreen $ export COEG_PATH=coeg $ cp out/raspi-2_qa/starboard/loader_app $COEG_PATH ## Create directory structure for the initial installation [2-slot configuration] $ mkdir -p ~/.cobalt_storage/installation_0/ $ cd ~/.cobalt_storage/installation_0/ ## Download package $ curl -L https://dl.google.com/cobalt/evergreen/latest/cobalt_arm-hardfp_qa.crx -o cobalt.zip ## Unpack content package $ unzip cobalt.zip $ rm cobalt.zip $ cd - ``` -------------------------------- ### Initialize Redis Token Store Source: https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps?hl=ja Sets up a token store using Redis for persisting access and refresh tokens. Requires a running Redis instance. ```ruby token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) ``` -------------------------------- ### HTTP GET Request with Access Token Query Parameter Source: https://developers.google.com/youtube/partner/guides/auth/client-side-web-apps Example of calling the YouTube Content ID API using the access_token query string parameter. Note that this is less secure than using the Authorization header. ```http GET https://www.googleapis.com/youtubepartner/v1/contentOwners?access_token=access_token&fetchMine=true ``` -------------------------------- ### Incremental Authorization Request URL Example Source: https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps This HTTP GET request demonstrates how to construct a URL for incremental authorization. It includes the `include_granted_scopes=true` parameter along with other standard OAuth 2.0 parameters like `scope`, `access_type`, and `redirect_uri`. ```http GET https://accounts.google.com/o/oauth2/v2/auth? scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly& access_type=offline& state=security_token%3D138rk%3Btarget_url%3Dhttp...index& redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback& response_type=code& client_id=client_id& **include_granted_scopes=true** ``` -------------------------------- ### Asset Reference Upload Example Usage Source: https://developers.google.com/youtube/partner/asset_reference_upload_example?hl=he This snippet shows the command-line usage for the Python script. It requires a reference file, asset title, and owner as arguments. You can also get help by running the script with the --help flag. ```bash python asset_reference_upload_example.py --reference_file=REFERENCE_FILE --asset_title=ASSET_TITLE --owner=OWNER ``` ```bash python asset_reference_upload_example.py --help ``` -------------------------------- ### Setup Evergreen Build Arguments Source: https://developers.google.com/youtube/cobalt/docs/development/setup-linux Configure environment variables and generate build files for an Evergreen build. This is typically done in the Cobalt root directory. ```bash # go to cobalt root folder export COBALT_SRC=${PWD} export PYTHONPATH=${PWD}:${PYTHONPATH} # setup evergreen build arguments export EG_PLATFORM=evergreen-x64 export EG_BUILD_TYPE=devel export SB_API_VER=16 export EVERGREEN_DIR=out/${EG_PLATFORM}_${EG_BUILD_TYPE} gn gen $EVERGREEN_DIR --args="target_platform=\"$EG_PLATFORM\" use_asan=false build_type=\"$EG_BUILD_TYPE\" sb_api_version=$SB_API_VER" ``` -------------------------------- ### Fetch and Build Breakpad Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/doc/evergreen/symbolizing_minidumps Fetch the Breakpad source code using depot_tools and then configure and build the necessary tools, including `minidump_stackwalk` and `dump_syms`. ```bash mkdir breakpad && cd breakpad fetch breakpad cd src ./configure && make ``` -------------------------------- ### SbUserGetCurrent Source: https://developers.google.com/youtube/cobalt/docs/reference/starboard/modules/14/user Gets the current primary user, if one exists. This is the user that is determined, in a platform-specific way, to be the primary user controlling the application. For example, the determination might be made because that user launched the app, though it should be made using whatever criteria are appropriate for the platform. It is expected that there will be a unique SbUser per signed-in user, and that the referenced objects will persist for the lifetime of the app. ```APIDOC ## Functions ### SbUserGetCurrent Gets the current primary user, if one exists. This is the user that is determined, in a platform-specific way, to be the primary user controlling the application. For example, the determination might be made because that user launched the app, though it should be made using whatever criteria are appropriate for the platform. It is expected that there will be a unique SbUser per signed-in user, and that the referenced objects will persist for the lifetime of the app. #### Declaration ```c SbUser SbUserGetCurrent() ``` ``` -------------------------------- ### Display Test Runner Help Source: https://developers.google.com/youtube/cobalt/docs/gen/starboard/tools/doc/testing Run this command to see a full list of parameters that can be supplied to the test runner script. ```bash python test_runner.py --help ``` -------------------------------- ### Install Google API Client Library for PHP Source: https://developers.google.com/youtube/partner/guides/auth/server-side-web-apps Use Composer to install the Google APIs Client Library for PHP. Ensure you have PHP 8.0 or greater and Composer installed. ```bash composer require google/apiclient:^2.15.0 ```