I am trying to get images from s3 bucket but it is not working . i have searched a google lot but cant find any solution for this.
Simply what i want is that, i want images from the s3 bucket and view them in html page .
here is how i am doing this. i am using codeigniter for this. these images are private thats why i am doing this.
hope you can help me .
if ($info['photo']!='')
{
$awsAccessKey = 'access_key'; //AWS account access key
$awsSecretKey = 'secret_key'; //AWS account secret key
$s3 = new S3($awsAccessKey, $awsSecretKey);
try
{
$command = $s3->getObject('bajwa-staging', 'IMG20191013221832.jpg');
//The period of availability
$request = $s3->createPresignedRequest($command, '+20 minutes');
//Get the pre-signed URL
$signedUrl = (string) $request->getUri();
}
catch (Exception $e)
{
echo 'Message: ' .$e->getMessage();
exit;
}
}
Related
I am trying to record the video and upload into the aws s3 server. Vuejs as front end and php Laravel as backend, I was not using any conversion before saving it to s3. Due to this if any recording recorded from android cannot be played in apple device due to some codecs..
To over come this, I am using ffmpeg to encode in X264() format to make it play in apple and android device regardless on which device the recording is done.
1 min video taking 6-7 minutes using ffmpeg. I thought may be aws s3 taking time to save, i commented "saving to s3 bucket code" still very slow to save temp public folder in php.
please check the code if i am missing anything to make conversion quick. if any solution update answer with reference link or code snippet with reference to my code below.
public function video_upload(Request $request)
{
// Response Declaration
$response=array();
$response_code = 200;
$response['status'] = false;
$response['data'] = [];
// Validation
// TODO: Specify mimes:mp4,webm,ogg etc
$validator = Validator::make(
$request->all(), [
'file' => 'required'
]
);
if ($validator->fails()) {
$response['data']['validator'] = $validator->errors();
return response()->json($response);
}
try{
$file = $request->file('file');
//convert
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($file);
$format = new X264();
//end convert
$file_name = str_replace (' ', '-', Hash::make(time()));
$file_name = preg_replace('/[^A-Za-z0-9\-]/', '',$file_name).'.mp4';
$video->save($format, $file_name);
$file_folder = 'uploads/video/';
// Store the file to S3
// $store = Storage::disk('s3')->put($file_folder.$file_name, file_get_contents($file));
$store = Storage::disk('s3')->put($file_folder.$file_name, file_get_contents($file_name));
if($store){
// Replace old file if exist
//delete the file from public folder
$file = public_path($file_name);
if (file_exists($file)) {
unlink($file);
}
if(isset($request->old_file)){
if(Storage::disk('s3')->exists($file_folder.basename($request->old_file))) {
Storage::disk('s3')->delete($file_folder.basename($request->old_file));
}
}
}
$response['status'] = true;
$response['data']= '/s3/'.$file_folder. $file_name;
}catch (\Exception $e) {
$response['data']['message']=$e->getMessage()."line".$e->getLine();
$response_code = 400;
}
return response()->json($response, $response_code);
}
Its blocking point for me. I cannot let user to wait 5-6 mins to upload 1 min video.
I am using the square api to search my orders using the following code:
require '../connect-php-sdk-master/autoload.php';
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('MY_AUTH_CODE');
//settings for the searchOrders
$searchOrdersSettings = ([
'location_ids'=>['MY_LOCATION_ID']
]);
$apiInstance = new SquareConnect\Api\OrdersApi();
$body = new \SquareConnect\Model\SearchOrdersRequest($searchOrdersSettings); // \SquareConnect\Model\SearchOrdersRequest | An object containing the fields to POST for the request. See the corresponding object definition for field details.
try {
$result = $apiInstance->searchOrders($body);
/* echo '<pre>';
print_r($result);
echo '<pre>'; */
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->searchOrders: ', $e->getMessage(), PHP_EOL;
}
I would like to set a created_at start and end date but I have no idea how to create 'An object containing the fields to POST for the request'. Can anyone help me out?
Per the Square PHP SDK documentation, you would need to set the query and filter of the query. You can do something like this (tested and working as a small snippet):
require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('ACCESS_TOKEN_HERE');
$apiInstance = new \SquareConnect\Api\OrdersApi();
$body = new \SquareConnect\Model\SearchOrdersRequest();
$body->setLocationIds(['LOCATION_ID_HERE']);
// create query for searching by date
$query = new \SquareConnect\Model\SearchOrdersQuery();
$filter = new \SquareConnect\Model\SearchOrdersFilter();
$date_time_filter = new \SquareConnect\Model\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt([
"start_at" => "2020-03-01T00:00:00Z",
"end_at" => "2020-03-13T00:00:00Z"
]);
//pass the filter and query to the request
$filter->setDateTimeFilter($date_time_filter);
$query->setFilter($filter);
$body->setQuery($query);
try {
$result = $apiInstance->searchOrders($body);
error_log(var_dump($result));
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->searchOrders: ', $e->getMessage(), PHP_EOL;
}
I want to make functionality for users to upload video on my channel without authentication (if needed). IS it possible ?
Please help me .
Thanks
OM
Yes Omprakash,it is possible
You will need Google APIs Client Library for PHP.
You will also need to create a project on
https://console.developers.google.com/ and get credentials(i.e
client secret & client id).
Finally,you will need to generate access token for specific channel.
Please take a look at this link
(https://youtube-eng.googleblog.com/2013/06/google-page-identities-and-youtube-api_24.html)
to generate access token.
Once you have all these things ready with you,you can use ready made
example code available in Google APIs Client Library for PHP to upload
video on YouTube.
Note: This is not in detail process.It is not possible to explain all of the process in detail on stack-overflow. But, once you get close to solution,you can re-post or put comment for further assistance.
This is example code to upload video on YouTube. Hope, it will help you
/*include google libraries */
require_once '../api/src/Google/autoload.php';
require_once '../api/src/Google/Client.php';
require_once '../api/src/Google/Service/YouTube.php';
$application_name = 'Your application/project name created on google developer console';
$client_secret = 'Your client secret';
$client_id = 'Your client id';
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
try{
$key = file_get_contents('the_key.txt'); //it stores access token obtained in step 3
$videoPath = 'video path on your server goes here';
$videoTitle = 'video title';
$videoDescription = 'video description';
$videoCategory = "22"; //please take a look at youtube video categories for videoCategory.Not so important for our example
$videoTags = array('tag1', 'tag2','tag3');
// Client init
$client = new Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
$client->setClientSecret($client_secret);
if ($client->getAccessToken()) {
/**
* Check to see if our access token has expired. If so, get a new one and save it to file for future use.
*/
if($client->isAccessTokenExpired()) {
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('the_key.txt', $client->getAccessToken());
}
$youtube = new Google_Service_YouTube($client);
// Create a snipet with title, description, tags and category id
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($videoTitle);
$snippet->setDescription($videoDescription);
$snippet->setCategoryId($videoCategory);
$snippet->setTags($videoTags);
// Create a video status with privacy status. Options are "public", "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->setPrivacyStatus('public');
// Create a YouTube video with snippet and status
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
/**
* Video has successfully been upload, now lets perform some cleanup functions for this video
*/
if ($status->status['uploadStatus'] == 'uploaded') {
$youtube_id = $status->id; //you got here youtube video id
} else {
// handle failere here
}
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(true);
} else{
// #TODO Log error
echo 'Problems creating the client';
}
} catch(Google_Service_Exception $e) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
} catch (Exception $e) {
echo "\r\n Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
echo "\r\n Stack trace is ".$e->getTraceAsString();
}
I'm totally new to Google Cloud Storage (since I used Amazon S3 until now).
I want to set up my web application, so that users can download files directly from the Google Cloud Storage.
I've already tried it, using the Google Api PHP Client, but didn't get a functionally code.
I've uploaded a test file named "test.jpg" to my bucket "test-bucket-46856" which I want to download via signed url (so that users only have time limited access), but I have no idea how to get this started.
Please help. Thanks.
//Edit:
Found the perfect solution. Here the link for all others who are also searching for this solution:
https://gist.github.com/stetic/c97c94a10f9c6b591883
<?php
/*
* PHP Example for Google Storage Up- and Download
* with Google APIs Client Library for PHP:
* https://github.com/google/google-api-php-client
*/
include( "Google/Client.php" );
include( "Google/Service/Storage.php" );
$serviceAccount = "1234-xyz#developer.gserviceaccount.com";
$key_file = "/path/to/keyfile.p12";
$bucket = "my_bucket";
$file_name = "test.txt";
$file_content = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/devstorage.read_write'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$storageService = new Google_Service_Storage( $client );
/***
* Write file to Google Storage
*/
try
{
$postbody = array(
'name' => $file_name,
'data' => $file_content,
'uploadType' => "media"
);
$gsso = new Google_Service_Storage_StorageObject();
$gsso->setName( $file_name );
$result = $storageService->objects->insert( $bucket, $gsso, $postbody );
print_r($result);
}
catch (Exception $e)
{
print $e->getMessage();
}
/***
* Read file from Google Storage
*/
try
{
$object = $storageService->objects->get( $bucket, $file_name );
$request = new Google_Http_Request($object['mediaLink'], 'GET');
$signed_request = $client->getAuth()->sign($request);
$http_request = $client->getIo()->makeRequest($signed_request);
echo $http_request->getResponseBody();
}
catch (Exception $e)
{
print $e->getMessage();
}
I have created the php script below that uploads videos to youtube and it uploads fine.
I would like to be able to set advanced settings to the uploaded video as follows:
Allow comments should be "approved" not "All"
I also need to be able to set the video location(this would come from
the database from my site)
I should also need to be able to set the recording date(to the date
of the upload)
I also don't want the video statistics to be publicly visible
I have looked around, but i cannot find any documentation on this from google, and i think google have not provided complete documentation for the API.
Any links will also do. Thanks
require_once '../google_api/Google_Client.php';
require_once '../google_api/contrib/Google_YouTubeService.php';
$OAUTH2_CLIENT_ID = '514750847005.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = '9mvQL0NPv1zEOty0tZw71O4t';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri("{$redirect}");
$youtube = new Google_YoutubeService($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
try {
$snippet = new Google_VideoSnippet();
$snippet->setTitle($title);
$snippet->setDescription($desc);
$snippet->setTags($tags);
$snippet->setCategoryId(22);
$status = new Google_VideoStatus();
$status->privacyStatus = "public";
$today = date("Y-m-d\TH:i:s");
$recordingDetails = new Google_VideoRecordingDetails();
$recordingDetails->setRecordingDate($today);
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$video->setRecordingDetails($recordingDetails);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Create a MediaFileUpload with resumable uploads
$media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
$media->setFileSize(filesize($vd_file));
// Create a video insert request
$insertResponse = $youtube->videos->insert("status,snippet", $video, array('mediaUpload' => $media));
$uploadStatus = false;
// Read file and upload chunk by chunk
$handle = fopen($vd_file, "rb");
while (!$uploadStatus && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$uploadStatus = $media->nextChunk($insertResponse, $chunk);
}
fclose($handle);
msg_add('suces', 'message', 'Youtube video upload was successful');
} catch (Google_ServiceException $e) {
$message = sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
msg_add('err', 'message', $message);
} catch (Google_Exception $e) {
$message = sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
msg_add('err', 'message', $message);
}
What you are doing is simply a video->insert call. You are editing snippet, status and recordingDetails. You can do more by adding the other fields to the VIDEOS resource.
Fill in any field of the VIDEOS resource before inserting, that should do.
I ran across a similar situation where I was trying to set the location on insert but it was not working. I got my code to correctly set location by including "recordingDetails" in the part parameter which is a comma separated list (docs). I am using C#, so for me it looks like this:
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status,recordingDetails", fileStream, "video/*");
From your sample it looks like in php this would be
$insertResponse = $youtube->videos->insert("status,snippet,recordingDetails", $video, array('mediaUpload' => $media));
Allow comments should be "approved" not "All"
It seems that's a youtube bug:
https://code.google.com/p/gdata-issues/issues/detail?id=7664