建立及管理 CDN 金鑰

Video Stitcher API 會下載影片素材資源,以便在其中插入廣告。影片資產通常會透過內容傳遞網路 (CDN) 發布。為保護內容,影片素材資源網址可能需要簽章才能擷取,這就是所謂的網址簽署

如果影片資產需要簽章,Video Stitcher API 必須知道 CDN 金鑰,才能擷取媒體。此外,Video Stitcher API 會使用這些金鑰,為用戶端裝置的媒體片段建立權杖。

本文說明如何建立及管理 CDN 金鑰。詳情請參閱 REST 說明文件

註冊 CDN 金鑰

如果影片資產受到網址簽署保護,則必須向 Video Stitcher API 註冊 CDN 金鑰。

如要註冊 CDN 金鑰,請使用 projects.locations.cdnKeys.create 方法。

REST (Media CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID,會成為 CDN 金鑰資源名稱的最終元件。這個 ID 只能包含小寫英文字母、數字和連字號。 第一個字元必須是英文字母,最後一個字元必須是英文字母或數字,且整個 ID 最多只能有 63 個字元。
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • Media CDN 金鑰的金鑰組名稱MEDIA_CDN_KEYNAME
  • MEDIA_CDN_PRIVATE_KEY:64 位元組的 Ed25519 私密金鑰,採用 Base64 編碼字串。詳情請參閱「 建立 Media CDN 的私密金鑰」。

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。複製傳回的 OPERATION_ID,這是 name 欄位的最後一部分,將在下一節中使用。

REST (Cloud CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID,會成為 CDN 金鑰資源名稱的最終元件。這個 ID 只能包含小寫英文字母、數字和連字號。 第一個字元必須是英文字母,最後一個字元必須是英文字母或數字,且整個 ID 最多只能有 63 個字元。
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • Cloud CDN 金鑰的名稱GCDN_KEYNAME
  • GCDN_PRIVATE_KEY:Cloud CDN 金鑰的 base64 編碼字串密碼

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。複製傳回的 OPERATION_ID,這是 name 欄位的最後一部分,將在下一節中使用。

REST (Akamai CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID,會成為 CDN 金鑰資源名稱的最終元件。這個 ID 只能包含小寫英文字母、數字和連字號。 第一個字元必須是英文字母,最後一個字元必須是英文字母或數字,且整個 ID 最多只能有 63 個字元。
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • AKAMAI_TOKEN_KEY:Akamai CDN 邊緣設定的權杖金鑰,採用 base64 編碼的字串

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。複製傳回的 OPERATION_ID,這是 name 欄位的最後一部分,將在下一節中使用。

C#

在試用這個範例之前,請先按照C#使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API C# API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf;
using System.Threading.Tasks;

public class CreateCdnKeySample
{
    public async Task<CdnKey> CreateCdnKeyAsync(
    string projectId, string location, string cdnKeyId, string hostname,
    string keyName, string privateKey, bool isMediaCdn)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            Hostname = hostname
        };

        if (isMediaCdn)
        {
            cdnKey.MediaCdnKey = new MediaCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }
        else
        {
            cdnKey.GoogleCdnKey = new GoogleCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }

        CreateCdnKeyRequest request = new CreateCdnKeyRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, location),
            CdnKeyId = cdnKeyId,
            CdnKey = cdnKey
        };

        // Make the request.
        Operation<CdnKey, OperationMetadata> response = await client.CreateCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<CdnKey, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Go API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// createCDNKey creates a CDN key. A CDN key is used to retrieve protected media.
// If isMediaCDN is true, create a Media CDN key. If false, create a Cloud
// CDN key. To create a privateKey value for Media CDN, see
// https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
func createCDNKey(w io.Writer, projectID, keyID, privateKey string, isMediaCDN bool) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// privateKey := "my-private-key"
	// isMediaCDN := true
	location := "us-central1"
	hostname := "cdn.example.com"
	keyName := "cdn-key"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	var req *stitcherstreampb.CreateCdnKeyRequest
	if isMediaCDN {
		req = &stitcherstreampb.CreateCdnKeyRequest{
			Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
			CdnKeyId: keyID,
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_MediaCdnKey{
					MediaCdnKey: &stitcherstreampb.MediaCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Hostname: hostname,
			},
		}
	} else {
		req = &stitcherstreampb.CreateCdnKeyRequest{
			Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
			CdnKeyId: keyID,
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_GoogleCdnKey{
					GoogleCdnKey: &stitcherstreampb.GoogleCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Hostname: hostname,
			},
		}
	}

	// Creates the CDN key.
	op, err := client.CreateCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.CreateCdnKey: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "CDN key: %v", response.GetName())
	return nil
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Java API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CreateCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.GoogleCdnKey;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.MediaCdnKey;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateCdnKey {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";
    String hostname = "cdn.example.com";
    String keyName = "my-key";
    // To create a privateKey value for Media CDN, see
    // https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
    String privateKey = "my-private-key"; // will be converted to a byte string
    Boolean isMediaCdn = true;

    createCdnKey(projectId, location, cdnKeyId, hostname, keyName, privateKey, isMediaCdn);
  }

  // createCdnKey creates a Media CDN key or a Cloud CDN key. A CDN key is used to retrieve
  // protected media.
  public static CdnKey createCdnKey(
      String projectId,
      String location,
      String cdnKeyId,
      String hostname,
      String keyName,
      String privateKey,
      Boolean isMediaCdn)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CdnKey cdnKey;
      if (isMediaCdn) {
        cdnKey =
            CdnKey.newBuilder()
                .setHostname(hostname)
                .setMediaCdnKey(
                    MediaCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      } else {
        cdnKey =
            CdnKey.newBuilder()
                .setHostname(hostname)
                .setGoogleCdnKey(
                    GoogleCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      }

      CreateCdnKeyRequest createCdnKeyRequest =
          CreateCdnKeyRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .setCdnKeyId(cdnKeyId)
              .setCdnKey(cdnKey)
              .build();

      CdnKey result =
          videoStitcherServiceClient
              .createCdnKeyAsync(createCdnKeyRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Created new CDN key: " + result.getName());
      return result;
    }
  }
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Node.js API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

const location = 'us-central1';
const hostname = 'cdn.example.com';
const keyName = 'cdn-key';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// privateKey = 'my-private-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function createCdnKey() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    cdnKey: {
      hostname: hostname,
    },
    cdnKeyId: cdnKeyId,
  };

  if (isMediaCdn === 'true') {
    request.cdnKey.mediaCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
  } else {
    request.cdnKey.googleCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
  }

  const [operation] = await stitcherClient.createCdnKey(request);
  const [response] = await operation.promise();
  console.log(`CDN key: ${response.name}`);
}

createCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在試用這個範例之前,請先按照PHP使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API PHP API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\CreateCdnKeyRequest;
use Google\Cloud\Video\Stitcher\V1\GoogleCdnKey;
use Google\Cloud\Video\Stitcher\V1\MediaCdnKey;

/**
 * Creates a CDN key. Cloud CDN keys and Media CDN keys are supported.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the CDN key
 * @param string  $cdnKeyId           The ID of the CDN key to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $keyName            For a Media CDN key, this is the keyset name.
 *                                    For a Cloud CDN key, this is the public name of the
 *                                    CDN key.
 * @param string  $privateKey         For a Media CDN key, this is a 64-byte Ed25519 private
 *                                    key encoded as a base64-encoded string. See
 *                                    https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
 *                                    for more information. For a Cloud CDN key,
 *                                    this is a base64-encoded string secret.
 * @param bool    $isMediaCdn         If true, create a Media CDN key. If false,
 *                                    create a Cloud CDN key.
 */
function create_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $keyName,
    string $privateKey,
    bool $isMediaCdn
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $cdnKey = new CdnKey();
    $cdnKey->setHostname($hostname);

    if ($isMediaCdn == true) {
        $cloudCdn = new MediaCdnKey();
        $cdnKey->setMediaCdnKey($cloudCdn);
    } else {
        $cloudCdn = new GoogleCdnKey();
        $cdnKey->setGoogleCdnKey($cloudCdn);
    }
    $cloudCdn->setKeyName($keyName);
    $cloudCdn->setPrivateKey($privateKey);

    // Run CDN key creation request
    $request = (new CreateCdnKeyRequest())
        ->setParent($parent)
        ->setCdnKey($cdnKey)
        ->setCdnKeyId($cdnKeyId);
    $operationResponse = $stitcherClient->createCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('CDN key: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Python API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def create_cdn_key(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    key_name: str,
    private_key: str,
    is_cloud_cdn: bool,
) -> stitcher_v1.types.CdnKey:
    """Creates a Cloud CDN or Media CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location in which to create the CDN key.
        cdn_key_id: The user-defined CDN key ID.
        hostname: The hostname to which this CDN key applies.
        key_name: For a Media CDN key, this is the keyset name.
                  For a Cloud CDN key, this is the public name of the CDN key.
        private_key: For a Media CDN key, this is a 64-byte Ed25519 private
                     key encoded as a base64-encoded string.
                     See https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
                     for more information. For a Cloud CDN key, this is a base64-encoded string secret.
        is_cloud_cdn: If true, create a Cloud CDN key. If false, create a Media CDN key.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"

    cdn_key = stitcher_v1.types.CdnKey(
        name=cdn_key_id,
        hostname=hostname,
    )

    if is_cloud_cdn:
        cdn_key.google_cdn_key = stitcher_v1.types.GoogleCdnKey(
            key_name=key_name,
            private_key=private_key,
        )
    else:
        cdn_key.media_cdn_key = stitcher_v1.types.MediaCdnKey(
            key_name=key_name,
            private_key=private_key,
        )

    operation = client.create_cdn_key(
        parent=parent, cdn_key_id=cdn_key_id, cdn_key=cdn_key
    )
    response = operation.result()
    print(f"CDN key: {response.name}")
    return response

Ruby

在試用這個範例之前,請先按照Ruby使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Ruby API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/video/stitcher"

##
# Create a Media CDN or Cloud CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] The user-defined CDN key ID
# @param hostname [String] The hostname to which this CDN key applies
# @param key_name [String] For a Media CDN key, this is the keyset name.
#   For a Cloud CDN key, this is the public name of the CDN key.
# @param private_key [String] For a Media CDN key, this is a 64-byte Ed25519
#   private key encoded as a base64-encoded string. See
#   https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
#   for more information. For a Cloud CDN key, this is a base64-encoded string
#   secret.
# @param is_media_cdn [Boolean] If true, create a Media CDN key. If false,
#  create a Cloud CDN key.
#
def create_cdn_key project_id:, location:, cdn_key_id:, hostname:, key_name:,
                   private_key:, is_media_cdn:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location
  # Build the path for the CDN key resource.
  cdn_key_path = client.cdn_key_path project: project_id, location: location,
                                     cdn_key: cdn_key_id

  # Set the CDN key fields.
  new_cdn_key = if is_media_cdn
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    media_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                else
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    google_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                end

  operation = client.create_cdn_key parent: parent, cdn_key: new_cdn_key,
                                    cdn_key_id: cdn_key_id

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the CDN key name.
  puts "CDN key: #{operation.response.name}"
end

查看結果

如要檢查是否已建立 CDN 金鑰,請使用 projects.locations.operations.get 方法。如果回應包含 "done: false",請重複執行指令,直到回應包含 "done: true" 為止。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:資料位置; 請使用支援的區域
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • OPERATION_ID:作業的 ID

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "endTime": END_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "create",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.video.stitcher.v1.CdnKey",
    "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "hostname": "HOSTNAME",
    "mediaCdnKey": {
      "keyName": "MEDIA_CDN_KEYNAME"
    }
  }
}

建立 Media CDN 私密金鑰

Video Stitcher API 預期 ed25519 私密金鑰會是金鑰種子和公開金鑰的串連。如要使用 ed25519 產生的私密金鑰,建立與 Video Stitcher API 相容的私密金鑰,請執行下列指令:

# Extract the "key seed" from the private key
openssl pkey -outform DER -in test.private.key | tail -c +17 >> tmp.key

# Extract the "public key" from the private key
openssl pkey -outform DER -pubout -in test.private.key | tail -c +13 >> tmp.key

# Concatenate both parts in an intermediary key and base64-encode the resulting value
head -c 64 tmp.key | python3 -c "import base64, sys; print(('%s' % base64.urlsafe_b64encode(sys.stdin.buffer.read()))[2:-1])"

取得 CDN 金鑰

如要取得特定 CDN 金鑰的詳細資料,請使用 projects.locations.cdnKeys.get 方法。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號; 這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位
  • LOCATION:CDN 金鑰所在位置; 請使用其中一個支援的區域
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
  "hostname": "HOSTNAME",
  "mediaCdnKey": {
    "keyName": "MEDIA_CDN_KEYNAME"
  }
}

C#

在試用這個範例之前,請先按照C#使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API C# API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Video.Stitcher.V1;

public class GetCdnKeySample
{
    public CdnKey GetCdnKey(
        string projectId, string location, string cdnKeyId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        GetCdnKeyRequest request = new GetCdnKeyRequest
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId)
        };

        // Call the API.
        CdnKey response = client.GetCdnKey(request);

        // Return the result.
        return response;
    }
}

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Go API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// getCDNKey gets a CDN key by ID.
func getCDNKey(w io.Writer, projectID, keyID string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.GetCdnKeyRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID),
	}
	// Gets the CDN key.
	response, err := client.GetCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetCdnKey: %w", err)
	}
	b, err := json.MarshalIndent(response, "", " ")
	if err != nil {
		return fmt.Errorf("json.MarshalIndent: %w", err)
	}

	fmt.Fprintf(w, "CDN key:\n%s", string(b))
	return nil
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Java API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CdnKeyName;
import com.google.cloud.video.stitcher.v1.GetCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;

public class GetCdnKey {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";

    getCdnKey(projectId, location, cdnKeyId);
  }

  // Gets a CDN key.
  public static CdnKey getCdnKey(String projectId, String location, String cdnKeyId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      GetCdnKeyRequest getCdnKeyRequest =
          GetCdnKeyRequest.newBuilder()
              .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
              .build();

      CdnKey response = videoStitcherServiceClient.getCdnKey(getCdnKeyRequest);
      System.out.println("CDN key: " + response.getName());
      return response;
    }
  }
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Node.js API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// cdnKeyId = 'my-cdn-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function getCdnKey() {
  // Construct request
  const request = {
    name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
  };
  const [cdnKey] = await stitcherClient.getCdnKey(request);
  console.log(`CDN key: ${cdnKey.name}`);
}

getCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在試用這個範例之前,請先按照PHP使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API PHP API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\GetCdnKeyRequest;

/**
 * Gets a CDN key.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the CDN key
 * @param string $cdnKeyId             The ID of the CDN key
 */
function get_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $request = (new GetCdnKeyRequest())
        ->setName($formattedName);
    $key = $stitcherClient->getCdnKey($request);

    // Print results
    printf('CDN key: %s' . PHP_EOL, $key->getName());
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Python API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)


def get_cdn_key(
    project_id: str, location: str, cdn_key_id: str
) -> stitcher_v1.types.CdnKey:
    """Gets a CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN key.
        cdn_key_id: The user-defined CDN key ID.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/cdnKeys/{cdn_key_id}"
    response = client.get_cdn_key(name=name)
    print(f"CDN key: {response.name}")
    return response

