Mettre à jour une clé CDN

Mettre à jour une ressource de clé CDN d'assembleur vidéo.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Avant d'essayer cet exemple, suivez les instructions de configuration pour C# du guide de démarrage rapide de l'API Video Stitcher à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API C# de l'outil de montage vidéo.

Pour vous authentifier auprès de l'API Video Stitcher, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Avant d'essayer cet exemple, suivez les instructions de configuration de Go dans le Guide de démarrage rapide de l'API Video Stitcher avec bibliothèques clientes. Pour en savoir plus, consultez les API Go de l'API Video Stitcher documentation de référence.

Pour vous authentifier auprès de l'API Video Stitcher, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java du guide de démarrage rapide de l'API Video Stitcher à l'aide des bibliothèques clientes. Pour en savoir plus, consultez les API Java de l'API Video Stitcher documentation de référence.

Pour vous authentifier auprès de l'API Video Stitcher, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Avant d'essayer cet exemple, suivez les instructions de configuration de Node.js dans le Guide de démarrage rapide de l'API Video Stitcher avec bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Node.js de l'outil de montage vidéo.

Pour vous authentifier auprès de l'API Video Stitcher, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Avant d'essayer cet exemple, suivez les instructions de configuration pour PHP du guide de démarrage rapide de l'API Video Stitcher à l'aide des bibliothèques clientes. Pour en savoir plus, consultez les API PHP de l'API Video Stitcher documentation de référence.

Pour vous authentifier auprès de l'API Video Stitcher, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python du guide de démarrage rapide de l'API Video Stitcher à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Python de l'outil de montage vidéo.

Pour vous authentifier auprès de l'API Video Stitcher, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Avant d'essayer cet exemple, suivez les instructions de configuration pour Ruby du guide de démarrage rapide de l'API Video Stitcher à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Ruby de l'outil de montage vidéo.

Pour vous authentifier auprès de l'API Video Stitcher, configurez les identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.