更新 Akamai CDN 密钥

更新视频拼接器 Akamai CDN 密钥资源。

代码示例

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 UpdateCdnKeyAkamaiSample
{
    public async Task<CdnKey> UpdateCdnKeyAkamaiAsync(
        string projectId, string location, string cdnKeyId, string hostname,
        string akamaiTokenKey)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            CdnKeyName = CdnKeyName.FromProjectLocationCdnKey(projectId, location, cdnKeyId),
            Hostname = hostname,
            AkamaiCdnKey = new AkamaiCdnKey
            {
                TokenKey = ByteString.CopyFromUtf8(akamaiTokenKey)
            }
        };

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

        // 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

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Go 设置说明进行操作。 有关详情,请参阅 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"
)

// updateCDNKeyAkamai updates an Akamai CDN key. A CDN key is used to retrieve
// protected media.
func updateCDNKeyAkamai(w io.Writer, projectID, keyID, akamaiTokenKey string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// akamaiTokenKey := "my-updated-token-key"
	location := "us-central1"
	hostname := "updated.cdn.example.com"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %w", err)
	}
	defer client.Close()

	req := &stitcherstreampb.UpdateCdnKeyRequest{
		CdnKey: &stitcherstreampb.CdnKey{
			CdnKeyConfig: &stitcherstreampb.CdnKey_AkamaiCdnKey{
				AkamaiCdnKey: &stitcherstreampb.AkamaiCdnKey{
					TokenKey: []byte(akamaiTokenKey),
				},
			},
			Name:     fmt.Sprintf("projects/%s/locations/%s/cdnKeys/%s", projectID, location, keyID),
			Hostname: hostname,
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"hostname", "akamai_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

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Java API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.video.stitcher.v1.AkamaiCdnKey;
import com.google.cloud.video.stitcher.v1.CdnKey;
import com.google.cloud.video.stitcher.v1.CdnKeyName;
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 UpdateCdnKeyAkamai {

  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 akamaiTokenKey = "my-updated-token-key"; // will be converted to a byte string

    updateCdnKeyAkamai(projectId, location, cdnKeyId, hostname, akamaiTokenKey);
  }

  // updateCdnKeyAkamai updates the hostname and key fields for an existing CDN key.
  public static CdnKey updateCdnKeyAkamai(
      String projectId, String location, String cdnKeyId, String hostname, String akamaiTokenKey)
      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 =
          CdnKey.newBuilder()
              .setName(CdnKeyName.of(projectId, location, cdnKeyId).toString())
              .setHostname(hostname)
              .setAkamaiCdnKey(
                  AkamaiCdnKey.newBuilder()
                      .setTokenKey(ByteString.copyFromUtf8(akamaiTokenKey))
                      .build())
              .build();

      UpdateCdnKeyRequest updateCdnKeyRequest =
          UpdateCdnKeyRequest.newBuilder()
              .setCdnKey(cdnKey)
              // Update the hostname field and token key field. You must set the mask to the fields
              // you want to update.
              .setUpdateMask(
                  FieldMask.newBuilder().addPaths("hostname").addPaths("akamai_cdn_key").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';
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// cdnKeyId = 'my-cdn-key';
// akamaiTokenKey = 'my-token-key';

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

async function updateCdnKeyAkamai() {
  // Construct request
  const request = {
    cdnKey: {
      name: stitcherClient.cdnKeyPath(projectId, location, cdnKeyId),
      hostname: hostname,
      akamaiCdnKey: {
        tokenKey: akamaiTokenKey,
      },
    },
    updateMask: {
      paths: ['hostname', 'akamai_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}`);
}

updateCdnKeyAkamai().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\AkamaiCdnKey;
use Google\Cloud\Video\Stitcher\V1\CdnKey;
use Google\Cloud\Video\Stitcher\V1\Client\VideoStitcherServiceClient;
use Google\Cloud\Video\Stitcher\V1\UpdateCdnKeyRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates an Akamai 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 to be created
 * @param string  $hostname           The hostname of the CDN key
 * @param string  $tokenKey           The base64-encoded string token key for
 *                                    the Akamai CDN edge configuration
 */
function update_cdn_key_akamai(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $tokenKey
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $name = $stitcherClient->cdnKeyName($callingProjectId, $location, $cdnKeyId);
    $cdnKey = new CdnKey();
    $cdnKey->setName($name);
    $cdnKey->setHostname($hostname);
    $akamaiCdn = new AkamaiCdnKey();
    $akamaiCdn->setTokenKey($tokenKey);
    $cdnKey->setAkamaiCdnKey($akamaiCdn);

    $updateMask = new FieldMask([
        'paths' => ['hostname', 'akamai_cdn_key']
    ]);

    // 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

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 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_akamai(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    akamai_token_key: str,
) -> stitcher_v1.types.CdnKey:
    """Updates an Akamai 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.
        akamai_token_key: A base64-encoded string token 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,
        akamai_cdn_key=stitcher_v1.types.AkamaiCdnKey(
            token_key=akamai_token_key,
        ),
    )
    update_mask = field_mask.FieldMask(paths=["hostname", "akamai_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

在试用此示例之前,请按照 Video Stitcher API 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Video Stitcher API Ruby API 参考文档

如需向 Video Stitcher API 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/video/stitcher"

##
# Update an Akamai 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 akamai_token_key [String] Applies to an Akamai CDN key. A
#   base64-encoded string token key.
#
def update_cdn_key_akamai project_id:, location:, cdn_key_id:, hostname:,
                          akamai_token_key:
  # 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.
  update_mask = { paths: ["hostname", "akamai_cdn_key"] }
  new_cdn_key = {
    name: cdn_key_path,
    hostname: hostname,
    akamai_cdn_key: {
      token_key: akamai_token_key
    }
  }

  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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器