Buat kunci CDN Akamai baru

Aset video biasanya didistribusikan menggunakan jaringan penayangan konten (CDN) yang dikenal sebagai CDN. Untuk melindungi konten, URL aset video dapat memerlukan tanda tangan agar dapat diambil; ini dikenal sebagai penandatanganan URL. Buat kunci CDN untuk mengaktifkan akses API ke aset video.

Contoh kode

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di panduan memulai Video Stitcher API menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Video Stitcher API.

Untuk mengautentikasi ke Video Stitcher API, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.