Amazon S3 Multiple Part Upload Returns NULL - php

I am trying to upload an 8GB file, but it constantly returns null. I also do not get an error message no exceptions thrown. The null is displayed in the va_dump, the normal s3 -> putObject works fine with files under 5GB. My code is the following:
$s3 = S3Client::factory(array(
'credentials' => array(
'secret' => 'xxx',
'key' => 'xxxxx'
),
'region' => 'us-west-2',
'version' => '2006-03-01'
));;
try {
if(filesize($body) < 5000000000) {
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $obect,
'SourceFile' => $body,
'ContentType' => $content_type,
'ACL' => $acl,
));
return $result['ObjectURL'];
} else {
echo 'Starting Uploads';
$source = fopen($body, 'rb');
$uploader = new MultipartUploader($s3, $source
, [
'bucket' => $bucket,
'key' => $obect,
'acl' => $acl,
'concurrency' => 5,
'part_size' => (100 * 1024 * 1024),
'before_initiate' => function(\Aws\Command $command) use ($content_type) {
$command['ContentType'] = $content_type; // video/mp4
}
]);
echo 'Into Upload';
$result = $uploader->upload();
echo 'Complete Upload';
var_dump($result);
return (isset($result['Location'])) ? $result['Location'] : false;
}
} catch (MultipartUploadException $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
$uploader = new \Aws\S3\MultipartUploader($s3, $body, [
'state' => $e->getState(),
]);
return false;
} catch (Aws\Exception\S3Exception $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
return false;
} catch (Exception $e) {
error_log($e -> getMessage() . ' ' . $e -> getTraceAsString());
return false;
}
return false;

Related

How to fix time out issue in FCM?