Ruby

在試用這個範例之前,請先按照Ruby使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Ruby API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/video/stitcher"

##
# Get a CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] Your CDN key name (e.g. `my-cdn-key`)
#
def get_cdn_key project_id:, location:, cdn_key_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the CDN key.
  name = client.cdn_key_path project: project_id, location: location,
                             cdn_key: cdn_key_id

  # Get the CDN key.
  cdn_key = client.get_cdn_key name: name

  # Print the CDN key name.
  puts "CDN key: #{cdn_key.name}"
end

更新 CDN 金鑰

如要更新特定 CDN 金鑰,請使用 projects.locations.cdnKeys.patch 方法。

REST (Media CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • Media CDN 金鑰的金鑰組名稱MEDIA_CDN_KEYNAME
  • MEDIA_CDN_PRIVATE_KEY:64 位元組的 Ed25519 私密金鑰,採用 Base64 編碼字串。詳情請參閱「 建立 Media CDN 的私密金鑰」。

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "update",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。詳情請參閱「檢查結果」。

REST (Cloud CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • Cloud CDN 金鑰的名稱GCDN_KEYNAME
  • GCDN_PRIVATE_KEY:Cloud CDN 金鑰的 base64 編碼字串密碼

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "update",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。詳情請參閱「檢查結果」。

REST (Akamai CDN)

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:建立 CDN 金鑰的位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID
  • HOSTNAME:要與這個 CDN 金鑰建立關聯的 CDN 主機名稱 (例如 35.190.60.252 這類 IP 位址,或是 cdn.example.com 這類網域名稱)
  • AKAMAI_TOKEN_KEY:Akamai CDN 邊緣設定的權杖金鑰,採用 base64 編碼的字串

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "update",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。詳情請參閱「檢查結果」。

C#

在試用這個範例之前,請先按照C#使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API C# API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateCdnKeySample
{
    public async Task<CdnKey> UpdateCdnKeyAsync(
        string projectId, string location, string cdnKeyId, string hostname,
        string keyName, string privateKey, bool isMediaCdn)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId),
            Hostname = hostname
        };

        string path;
        if (isMediaCdn)
        {
            path = "media_cdn_key";
            cdnKey.MediaCdnKey = new MediaCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }
        else
        {
            path = "google_cdn_key";
            cdnKey.GoogleCdnKey = new GoogleCdnKey
            {
                KeyName = keyName,
                PrivateKey = ByteString.CopyFromUtf8(privateKey)
            };
        }

        UpdateCdnKeyRequest request = new UpdateCdnKeyRequest
        {
            CdnKey = cdnKey,
            UpdateMask = new FieldMask { Paths = { "hostname", path } }
        };

        // Make the request.
        Operation<CdnKey, OperationMetadata> response = await client.UpdateCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<CdnKey, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Go API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateCDNKey updates a CDN key. A CDN key is used to retrieve protected media.
// If isMediaCDN is true, update a Media CDN key. If false, update a Cloud
// CDN key. To create an updated privateKey value for Media CDN, see
// https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
func updateCDNKey(w io.Writer, projectID, keyID, privateKey string, isMediaCDN bool) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// privateKey := "my-updated-private-key"
	// isMediaCDN := true
	location := "us-central1"
	hostname := "updated.cdn.example.com"
	keyName := "cdn-key"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	var req *stitcherstreampb.UpdateCdnKeyRequest
	if isMediaCDN {
		req = &stitcherstreampb.UpdateCdnKeyRequest{
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_MediaCdnKey{
					MediaCdnKey: &stitcherstreampb.MediaCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Name:     fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID),
				Hostname: hostname,
			},
			UpdateMask: &fieldmaskpb.FieldMask{
				Paths: []string{
					"hostname", "media_cdn_key",
				},
			},
		}
	} else {
		req = &stitcherstreampb.UpdateCdnKeyRequest{
			CdnKey: &stitcherstreampb.CdnKey{
				CdnKeyConfig: &stitcherstreampb.CdnKey_GoogleCdnKey{
					GoogleCdnKey: &stitcherstreampb.GoogleCdnKey{
						KeyName:    keyName,
						PrivateKey: []byte(privateKey),
					},
				},
				Name:     fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID),
				Hostname: hostname,
			},
			UpdateMask: &fieldmaskpb.FieldMask{
				Paths: []string{
					"hostname", "google_cdn_key",
				},
			},
		}
	}

	// Updates the CDN key.
	op, err := client.UpdateCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.UpdateCdnKey: %w", err)
	}
	response, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Updated CDN key: %+v", response)
	return nil
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Java API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CdnKeyName;
import com.google.cloud.video.stitcher.v1.GoogleCdnKey;
import com.google.cloud.video.stitcher.v1.MediaCdnKey;
import com.google.cloud.video.stitcher.v1.UpdateCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.protobuf.ByteString;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateCdnKey {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-updated-cdn-key-id";
    String hostname = "updated.example.com";
    String keyName = "my-key";
    // To create a privateKey value for Media CDN, see
    // https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn.
    String privateKey = "my-updated-private-key"; // will be converted to a byte string
    Boolean isMediaCdn = true;

    updateCdnKey(projectId, location, cdnKeyId, hostname, keyName, privateKey, isMediaCdn);
  }

  // updateCdnKey updates the hostname and key fields for an existing Media CDN key or Cloud
  // CDN key.
  public static CdnKey updateCdnKey(
      String projectId,
      String location,
      String cdnKeyId,
      String hostname,
      String keyName,
      String privateKey,
      Boolean isMediaCdn)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      CdnKey cdnKey;
      String path;
      if (isMediaCdn) {
        path = "media_cdn_key";
        cdnKey =
            CdnKey.newBuilder()
                .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
                .setHostname(hostname)
                .setMediaCdnKey(
                    MediaCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      } else {
        path = "google_cdn_key";
        cdnKey =
            CdnKey.newBuilder()
                .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
                .setHostname(hostname)
                .setGoogleCdnKey(
                    GoogleCdnKey.newBuilder()
                        .setKeyName(keyName)
                        .setPrivateKey(ByteString.copyFromUtf8(privateKey))
                        .build())
                .build();
      }

      UpdateCdnKeyRequest updateCdnKeyRequest =
          UpdateCdnKeyRequest.newBuilder()
              .setCdnKey(cdnKey)
              // Update the hostname field and the fields for the specific key type (Media CDN
              // or Cloud CDN). You must set the mask to the fields you want to update.
              .setUpdateMask(FieldMask.newBuilder().addPaths("hostname").addPaths(path).build())
              .build();

      CdnKey response =
          videoStitcherServiceClient
              .updateCdnKeyAsync(updateCdnKeyRequest)
              .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Updated CDN key: " + response.getName());
      return response;
    }
  }
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Node.js API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

