php deleting files from google storage using google-api-php-client - php

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);
}

Related

aws-sdk-s3 PHP ListObjects fails when prefix doesn't exist in bucket

We are using ListObjects with specific prefixes to return keys to process. Some of the prefixes don't exist all the time. Our previous working environment was PHP 7.3 and aws-sdk 3.142.0 and the code worked as expected. If the prefix has data the result would be parsed, if the prefix didn't exist it returned nothing without issue. We have recently upgraded to PHP 8.1.8 and aws-sdk 3.231.8. ListObjects returns the data as expected when the prefix exists, if the prefix doesn't exist the call fails and the code fails and it is not handled by the exception code. The below code processes the listObjects prefix acr/ and then fails on acr_processed/ because the prefix doesn't currently exist in the bucket.
Has anyone seen this or have a workaround? thank you in advance
$prefixarray = array('acr/','acr_processed/'); // NOTE: acr_processed/ doesn't exist
foreach ($prefixarray as $prefix) {
$bucketName = 'abc';
try {
$objects = $s3->ListObjectsV2(['Bucket' => $bucketName,
'Prefix' => $prefix
]);
} catch (S3Exception $e) {
echo "there was a S3 exception";
} catch (Exception $e) {
echo 'there was an exception';
}
foreach ($objects['Contents'] as $contents) {
echo $contents['Key'] . "<br>";
}
}
The issue is Addressed, call it a workaround because the error 500 still returns if a prefix doesn't exist when you try and list it. With these current versions of PHP and Asw-sdk.
To fix create a dummyobject in the prefix being listed prior to the listing of the prefix. The process is HeadObject to see if the dummyobject is there, if not putObject in the prefix and then list the prefix. The dummyobject will be returned but it is easy to skip when processing the list results.
$tagstring = 'status=placeholder';
$dummykeyName = $prefix . 'placeholder.prefix';
try {
// head a s3 object:
$result = $s3->headObject([
'Bucket' => $bucketName,
'Key' => $dummykeyName
]);
// found
$NoResults = 'no';
} catch (S3Exception $e) {
die('s3 Error:' . $e->getMessage());
} catch (Exception $e) { // placeholder.prefix was not found put it
try {
$s3->putObject(
array(
'Bucket' => $bucketName,
'Key' => $dummykeyName,
'ContentType' => 'text/xml',
'Tagging' => $tagstring,
'StorageClass' => $strgclass
)
);
} catch (S3Exception $e) {
echo 'there was an S3 exception ' . $dummykeyName . '<br>';
$NoResults = 'yes';
} catch (Exception $e) {
echo 'there was an exception ' . $dummykeyName . '<br>';
$NoResults = 'yes';
}
}
// get the list of objects from the bucket
try {
$objects = $s3->ListObjectsV2(['Bucket' => $bucketName,
'Prefix' => $prefix
]);
} catch (S3Exception $e) {
$e->getMessage();
echo "<tr><td>list-enduser error" . $e . "</td></tr>";
$NoResults = 'yes';
} catch (Exception $e) {
echo 'there was an exception';
$NoResults = 'yes';
}

Using the Google Drive API for PHP, What is the proper way to upload a file while setting the "keepRevisionForever" to true?

I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

Alibaba cloud - video streaming

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);

Error calling DELETE - (403) Insufficient permissions for this file" | Google Drive API

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.

Error when changing a post privacy with the Facebook PHP SDK

What I'm doing is creating a post with the Facebook PHP SDK(v4)(and the app is set to use the v2.3 API) with the privacy settings of value to SELF, then later on changing the value to CUSTOM, and allow to the ids of the friends that have accepted the app.
Until recently everything worked fine, and now out of the blue I'm getting this error(nothing changed on our part): "(#100) Object does not support message editing", which I couldn't locate in their documentation. Has anybody encountered this situation and this error?
Here is the code I'm using (like I said everything worked fine until recently)(if you need more details please let me know)
$fb_token = 'FB_TOKEN';
$FB_session = new FacebookSession($fb_token);
try {
$FB_session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
//echo $ex->getMessage();
throw new RestException(501,'FB error: '. $ex->getMessage());
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
//echo $ex->getMessage();
throw new RestException(501,'FB error: '. $ex->getMessage());
}
//make posting request to FB
if($FB_session) {
try {
$fb_array = array(
'privacy' => array(
'value' => 'CUSTOM',
'allow' => 'USER_ID'
)
);
$fb_req = new FacebookRequest(
$FB_session, 'POST', "/POST_ID", $fb_array
);
$response = $fb_req->execute()->getGraphObject();
//echo "Posted with id: " . $response->getProperty('id');
$fb_post_id = $response->getProperty('id');
} catch(FacebookRequestException $e) {
//echo "Exception occured, code: " . $e->getCode();
//echo " with message: " . $e->getMessage();
throw new RestException(501,'FB error: '. $e->getCode() .'-'. $e->getMessage());
}
}

Categories