I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?
I have written this code:
// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
try {
$request->validate( [
'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
] );
$originName = $request->file( 'file' )->getClientOriginalName();
$fileName = pathinfo( $originName, PATHINFO_FILENAME );
$extension = $request->file( 'file' )->getClientOriginalExtension();
$fileNames = time() . '.' . $extension;
$request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
$notiData = [
'title' => $request->title,
'body' => $request->body,
'imageurl' => $fileNames
];
// Create a copy in database for notifications.
NotificationTable::create( $notiData );
// Initiate token with https
$notification = [
'title' => $validation->safe()->only( 'title' )['title'],
'body' => $validation->safe()->only( 'body' )['body'],
'image' => 'https://example.com/storage/notification/' . $fileNames
];
$data = [
'first_key' => 'First Value',
'second_key' => 'Second Value',
];
$response[] = '';
foreach ( $deviceTokens as $object ) {
// $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
$message = CloudMessage::fromArray( [
'token' => $object,
'notification' => $notification
] );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( \Throwable $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
} catch ( \Throwable $th ) {
return response()->json( [
'status' => false,
'message' => $th->getMessage()
], 500 );
}}
$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body' => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key' => 'First Value', 'second_key' => 'Second Value',];
$response = array();
foreach ( $deviceTokens as $object ) {
$message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( MessagingException|FirebaseException $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
I want to send messages to all 10k devices but am unable to understand how to do it.

Dont download images yii2

Dont work upload images on yii2... write dont have $addImgFile->extension;...
if i write him .png , i see other error
Exception 'Error' with message 'Call to a member function saveAs() on null'
public function actionMultipleImg()
{
$this->enableCsrfValidation = false;
if (\Yii::$app->request->isPost) {
$post = \Yii::$app->request->post();
$dir = \Yii::getAlias('#productImgPath') . '/additional-image/';
$result_link = str_replace('administrator', '', Url::home(true)) . 'storage/additional-image/';
$addImgFile = UploadedFile::getInstanceByName('ProductImage[attachment]');
$modelProductImage = new ProductImage();
$modelProductImage->filename = strtotime('now') . '_' . \Yii::$app->getSecurity()->generateRandomString(6) . '.'.$addImgFile->extension;
$modelProductImage->load($post);
$modelProductImage->validate();
if ($modelProductImage->hasErrors()) {
$result = ['error' => $modelProductImage->getFirstError('addImgFile')];
} else {
if ($addImgFile->saveAs($dir . $modelProductImage->filename)) {
$imag = \Yii::$app->image->load($dir . $modelProductImage->filename);
$imag->save($dir . $modelProductImage->filename, 90);
$result = ['filelink' => $result_link . $modelProductImage->filename, 'filename' => $modelProductImage->filename];
} else {
$result = ['error' => 'Ошибка'];
}//else
}//else
$modelProductImage->save();
\Yii::$app->response->format = Response::FORMAT_JSON;
return $result;
} else {
throw new BadRequestHttpException('Only POST is allowed');
}
}//action multiple img
my view form where download image
<?php echo FileInput::widget([
'name' => 'ProductImage[attachment]',
'options' => ['accept' => 'image/*','multiple' => true],
'pluginOptions' => [
'deleteUrl' => Url::toRoute(['/product/delete-image']),
'initialPreview' => $model->imagesLinks,
'initialPreviewAsData'=>true,
'overwriteInitial' => false,
'initialPreviewConfig' => $model->imagesLinksData,
'uploadUrl' => Url::to(['/product/multiple-img']),
'uploadExtraData' => [
'ProductImage[product_id]' => $model->id,
],
'maxFileCount' => 10
],
'pluginEvents' => [
'filesorted' => new JsExpression('function(event, params){
$.post("' . Url::toRoute(["/product/sort-image", "id"=>$model->id]) . '", {position:params});
}')
],
]);?>
and its helped
$addImgFile = UploadedFile::getInstanceByName('ProductImage[attachment][0]');

"INVALID_ARGUMENT" when updating or adding a label using the gmail api

I am trying to manage the mail labels using the gmail api the delete does but when I try to add or modify some it tells me that the arguments are invalid.
My code to modify is the following:
public function editLabelGmail(Request $request)
{
try {
$url = 'https://www.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'id' => $request->id,
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
];
$response = Http::asForm()
->put(
$url . '/' . $request->id . '?access_token=' . $token,
$params
)
->json();
return Response($response, 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
And to add:
public function addLabelGmail(Request $request)
{
try {
$url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
'type' => 'user',
];
$response = Http::asForm()
->post($url . '?access_token=' . $token, $params)
->json();
return Response([$response, 'ok'], 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
The parameters I am passing from the front end are coming in as follows:
{
"id": "Label_3",
"name": "Test3"
}
Solution:
I was able to solve it by replacing the $response with the following:
Method Add:
$response = Http::post($url . '?access_token=' . $token, $params)->json();
Method Update:
$response = Http::put($url . '?access_token=' . $token, $params)->json();

Google Drive File not set expiration time permissions

$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress($value);
$newPermission->setExpirationTime('2018-07-13T16:00:00+05:30');
$newPermission->setType($type);
$newPermission->setRole($role);
my drive storage not storing ExpirationTime
There is some minor changes in v3. Check out this links https://developers.google.com/drive/api/v3/reference/permissions/create https://developers.google.com/drive/api/v3/manage-sharing
https://gist.github.com/bshaffer/9bb2cdccd315880ab52f#file-drive-php-L954
insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Service_Drive_Permission(array(
'type' => $type,
'role' => $role,
'emailAddress' => $value,
'expirationTime' => '2018-08-18T16:00:00+05:30'
));
try {
$created = $service->permissions->create($fileId, $newPermission);
$permissionsId = $created->id;
$updatedPermission = new Google_Service_Drive_Permission(array(
'role' => $role,
'expirationTime' => '2018-08-18T16:00:00+05:30'
));
$updated = $service->permissions->update($fileId, $permissionsId , $updatedPermission, array(
'fields' => 'id, expirationTime'
));
$expirationTime = $updated->expirationTime;
echo "expirationTime : " . $expirationTime;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}

bufferapp always returns me a NULL access_token

Here is the code:
$client_id = '';
$client_secret = '';
$callback_url = '';
$buffer = new BufferApp($client_id, $client_secret, $callback_url);
if (!$buffer->ok) {
echo 'Connect to Buffer!';
} else {
//this pulls all of the logged in user's profiles
$profiles = $buffer->go('/profiles');
if (is_array($profiles)) {
foreach ($profiles as $profile) {
//this creates a status on each one
$buffer->go('/updates/create', array('text' => 'My first status update from bufferapp-php worked!', 'profile_ids[]' => $profile->id));
}
}
}
if (isset($_GET['code']))
{
var_dump($_SESSION['oauth']['buffer']['access_token']);
}
it is an example code, I had to be returned the access_token, but it is NULL
trying to log in I'm redirected to the bufferapp' site, give the access, then I'm redirected back and it is NULL
what's the problem ?
thanks in advance)
the bufferapi code :
class BufferApp {
private $client_id;
private $client_secret;
private $code;
private $access_token;
private $callback_url;
private $authorize_url = 'https://bufferapp.com/oauth2/authorize';
private $access_token_url = 'https://api.bufferapp.com/1/oauth2/token.json';
private $buffer_url = 'https://api.bufferapp.com/1';
public $ok = false;
private $endpoints = array(
'/user' => 'get',
'/profiles' => 'get',
'/profiles/:id/schedules/update' => 'post', // Array schedules [0][days][]=mon, [0][times][]=12:00
'/profiles/:id/updates/reorder' => 'post', // Array order, int offset, bool utc
'/profiles/:id/updates/pending' => 'get',
'/profiles/:id/updates/sent' => 'get',
'/profiles/:id/schedules' => 'get',
'/profiles/:id' => 'get',
'/updates/:id/update' => 'post', // String text, Bool now, Array media ['link'], ['description'], ['picture'], Bool utc
'/updates/create' => 'post', // String text, Array profile_ids, Aool shorten, Bool now, Array media ['link'], ['description'], ['picture']
'/updates/:id/destroy' => 'post',
'/updates/:id' => 'get',
'/links/shares' => 'get',
);
public $errors = array(
'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.',
'403' => 'Permission denied.',
'404' => 'Endpoint not found.',
'405' => 'Method not allowed.',
'1000' => 'An unknown error occurred.',
'1001' => 'Access token required.',
'1002' => 'Not within application scope.',
'1003' => 'Parameter not recognized.',
'1004' => 'Required parameter missing.',
'1005' => 'Unsupported response format.',
'1010' => 'Profile could not be found.',
'1011' => 'No authorization to access profile.',
'1012' => 'Profile did not save successfully.',
'1013' => 'Profile schedule limit reached.',
'1014' => 'Profile limit for user has been reached.',
'1020' => 'Update could not be found.',
'1021' => 'No authorization to access update.',
'1022' => 'Update did not save successfully.',
'1023' => 'Update limit for profile has been reached.',
'1024' => 'Update limit for team profile has been reached.',
'1028' => 'Update soft limit for profile reached.',
'1030' => 'Media filetype not supported.',
'1031' => 'Media filesize out of acceptable range.',
);
public $responses = array(
'403' => 'Permission denied.',
'404' => 'Endpoint not found.',
'405' => 'Method not allowed.',
'500' => 'An unknown error occurred.',
'403' => 'Access token required.',
'403' => 'Not within application scope.',
'400' => 'Parameter not recognized.',
'400' => 'Required parameter missing.',
'406' => 'Unsupported response format.',
'404' => 'Profile could not be found.',
'403' => 'No authorization to access profile.',
'400' => 'Profile did not save successfully.',
'403' => 'Profile schedule limit reached.',
'403' => 'Profile limit for user has been reached.',
'404' => 'Update could not be found.',
'403' => 'No authorization to access update.',
'400' => 'Update did not save successfully.',
'403' => 'Update limit for profile has been reached.',
'403' => 'Update limit for team profile has been reached.',
'403' => 'Update soft limit for profile reached.',
'400' => 'Media filetype not supported.',
'400' => 'Media filesize out of acceptable range.',
);
function __construct($client_id = '', $client_secret = '', $callback_url = '') {
if ($client_id) $this->set_client_id($client_id);
if ($client_secret) $this->set_client_secret($client_secret);
if ($callback_url) $this->set_callback_url($callback_url);
if ($_GET['code']) {
$this->code = $_GET['code'];
$this->create_access_token_url();
}
$this->retrieve_access_token();
}
function go($endpoint = '', $data = '') {
if (in_array($endpoint, array_keys($this->endpoints))) {
$done_endpoint = $endpoint;
} else {
$ok = false;
foreach (array_keys($this->endpoints) as $done_endpoint) {
if (preg_match('/' . preg_replace('/(\:\w+)/i', '(\w+)', str_replace('/', '\/', $done_endpoint)) . '/i', $endpoint, $match)) {
$ok = true;
break;
}
}
if (!$ok) return $this->error('invalid-endpoint');
}
if (!$data || !is_array($data)) $data = array();
$data['access_token'] = $this->access_token;
$method = $this->endpoints[$done_endpoint]; //get() or post()
return $this->$method($this->buffer_url . $endpoint . '.json', $data);
}
function store_access_token() {
$_SESSION['oauth']['buffer']['access_token'] = $this->access_token;
}
function retrieve_access_token() {
$this->access_token = $_SESSION['oauth']['buffer']['access_token'];
if ($this->access_token) {
$this->ok = true;
}
}
function error($error) {
return (object) array('error' => $this->errors[$error]);
}
function create_access_token_url() {
$data = array(
'code' => $this->code,
'grant_type' => 'authorization_code',
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->callback_url,
);
$obj = $this->post($this->access_token_url, $data);
$this->access_token = $obj->access_token;
$this->store_access_token();
}
function req($url = '', $data = '', $post = true) {
if (!$url) return false;
if (!$data || !is_array($data)) $data = array();
$options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false);
if ($post) {
$options += array(
CURLOPT_POST => $post,
CURLOPT_POSTFIELDS => $data
);
} else {
$url .= '?' . http_build_query($data);
}
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$rs = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code >= 400) {
return $this->error($code);
}
return json_decode($rs);
}
function get($url = '', $data = '') {
return $this->req($url, $data, false);
}
function post($url = '', $data = '') {
return $this->req($url, $data, true);
}
function get_login_url() {
return $this->authorize_url . '?'
. 'client_id=' . $this->client_id
. '&redirect_uri=' . urlencode($this->callback_url)
. '&response_type=code';
}
function set_client_id($client_id) {
$this->client_id = $client_id;
}
function set_client_secret($client_secret) {
$this->client_secret = $client_secret;
}
function set_callback_url($callback_url) {
$this->callback_url = $callback_url;
}
}

Categories