const location = 'us-central1';
const keyName = 'cdn-key';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// privateKey = 'my-private-key';
// isMediaCdn = true;

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function updateCdnKey() {
  // Construct request
  const request = {
    cdnKey: {
      name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
      hostname: hostname,
    },
  };

  if (isMediaCdn === 'true') {
    request.cdnKey.mediaCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
    request.updateMask = {
      paths: ['hostname', 'media_cdn_key'],
    };
  } else {
    request.cdnKey.googleCdnKey = {
      keyName: keyName,
      privateKey: privateKey,
    };
    request.updateMask = {
      paths: ['hostname', 'google_cdn_key'],
    };
  }

  const [operation] = await stitcherClient.updateCdnKey(request);
  const [response] = await operation.promise();
  console.log(`Updated CDN key: ${response.name}`);
  console.log(`Updated hostname: ${response.hostname}`);
}

updateCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在試用這個範例之前,請先按照PHP使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API PHP API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\GoogleCdnKey;
use Google\Cloud\Video\Stitcher\V1\MediaCdnKey;
use Google\Cloud\Video\Stitcher\V1\UpdateCdnKeyRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates a CDN key. Cloud CDN keys and Media CDN keys are supported.
 *
 * @param string  $callingProjectId   The project ID to run the API call under
 * @param string  $location           The location of the CDN key
 * @param string  $cdnKeyId           The ID of the CDN key to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $keyName            For a Media CDN key, this is the keyset name.
 *                                    For a Cloud CDN key, this is the public name of the
 *                                    CDN key.
 * @param string  $privateKey         For a Media CDN key, this is a 64-byte Ed25519 private
 *                                    key encoded as a base64-encoded string. See
 *                                    https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
 *                                    for more information. For a Cloud CDN key,
 *                                    this is a base64-encoded string secret.
 * @param bool    $isMediaCdn         If true, update a Media CDN key. If false,
 *                                    update a Cloud CDN key.
 */
