I want to use video on demand service of Alibaba cloud for video streaming.
video on demand makes different resolution videos from uploaded videos for data streaming.
For that, I am using https://github.com/aliyun/aliyun-openapi-php-sdk.
Now problem is that I don't know how to upload video in a video on demand panel via code. I have checked in a https://github.com/aliyun/aliyun-openapi-php-sdk/blob/master/aliyun-php-sdk-vod/vod/Request/V20170321/CreateUploadVideoRequest.php but haven't found field or parameter which is used to upload video. If any other SDK or code is there then please let me know. Even any document of a code or snippet is also appreciated.
Sample code snippet could be found here (in Simplified Chinese though): https://help.aliyun.com/document_detail/61069.html
<?php
include_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php'; //source php and aliyun-php-sdk in same directory
use vod\Request\V20170321 as vod;
function init_vod_client($accessKeyId, $accessKeySecret) {
$regionId = 'cn-shanghai';
$profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
return new DefaultAcsClient($profile);
}
function create_upload_video($client) {
$request = new vod\CreateUploadVideoRequest();
$request->setTitle("VideoTitle"); // Video Title (Mandatory)
$request->setFileName("filename.mov"); // Source document file name with file extension (Mandatory)
$request->setDescription("Video Description"); // Video Description (Optional)
$request->setCoverURL("http://img.alicdn.com/tps/XXXXXXXXXXXXXXXXXXXXXXXXXXX-700-700.png"); // Custom video coverpage (Optional)
$request->setTags("Tag1,Tag2"); // Video tags, separated by commas (Optional)
$request->setAcceptFormat('JSON');
return $client->getAcsResponse($request);
}
try {
$client = init_vod_client('<AccessKeyId>', '<AccessKeySecret>');
$uploadInfo = create_upload_video($client);
var_dump($uploadInfo);
} catch (Exception $e) {
print $e->getMessage()."\n";
}
?>
There is also a demo for using OSS SDK to upload video available in https://help.aliyun.com/document_detail/61388.html (also in Simplified Chinese)
Hope this helps.
Please find the code snippet.
<?php
require_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php';
require_once './aliyun-php-sdk/aliyun-oss-php-sdk-2.2.4/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
function init_vod_client($accessKeyId, $accessKeySecret) {
$regionId = 'cn-shanghai';
$profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
return new DefaultAcsClient($profile);
}
function create_upload_video($vodClient) {
$request = new vod\CreateUploadVideoRequest();
$request->setTitle("Movie");
$request->setFileName("elephant.mov");
$request->setDescription("It is about elephant");
$request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png");
$request->setTags("forest,elephant");
return $vodClient->getAcsResponse($request);
}
function refresh_upload_video($vodClient, $videoId) {
$request = new vod\RefreshUploadVideoRequest();
$request->setVideoId($videoId);
return $vodClient->getAcsResponse($request);
}
function init_oss_client($uploadAuth, $uploadAddress) {
$ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
false, $uploadAuth['SecurityToken']);
$ossClient->setTimeout(86400*7);
$ossClient->setConnectTimeout(10);
return $ossClient;
}
function upload_local_file($ossClient, $uploadAddress, $localFile) {
return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}
function multipart_upload_file($ossClient, $uploadAddress, $localFile) {
return $ossClient->multiuploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}
$accessKeyId = '<AccessKeyId>';
$accessKeySecret = '<AccessKeySecret>';
$localFile = '/Users/yours/Video/testVideo.flv';
try {
$vodClient = init_vod_client($accessKeyId, $accessKeySecret);
$createRes = create_upload_video($vodClient);
$videoId = $createRes->VideoId;
$uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
$uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
$ossClient = init_oss_client($uploadAuth, $uploadAddress);
//$result = upload_local_file($ossClient, $uploadAddress, $localFile);
$result = multipart_upload_file($ossClient, $uploadAddress, $localFile);
printf("Succeed, VideoId: %s", $videoId);
} catch (Exception $e) {
// var_dump($e);
printf("Failed, ErrorMessage: %s", $e->getMessage());
}
For more details, Please have a look at the official documentation
Here is the newest code update on 202105 for you.
the guide link as below:
https://www.alibabacloud.com/help/doc-detail/100976.htm?spm=a2c63.p38356.879954.13.330a12fcc5cLMD#task-1995280
<? php
/**
* Created by Aliyun ApsaraVideo VOD.
*/
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';
date_default_timezone_set('PRC');
// Test the upload of an on-premises video.
function testUploadLocalVideo($accessKeyId, $accessKeySecret, $filePath)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
//$uploadVideoRequest->setCateId(1);
//$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
//$uploadVideoRequest->setTags('test1,test2');
//$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
//$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289326');
$userData = array(
"MessageCallback"=>array("CallbackURL"=>"https://demo.sample.com/ProcessMessageCallback"),
"Extend"=>array("localId"=>"xxx", "test"=>"www")
);
$uploadVideoRequest->setUserData(json_encode($userData));
$res = $uploader->uploadLocalVideo($uploadVideoRequest);
print_r($res);
} catch (Exception $e) {
printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Tests the upload of an online video.
function testUploadWebVideo($accessKeyId, $accessKeySecret, $fileURL)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($fileURL, 'testUploadWebVideo via PHP-SDK');
$res = $uploader->uploadWebVideo($uploadVideoRequest);
print_r($res);
} catch (Exception $e) {
printf("testUploadWebVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Test the upload of an on-premises M3U8 video.
function testUploadLocalM3u8($accessKeyId, $accessKeySecret, $m3u8FilePath)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($m3u8FilePath, 'testUploadLocalM3u8 via PHP-SDK');
// Call the method for parsing the M3U8 playlist to obtain the URLs of parts. If the parsing result is invalid, manually assemble the URLs of parts. By default, the part files and M3U8 files are stored in the same directory.
$sliceFiles = $uploader->parseM3u8File($m3u8FilePath);
//print_r($sliceFiles);
$res = $uploader->uploadLocalM3u8($uploadVideoRequest, $sliceFiles);
print_r($res);
} catch (Exception $e) {
printf("testUploadLocalM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
// Test the upload of an online M3U8 video.
function testUploadWebM3u8($accessKeyId, $accessKeySecret, $m3u8FileUrl)
{
try {
$uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
$uploadVideoRequest = new UploadVideoRequest($m3u8FileUrl, 'testUploadWebM3u8 via PHP-SDK');
// Call the method for parsing the M3U8 playlist to obtain the URLs of parts. If the parsing result is invalid, manually assemble the URLs of parts. By default, the part files and M3U8 files are stored in the same directory.
$sliceFileUrls = $uploader->parseM3u8File($m3u8FileUrl);
//print_r($sliceFileUrls);
$res = $uploader->uploadWebM3u8($uploadVideoRequest, $sliceFileUrls);
print_r($res);
} catch (Exception $e) {
printf("testUploadWebM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
$e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
}
}
#### Run the test code. ####
$accessKeyId = '<AccessKeyId>';
$accessKeySecret = '<AccessKeySecret>';
//$localFilePath = 'C:\test\sample.mp4';
$localFilePath = '/opt/video/sample.mp4';
//testUploadLocalVideo($accessKeyId, $accessKeySecret, $localFilePath);
$webFileURL = 'http://vod-test1.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc95c8/daa30814c0c340cf8199926f78aa5c0e-a0bc05ba62c3e95cc672e88b828148c9-ld.mp4?auth_key=1608774986-0-0-c56acd302bea0c331370d8ed686502fe';
testUploadWebVideo($accessKeyId, $accessKeySecret, $webFileURL);
$localM3u8FilePath = '/opt/video/m3u8/sample.m3u8';
//testUploadLocalM3u8($accessKeyId, $accessKeySecret, $localM3u8FilePath);
$webM3u8FileURL = 'http://vod-test1.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc95c8/daa30814c0c340cf8199926f78aa5c0e-195a25af366b5edae324c47e99a03f04-ld.m3u8?auth_key=1608775606-0-0-9fb038deaecd009dadd86721c5855629';
//testUploadWebM3u8($accessKeyId, $accessKeySecret, $webM3u8FileURL);
Related
Using SquareConnect's PHP Sdk, I am trying to create a very basic variant product using their API.
`
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
//print out the objectid. Works perfectly!
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
//now create the variant and it will fail
$var_api = new \SquareConnect\Api\V1ItemsApi();
$variation = new \SquareConnect\Model\V1Variation(); // \SquareConnect\Model\V1Variation | An object containing the fields to POST for the request. See the corresponding object definition for field details.
$variation->setName("JERSUB");
$variation->setSku("JERSUPPERSKU");
try {
$meresult = $var_api->createVariation($location_id, $object_id, $variation);
print_r($meresult);
} catch (Exception $e) {
echo 'Exception when calling V1ItemsApi->createVariation: ', $e->getMessage(), PHP_EOL;
}
`
No matter what I do I always get a 400 Bad request.
Exception when calling V1ItemsApi->createVariation: [HTTP/1.1 400 Bad Request] {"type":"bad_request","message":"BadRequest"}
I have tried just passing in a blank variation object like the documentation, but it still does not work. How do I get around or diagnose the error?
I was using an older V1 version of the API. I found an OO way of doing it that was actually smarter. Below is a snippet that should hopefully help someone.
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
$clone=$results[0];
$clone->setId("#TEMP123"); //change it to a temp id
$clone->setType("ITEM_VARIATION");
$id=$clone->getId();
$var_data=$clone->getItemVariationData();
//now clear/update the cloned object
$var_data->setName(UPC_FIELD_NAME);
$var_data->setSku("SUPPERSKU_TEST2"); //update sku
$var_data->setPricingType("VARIABLE_PRICING");
$var_data->setTrackInventory(null);
$var_data->setLocationOverrides(null); //got to remove location ovverides or it will track.
$var_data->setPriceMoney(null);
$clone->setItemVariationData($var_data);
//upsert it
$upsert=new \SquareConnect\Model\UpsertCatalogObjectRequest();
//set unique key
$upsert->setIdempotencyKey(md5(time()));
$upsert->setObject($clone);
//fire the update
$update_result=$api_instance->upsertCatalogObject($upsert);
I have created following code. I have to download files from my Google Drive folder. The folder is shared. After downloading, I have to delete those files from the Google Drive.
I tried -
$file = $service->parents->delete($file_id,$folder_id); - It doesn't do anything, nor does it give any error.
$file = $service->files->trash($file_id); - It gives Error calling DELETE - (403) Insufficient permissions for this file" Error.
My code :
<?php
require_once "google/google-api-php-client/src/Google_Client.php";
require_once "google/google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google/google-api-php-client/src/contrib/Google_Oauth2Service.php";
require_once "google/vendor/autoload.php";
$file_id = '1bJm_cqIRVh5RaVrqVXGRL0CSYwTBlZur';
$folder_id='1gEllj4B9TCnLPe_dnl1ujX4u8smLL-Ky';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'service_account_email#domain.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'GoogleDriveApi-7cd8056e9eae.p12';
function buildService() {//function for first build up service
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
function printFilesInFolder($service, $folderId) {
$pageToken = NULL;
$arrayFile=array();
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$children = $service->children->listChildren($folderId, $parameters);
$arrayFile=$children;
$pageToken = $children->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $arrayFile;
}
try {
$service = buildService();
$children=printFilesInFolder($service,$folder_id);
$myfile = fopen("D:/list.txt", "wb") or die("Unable to open file!");
foreach ($children->getItems() as $child) {
print "\r\nFile Id: " . $child->getId();
fwrite($myfile, $child->getId());
fwrite($myfile, "\r\n");
}
$file = $service->parents->delete($file_id,$folder_id);
$file = $service->files->trash($file_id);
fclose($myfile);
} catch (Exception $e) {
print "An error occurred1: " . $e->getMessage();
}
?>
Your error indicates that the user doesn't have a write access to the file, and an app is attempting to modify the particular file.
Suggested action: Report to the user that there is a need to ask for
those permissions in order to update the file. You may also want to
check user access levels in the metadata retrieved by
files.get and use that to change your UI to a read only UI.
I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??
Trying below code for deleting files from google storage but getting the error "An error occurred: (delete) missing required param: 'object'". I am sending the filesId like this $fileId = 1458180875815000.
$google-api-php-client :- getting the google service
// code for delete
$bucketName = "bucketname";
$googleServiceStorage = new Google_Service_Storage($this->client);
//$googleServiceStorage = new Google_Service_Storage_StorageObject();
try
{
$googleServiceStorage->objects->delete($bucketName,$companyId,
[
'object' => $companyId."/".$objectName,
'generation' => $fileId,
'alt' => "media"
]
);
//$bucketName,$companyId,$objectName,$fileId);
}
catch (Exception $e)
{
print "An error occurred: " . $e->getMessage();
}
}
Here is how I am deleting files from GCS
$bucket = 'my_main_bucket';
$file = 'path/to/file/image.jpg';
$this->service = new Google_Service_Storage($this->client);
try
{
$this->service->objects->delete($bucket, $file);
}
catch (Google_Service_Exception $e)
{
syslog(LOG_ERR, $e);
}
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.