Crea una clave de CDN de Akamai nueva

Por lo general, los elementos de video se distribuyen mediante una red de distribución de contenidos, también conocida como CDN. Con el objetivo de proteger el contenido, es posible que las URLs de los recursos de video requieran una firma para poder recuperarse. Esto se conoce como firma de URL. Crea una clave de CDN para habilitar el acceso de la API al activo de video.

Muestra de código

C#

Antes de probar esta muestra, sigue las instrucciones de configuración de C# que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de C# de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

public class CreateCdnKeyAkamaiSample
{
    public async Task<CdnKey> CreateCdnKeyAkamaiAsync(
        string projectId, string location, string cdnKeyId, string hostname,
        string akamaiTokenKey)
    {
        // Create the client.
        VideoStitcherServiceClient client = VideoStitcherServiceClient.Create();

        CdnKey cdnKey = new CdnKey
        {
            Hostname = hostname,
            AkamaiCdnKey = new AkamaiCdnKey
            {
                TokenKey = ByteString.CopyFromUtf8(akamaiTokenKey)
            }
        };

        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

Antes de probar esta muestra, sigue las instrucciones de configuración de Go que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Go de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

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

// createCDNKeyAkamai creates an Akamai CDN key. A CDN key is used to retrieve
// protected media.
func createCDNKeyAkamai(w io.Writer, projectID, keyID, akamaiTokenKey string) error {
	// projectID := "my-project-id"
	// keyID := "my-cdn-key"
	// akamaiTokenKey := "my-private-token-key"
	location := "us-central1"
	hostname := "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.CreateCdnKeyRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		CdnKeyId: keyID,
		CdnKey: &stitcherstreampb.CdnKey{
			CdnKeyConfig: &stitcherstreampb.CdnKey_AkamaiCdnKey{
				AkamaiCdnKey: &stitcherstreampb.AkamaiCdnKey{
					TokenKey: []byte(akamaiTokenKey),
				},
			},
			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

Antes de probar esta muestra, sigue las instrucciones de configuración de Java que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Java de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

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

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

  // createCdnKeyAkamai creates an Akamai CDN key. A CDN key is used to retrieve protected media.
  public static void createCdnKeyAkamai(
      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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    VideoStitcherServiceClient videoStitcherServiceClient = VideoStitcherServiceClient.create();
    CdnKey cdnKey =
        CdnKey.newBuilder()
            .setHostname(hostname)
            .setAkamaiCdnKey(
                AkamaiCdnKey.newBuilder()
                    .setTokenKey(ByteString.copyFromUtf8(akamaiTokenKey))
                    .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());
    videoStitcherServiceClient.close();
  }
}

Node.js

Antes de probar esta muestra, sigue las instrucciones de configuración de Node.js que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Node.js de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

const location = 'us-central1';
const hostname = 'cdn.example.com';
/**
 * 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 createCdnKeyAkamai() {
  // Construct request
  const request = {
    parent: stitcherClient.locationPath(projectId, location),
    cdnKey: {
      hostname: hostname,
      akamaiCdnKey: {
        tokenKey: akamaiTokenKey,
      },
    },
    cdnKeyId: cdnKeyId,
  };

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

createCdnKeyAkamai();

PHP

Antes de probar esta muestra, sigue las instrucciones de configuración de PHP que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de PHP de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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\CreateCdnKeyRequest;

/**
 * Creates 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 create_cdn_key_akamai(
    string $callingProjectId,
    string $location,
    string $cdnKeyId,
    string $hostname,
    string $tokenKey
): void {
    // Instantiate a client.
    $stitcherClient = new VideoStitcherServiceClient();

    $parent = $stitcherClient->locationName($callingProjectId, $location);
    $cdnKey = new CdnKey();
    $cdnKey->setHostname($hostname);
    $cloudCdn = new AkamaiCdnKey();
    $cloudCdn->setTokenKey($tokenKey);
    $cdnKey->setAkamaiCdnKey($cloudCdn);

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

Antes de probar esta muestra, sigue las instrucciones de configuración de Python que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Python de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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_akamai(
    project_id: str,
    location: str,
    cdn_key_id: str,
    hostname: str,
    akamai_token_key: str,
) -> stitcher_v1.types.CdnKey:
    """Creates an Akamai 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.
        akamai_token_key: A base64-encoded string token 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,
        akamai_cdn_key=stitcher_v1.types.AkamaiCdnKey(
            token_key=akamai_token_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

Antes de probar esta muestra, sigue las instrucciones de configuración de Ruby que se encuentran en la Guía de inicio rápido de la API de Video Stitcher con bibliotecas cliente. Si deseas obtener más información, consulta la documentación de referencia de la API de Ruby de la API de Video Stitcher.

Para autenticarte en la API de Video Stitcher, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

require "google/cloud/video/stitcher"

##
# Create 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 create_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 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 = {
    name: cdn_key_path,
    hostname: hostname,
    akamai_cdn_key: {
      token_key: akamai_token_key
    }
  }

  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

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.