function update_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $keyName,
    string $privateKey,
    bool $isMediaCdn
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $name = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $cdnKey = new CdnKey();
    $cdnKey->setName($name);
    $cdnKey->setHostname($hostname);
    $updateMask = new FieldMask();

    if ($isMediaCdn == true) {
        $cloudCdn = new MediaCdnKey();
        $cdnKey->setMediaCdnKey($cloudCdn);
        $updateMask = new FieldMask([
            'paths' => ['hostname', 'media_cdn_key']
        ]);
    } else {
        $cloudCdn = new GoogleCdnKey();
        $cdnKey->setGoogleCdnKey($cloudCdn);
        $updateMask = new FieldMask([
            'paths' => ['hostname', 'google_cdn_key']
        ]);
    }
    $cloudCdn->setKeyName($keyName);
    $cloudCdn->setPrivateKey($privateKey);

    // Run CDN key creation request
    $request = (new UpdateCdnKeyRequest())
        ->setCdnKey($cdnKey)
        ->setUpdateMask($updateMask);
    $operationResponse = $stitcherClient->updateCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $result = $operationResponse->getResult();
        // Print results
        printf('Updated CDN key: %s' . PHP_EOL, $result->getName());
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Python API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import argparse

from google.cloud.video import stitcher_v1
from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import field_mask_pb2 as field_mask


