Skip to content

Using the API to Automate Publishing of New AutoGraph-Protected Video ​

All the steps explained in the AutoGraph walkthrough can also be performed programmatically via the Xvid MediaHub API. So we can:

  1. Obtain an API access token using client_id and client_secret of an application previously created in the MediaHub GUI ("Apps" tab). An API access token is needed to perform requests to protected API endpoints.
  2. Import and encode a new video with AutoGraph watermark-protection enabled. Video prepared like this is ready for AutoGraphed distribution.
  3. Obtain the file id of the newly created video files and generate AutoGraph-protected download links.

The PHP example code below demonstrates how to perform these three steps using the API and can also be run from the command line (or you can easily use the helper functions also from a PHP web application):

post_job_and_get_download.php

php
<?php
// Some constant
$api_url = "https://api.xvid.com";

// Helper function to make REST API calls using curl
function make_api_call($url, $method="GET", $data=null, $format=null) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    if ($data) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    if (strtoupper($method) == "POST") {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        if ($format && strtoupper($format) == "JSON") {
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data))
            );
        }
    }
    $curl_response = json_decode(curl_exec($curl), true); // Needs error checking in a real application...
    curl_close($curl);
    return $curl_response;
}

// Obtaining an API access token valid for '$valid_for' seconds
function get_oauth_token($clientid, $clientsecret, $valid_for) {
    global $api_url;
    $auth_api_url = $api_url . '/v1/oauth2/token/';
    $params = array(
         "scope" => 'mediahub,autograph',
         "grant_type" => 'client_credential',
         "client_id" => $clientid,
         "client_secret" => urlencode($clientsecret),
         );
    // url-ify our params for the POST
    $params_string = '';
    foreach($params as $key=>$value) { $params_string .= $key.'='.$value.'&'; }
    rtrim($params_string, '&');
    // prepare the request url and make the call
    $url = $auth_api_url . '?' . 'human=true&expires_in=' . $valid_for;
    $api_response = make_api_call($url, "POST", $params_string);
    if (array_key_exists('access_token', $api_response)) {
        return $api_response['access_token'];
    }
    return null;
}

// Post a job to convert input video specified by '$input_url'
// Polls for status until the job is done and then returns file_id of the newly created output file
function perform_autograph_job($input_url, $api_token) {
    global $api_url;
    $job_api_url = $api_url . '/v1/jobs/';
    // Get a pipeline ID - this is not really needed. You can hardcode a pipeline ID that you like to use with your job POSTs just as well...
    $pipelines = make_api_call($api_url . '/v1/pipelines/?access_token=' . $api_token);
    // Prepare the job data to post to the API
    $job_data = array("output_prefix" => "{job_id}/", // Unique output folder per Job
                      "pipeline" => array("id" => $pipelines['pipelines'][0]['id']),
                      "input" => array("input_name" => $input_url),
                      "autograph" => array("watermark_strength" => "light"), // Enable AutoGraph watermark-protection
                      "outputs" => array());
    // One output in this example - but you can do also more than one per Job
    $job_data['outputs'][0] = array("output_name" => "autograph_test", // the name of our converted output file (without file extension)
                                    "preset" => array("id" => "52a6bbdfa2ca79055aaa787a")); // pre-defined H.264 demo preset

    // Append the access token as query param to the request url and make the API call
    $url = $job_api_url . '?human=true&access_token=' . $api_token;
    $api_response = make_api_call($url, "POST", json_encode(array("job" => $job_data)), "json");

    // Extract id of the new Job
    $api_response = $api_response['job'];
    $job_id = $api_response['id'];
    // Let's poll for the job status until it is done
    while(($api_response['status'] != 'SUCCESS') && ($api_response['status'] != 'FAILURE')) {
        sleep(30);
        $url = $job_api_url . $job_id . '?human=true&access_token=' . $api_token;
        $api_response = make_api_call($url);
        $api_response = $api_response['job'];
        echo "Encoding Video..." . $api_response['percentage_completed'] . "%" . "\r";
    }
    // Return the file id of our first (and only) output
    return $api_response['outputs'][0]['file']['id'];
};

function get_signed_download_link($file_id, $tag, $valid_for, $client_id, $client_secret) {
    global $api_url;
    $download_api_url = '/v1/files/downloads/';
    // Compute the expiry time of the link
    $expiry = time();
    $expiry = $expiry - ($expiry % 3600) + $valid_for; // Round to nearest hour, then add the validity (in seconds)
    // Add file_id, tag, expiry_time and client_id as params
    $download_api_url .= "?file_id=" . $file_id . "&client_id=" . $client_id . "&autograph_tag=" . $tag . "&expiry_time=" . $expiry;
    $download_api_url .= "&redirect=true&multi_use=true"; // Redirect and start the download right away
    // Compute and append the HMAC signature. Prepend the api_url as the hostname to complete the link
    return $api_url . $download_api_url . "&signature=" . hash_hmac('sha256', $download_api_url, base64_decode($client_secret));
}


// Test call with args from CLI
// Invoke with: php -f ./post_job_and_get_download.php Input_URL Client_ID Client_Secret
// Check we're invoked with all params...
if ($argc < 4) {
    echo "Usage: php -f ./post_job_and_get_download.php Input_URL Client_ID Client_Secret\n\n";
    echo "Parameters:\n";
    echo "    Input_URL     - URL of input video to encode\n";
    echo "    Client_ID     - Client_ID of an application in your account\n";
    echo "    Client_Secret - Client_Secret of an application in your account\n";
    echo "\n";
    echo "Example:\n";
    echo "php -f ./post_job_and_get_download.php http://s3-eu-west-1.amazonaws.com/xmc-test-videos/kingdom_of_heaven_m720p.mov 58f4b56ae4b08cfadca75636 RZT5SvFcmhcQvXq6bD8Q1BLiThKwbnvkVsdZsutSQ7EUsiOS1O9uJctmVA2BukDj\n";
    exit(1);
}

echo "Obtaining API Access Token...";
$api_token = get_oauth_token($argv[2], $argv[3], 6*3600); // Token will be valid for 6 hrs. So you can cache it and re-use it to make many API calls.

if ($api_token) {
    echo "OK\n";
    echo "Encoding Video...0%\r";
    $output_file_id = perform_autograph_job($argv[1], $api_token);
    echo "\nFile ID of newly encoded video is " . $output_file_id . "\n";
    echo "Signing Download Link using sample Tag 'TEST': \n";
    echo get_signed_download_link($output_file_id, "TEST", 6*3600, $argv[2], $argv[3]); // Valid for 6*3600 sec = 6 hrs
} else {
    echo "FAILED\n";
}
?>