def update_cdn_key(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    key_name: str,
    private_key: str,
    is_cloud_cdn: bool,
) -> stitcher_v1.types.CdnKey:
    """Updates a Media CDN or Cloud CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN key.
        cdn_key_id: The user-defined CDN key ID.
        hostname: The hostname to which this CDN key applies.
        key_name: For a Media CDN key, this is the keyset name.
                  For a Cloud CDN key, this is the public name of the CDN key.
        private_key: For a Media CDN key, this is a 64-byte Ed25519 private
                     key encoded as a base64-encoded string.
                     See https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
                     for more information. For a Cloud CDN key, this is a base64-encoded string secret.
        is_cloud_cdn: If true, update a Cloud CDN key. If false, update a Media CDN key.

    Returns:
        The CDN key resource.
    """

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/cdnKeys/{cdn_key_id}"

    cdn_key = stitcher_v1.types.CdnKey(
        name=name,
        hostname=hostname,
    )

    if is_cloud_cdn:
        cdn_key.google_cdn_key = stitcher_v1.types.GoogleCdnKey(
            key_name=key_name,
            private_key=private_key,
        )
        update_mask = field_mask.FieldMask(paths=["hostname", "google_cdn_key"])
    else:
        cdn_key.media_cdn_key = stitcher_v1.types.MediaCdnKey(
            key_name=key_name,
            private_key=private_key,
        )
        update_mask = field_mask.FieldMask(paths=["hostname", "media_cdn_key"])

    operation = client.update_cdn_key(cdn_key=cdn_key, update_mask=update_mask)
    response = operation.result()
    print(f"Updated CDN key: {response.name}")
    return response

Ruby

在試用這個範例之前,請先按照Ruby使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Ruby API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/video/stitcher"

##
# Update a Media CDN or Cloud CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] The user-defined CDN key ID
# @param hostname [String] The hostname to which this CDN key applies
# @param key_name [String] For a Media CDN key, this is the keyset name.
#   For a Cloud CDN key, this is the public name of the CDN key.
# @param private_key [String] For a Media CDN key, this is a 64-byte Ed25519
#   private key encoded as a base64-encoded string. See
#   https://cloud.google.com/video-stitcher/docs/how-to/managing-cdn-keys#create-private-key-media-cdn
#   for more information. For a Cloud CDN key, this is a base64-encoded string
#   secret.
# @param is_media_cdn [Boolean] If true, update a Media CDN key. If false,
#                               update a Cloud CDN key.
#
def update_cdn_key project_id:, location:, cdn_key_id:, hostname:, key_name:,
                   private_key:, is_media_cdn:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the path for the CDN key resource.
  cdn_key_path = client.cdn_key_path project: project_id, location: location,
                                     cdn_key: cdn_key_id

  # Set the CDN key fields.
  new_cdn_key = if is_media_cdn
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    media_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                else
                  {
                    name: cdn_key_path,
                    hostname: hostname,
                    google_cdn_key: {
                      key_name: key_name,
                      private_key: private_key
                    }
                  }
                end

  update_mask = if is_media_cdn
                  { paths: ["hostname", "media_cdn_key"] }
                else
                  { paths: ["hostname", "google_cdn_key"] }
                end

  operation = client.update_cdn_key cdn_key: new_cdn_key,
                                    update_mask: update_mask

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print the CDN key name.
  puts "Updated CDN key: #{operation.response.name}"
end

列出所有已註冊的 CDN 金鑰

如要列出專案中特定位置註冊的所有 CDN 金鑰,請使用 projects.locations.cdnKeys.list 方法。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:CDN 金鑰所在位置;請使用支援的區域之一。
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "cdnKeys": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
      "hostname": "HOSTNAME",
      "mediaCdnKey": {
        "keyName": "MEDIA_CDN_KEYNAME"
      }
    },
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
      "hostname": "HOSTNAME",
      "googleCdnKey": {
        "keyName": "GCDN_KEYNAME"
      }
    },
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/my-other-cdn-key",
      "hostname": "my-other-hostname",
      "akamaiCdnKey": {}
    }
  ]
}

C#

在試用這個範例之前,請先按照C#使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API C# API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Stitcher.V1;
using System;

public class ListCdnKeysSample
{
    public PagedEnumerable<ListCdnKeysResponse, CdnKey> ListCdnKeys(
        string projectId, string regionId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        ListCdnKeysRequest request = new ListCdnKeysRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, regionId)
        };

        // Make the request.
        PagedEnumerable<ListCdnKeysResponse, CdnKey> response = client.ListCdnKeys(request);
        foreach (CdnKey cdnKey in response)
        {
            Console.WriteLine($"{cdnKey.Name}");
        }

        // Return the result.
        return response;
    }
}

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Go API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
	"google.golang.org/api/iterator"
)

// listCDNKeys gets all of the CDN keys for a given location.
func listCDNKeys(w io.Writer, projectID string) error {
	// projectID := "my-project-id"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.ListCdnKeysRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListCdnKeys(ctx, req)
	fmt.Fprintln(w, "CDN keys:")
	for {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("it.Next(): %w", err)
		}
		fmt.Fprintln(w, response.GetName())
	}

	return nil
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Java API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.ListCdnKeysRequest;
import com.google.cloud.video.stitcher.v1.LocationName;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient.ListCdnKeysPagedResponse;
import java.io.IOException;

public class ListCdnKeys {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";

    listCdnKeys(projectId, location);
  }

  // Lists the CDN keys for a given project and location.
  public static ListCdnKeysPagedResponse listCdnKeys(String projectId, String location)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      ListCdnKeysRequest listCdnKeysRequest =
          ListCdnKeysRequest.newBuilder()
              .setParent(LocationName.of(projectId, location).toString())
              .build();

      VideoStitcherServiceClient.ListCdnKeysPagedResponse response =
          videoStitcherServiceClient.listCdnKeys(listCdnKeysRequest);

      System.out.println("CDN keys:");
      for (CdnKey cdnKey : response.iterateAll()) {
        System.out.println(cdnKey.getName());
      }
      return response;
    }
  }
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Node.js API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function listCdnKeys() {
  const iterable = await stitcherClient.listCdnKeysAsync({
    parent: stitcherClient.locationPath(projectId, location),
  });
  console.info('CDN keys:');
  for await (const response of iterable) {
    console.log(response.name);
  }
}

listCdnKeys().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在試用這個範例之前,請先按照PHP使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API PHP API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\ListCdnKeysRequest;

/**
 * Lists all CDN keys for a location.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the CDN keys
 */
function list_cdn_keys(
    string $callingProjectId,
    string $location
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $request = (new ListCdnKeysRequest())
        ->setParent($parent);
    $response = $stitcherClient->listCdnKeys($request);

    // Print the CDN key list.
    $cdn_keys = $response->iterateAllElements();
    print('CDN keys:' . PHP_EOL);
    foreach ($cdn_keys as $key) {
        printf('%s' . PHP_EOL, $key->getName());
    }
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Python API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import argparse

from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    pagers,
    VideoStitcherServiceClient,
)


def list_cdn_keys(project_id: str, location: str) -> pagers.ListCdnKeysPager:
    """Lists all CDN keys in a location.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN keys.

    Returns:
        An iterable object containing CDN key resources.
    """

    client = VideoStitcherServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    response = client.list_cdn_keys(parent=parent)
    print("CDN keys:")
    for cdn_key in response.cdn_keys:
        print({cdn_key.name})

    return response

Ruby

在試用這個範例之前,請先按照Ruby使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Ruby API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/video/stitcher"

##
# List CDN keys for a given location
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
#
def list_cdn_keys project_id:, location:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the parent.
  parent = client.location_path project: project_id, location: location

  response = client.list_cdn_keys parent: parent

  puts "CDN keys:"
  # Print out all CDN keys.
  response.each do |cdn_key|
    puts cdn_key.name
  end
end

其他結果

curl 回應可能包含 nextPageToken,可用於擷取其他結果:

{
  "cdnKeys": [
    ...
  ],
  "nextPageToken": "NEXT_PAGE_TOKEN"
}

您可以傳送另一個 curl 要求 (包括 NEXT_PAGE_TOKEN 的值),列出其他 CDN 金鑰。在上述 API 呼叫的網址中附加下列內容:

?pageToken=NEXT_PAGE_TOKEN

如要進一步瞭解如何使用這個權杖,請參閱相關的用戶端程式庫

刪除 CDN 金鑰

如果不再需要已註冊的 CDN 金鑰,請使用 projects.locations.cdnKeys.delete 方法刪除。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_NUMBER:您的 Google Cloud 專案編號;這位於「IAM Settings」(IAM 設定) 頁面的「Project number」(專案編號) 欄位中
  • LOCATION:CDN 金鑰所在位置; 請使用其中一個支援的區域
    顯示地區
    • us-central1
    • us-east1
    • us-west1
    • asia-east1
    • asia-south1
    • asia-southeast1
    • europe-west1
    • southamerica-east1
  • CDN_KEY_ID:CDN 金鑰的使用者定義 ID

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.common.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_NUMBER/locations/LOCATION/cdnKeys/CDN_KEY_ID",
    "verb": "delete",
    "cancelRequested": false,
    "apiVersion": "v1"
  },
  "done": false
}
這個指令會建立長時間執行的作業 (LRO),您可以查詢該作業來追蹤進度。詳情請參閱「檢查結果」。

C#

在試用這個範例之前,請先按照C#使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API C# API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using Google.Cloud.Video.Stitcher.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class DeleteCdnKeySample
{
    public async Task DeleteCdnKeyAsync(
        string projectId, string location, string cdnKeyId)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        DeleteCdnKeyRequest request = new DeleteCdnKeyRequest
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId)
        };

        // Make the request.
        Operation<Empty, OperationMetadata> response = await client.DeleteCdnKeyAsync(request);

        // Poll until the returned long-running operation is complete.
        await response.PollUntilCompletedAsync();
    }
}

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Go API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	stitcherstreampb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// deleteCDNKey deletes a CDN key.
func deleteCDNKey(w io.Writer, projectID, keyID string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID)

	req := &stitcherstreampb.DeleteCdnKeyRequest{
		Name: name,
	}
	// Deletes the CDN key.
	op, err := client.DeleteCdnKey(ctx, req)
	if err != nil {
		return fmt.Errorf("client.DeleteCdnKey: %w", err)
	}
	err = op.Wait(ctx)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Deleted CDN key")
	return nil
}

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Java API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.video.stitcher.v1.CdnKeyName;
import com.google.cloud.video.stitcher.v1.DeleteCdnKeyRequest;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteCdnKey {

  private static final int TIMEOUT_IN_MINUTES = 2;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String cdnKeyId = "my-cdn-key-id";

    deleteCdnKey(projectId, location, cdnKeyId);
  }

  // Deletes a CDN key.
  public static void deleteCdnKey(String projectId, String location, String cdnKeyId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (VideoStitcherServiceClient videoStitcherServiceClient =
        VideoStitcherServiceClient.create()) {
      DeleteCdnKeyRequest deleteCdnKeyRequest =
          DeleteCdnKeyRequest.newBuilder()
              .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
              .build();

      videoStitcherServiceClient
          .deleteCdnKeyAsync(deleteCdnKeyRequest)
          .get(TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
      System.out.println("Deleted CDN key");
    }
  }
}

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Node.js API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// cdnKeyId = 'my-cdn-key';

// Imports the Video Stitcher library
const {VideoStitcherServiceClient} =
  require('@google-cloud/video-stitcher').v1;
// Instantiates a client
const stitcherClient = new VideoStitcherServiceClient();

async function deleteCdnKey() {
  // Construct request
  const request = {
    name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
  };
  const [operation] = await stitcherClient.deleteCdnKey(request);
  await operation.promise();
  console.log('Deleted CDN key');
}

deleteCdnKey().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

在試用這個範例之前,請先按照PHP使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API PHP API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\DeleteCdnKeyRequest;

/**
 * Deletes a CDN key.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $location             The location of the CDN key
 * @param string $cdnKeyId             The ID of the CDN key
 */
function delete_cdn_key(
    string $callingProjectId,
    string $location,
    string $cdnKeyId
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $formattedName = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $request = (new DeleteCdnKeyRequest())
        ->setName($formattedName);
    $operationResponse = $stitcherClient->deleteCdnKey($request);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        // Print status
        printf('Deleted CDN key %s' . PHP_EOL, $cdnKeyId);
    } else {
        $error = $operationResponse->getError();
        // handleError($error)
    }
}

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Python API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import argparse

from google.cloud.video.stitcher_v1.services.video_stitcher_service import (
    VideoStitcherServiceClient,
)
from google.protobuf import empty_pb2 as empty


def delete_cdn_key(project_id: str, location: str, cdn_key_id: str) -> empty.Empty:
    """Deletes a CDN key.
    Args:
        project_id: The GCP project ID.
        location: The location of the CDN key.
        cdn_key_id: The user-defined CDN key ID."""

    client = VideoStitcherServiceClient()

    name = f"projects/{project_id}/locations/{location}/cdnKeys/{cdn_key_id}"
    operation = client.delete_cdn_key(name=name)
    response = operation.result()
    print("Deleted CDN key")
    return response

Ruby

在試用這個範例之前,請先按照Ruby使用用戶端程式庫的 Video Stitcher API 快速入門中的設定說明操作。 詳情請參閱 Video Stitcher API Ruby API 參考說明文件

如要向 Video Stitcher API 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/video/stitcher"

##
# Delete a CDN key
#
# @param project_id [String] Your Google Cloud project (e.g. `my-project`)
# @param location [String] The location (e.g. `us-central1`)
# @param cdn_key_id [String] Your CDN key name (e.g. `my-cdn-key`)
#
def delete_cdn_key project_id:, location:, cdn_key_id:
  # Create a Video Stitcher client.
  client = Google::Cloud::Video::Stitcher.video_stitcher_service

  # Build the resource name of the CDN key.
  name = client.cdn_key_path project: project_id, location: location,
                             cdn_key: cdn_key_id

  # Delete the CDN key.
  operation = client.delete_cdn_key name: name

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  operation.wait_until_done!

  # Print a success message.
  puts "Deleted CDN key"
end

輪替 CDN 金鑰

如要輪替 CDN 金鑰,請按照下列步驟操作:

  1. 在所需 CDN (例如 Media CDN) 中新增金鑰。
  2. 在 Video Stitcher API 中註冊新金鑰。此時,Video Stitcher API 會使用舊金鑰或新金鑰簽署資源。這兩個金鑰都是 CDN 的有效憑證。
  3. 在 Video Stitcher API 中刪除舊的 CDN 金鑰。

    Video Stitcher API 會快取舊的 CDN 金鑰。快取通常會在 5 分鐘內過期。快取過期後,Video Stitcher API 只會使用新金鑰簽署資源。您可以檢查資源是否仍可存取,驗證新金鑰是否正常運作。

  4. 從所需 CDN 移除舊金鑰。

  5. 確認 Video Stitcher API 傳回的簽署 URI 仍有效且可存取。