Google_Http_REST::decodeHttpResponse throws exception unexpectedly - google-drive-api

We are using PHP client: "google/apiclient": "1.0.4-beta" to upload a CSV to our google drive. Our script was working before, but stop working now. We haven't change anything. We tried dev, staging, production Google Product ID, all throw same error. Is there any problem on API side ? or there is some problem on our script ?
Exception :
#0 /home/dev/workspace/fb/vendor/google/apiclient/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/dev/workspace/fb/vendor/google/apiclient/src/Google/Client.php(499): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/dev/workspace/fb/vendor/google/apiclient/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /home/dev/workspace/fb/vendor/google/apiclient/src/Google/Service/Drive.php(1694): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /home/dev/workspace/fb/app/modules/Core/Models/Report/Generator/Spreadsheet/Google.php(53): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 /home/dev/workspace/fb/app/modules/Core/Models/Report/Manager.php(69): Core\Models\Report\Generator\Spreadsheet\Google->insert('report_21_test_...', Array)
#6 /home/dev/workspace/fb/app/modules/Core/Commands/Report/GenerateByQuery.php(55):
......
Our Code:
$client = new \Google_Client();
$client->setClientId($apiConfig['clientId']);
$client->setAssertionCredentials(new \Google_Auth_AssertionCredentials(
$apiConfig['accountName'],
array('https://www.googleapis.com/auth/drive'),
$key
));
$this->service = new \Google_Service_Drive($client);
$date = date("Y-m-d H:i:s");
// slice to max rows
$data = array_slice($data, 0, self::MAX_ROWS);
// generate spreadsheet with filename and data
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle("$filename");
$file->setDescription("Report generate at $date");
$file->setMimeType(self::MIME_TYPE_ORIGINAL);
$csvStr = $this->getCsvString($data);
$createdFile = $this->service->files->insert($file, array(
'data' => $csvStr,
'mimeType' => self::MIME_TYPE_GOOGLE,
'uploadType' => 'multipart',
'convert' => true,
)); // exception is from here
// set permission
$this->service->permissions->insert($createdFile->getId(), $this->getPermission());

This was a temporary problem and it is now fixed.

Related

Laravel storage fake appears to be not working in github actions

Locally everything works great:
Storage::fake('local');
$file = UploadedFile::fake()->image('watch.jpg');
$watchData = [
'model' => 'beatae unde adipisci',
'size' => '50',
'number' => 'm98300',
'metal' => 'deserunt',
'rrp' => '92840',
'status' => 'discontinued',
'brand_id' => '2',
'new_image' => $file,
];
$response = $this->post('/watch', $watchData);
Storage::disk('local')->assertExists('mg/jc-int/watch-images/1.jpg');
When I try to run this same test as part of my deployment workflow in GitHub Actions:
1) Tests\Feature\WatchImagesTest::test_a_watch_image_can_be_created
Unable to find a file or directory at path [mg/jc-int/watch-images/1.jpg].
Failed asserting that false is true.
I've tried a few things but I think this is more that I'm not understand how either Storage::fake() works or how GitHub actions handles filepaths?
Found the issue.
In my controller that handles the image upload, I'm grabbing a folder from my config:
$folder = config('site.DO_SUBFOLDER');
This value is taken from my .env and wasn't being included in the deployment pipeline.

Cakephp4 don't accept Content Type application/json; charset=utf-8

I upgrade my application from Cakephp3 to cakephp4 but unfortunately I am unable to update the android app accordingly due to logistic issues. The android app makes HTTP calls with Content-Type application/json; charset=utf-8 and cakephp4 keeps throwing bad request. Is there a way to get cakephp4 to accept this header as a stop gap measure before I collect all the tablets and update them accordingly?
Below is the error log:
1) App\Test\TestCase\Controller\Api\EmployeesControllerTest::testJwtTokenPost
Possibly related to Cake\Http\Exception\BadRequestException: "Bad Request"
#0 /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php(73): Cake\Http\Middleware\BodyParserMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
#1 /var/www/html/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php(166): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
#2 /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php(73): Cake\Routing\Middleware\RoutingMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
#3 /var/www/html/vendor/cakephp/cakephp/src/Routing/Middleware/AssetMiddleware.php(68): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
#4 /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php(73): Cake\Routing\Middleware\AssetMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
#5 /var/www/html/vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php(121): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
#6 /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php(73): Cake\Error\Middleware\ErrorHandlerMiddleware->process(Object(Cake\Http\ServerRequest), Object(Cake\Http\Runner))
#7 /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php(58): Cake\Http\Runner->handle(Object(Cake\Http\ServerRequest))
#8 /var/www/html/vendor/cakephp/cakephp/src/Http/Server.php(90): Cake\Http\Runner->run(Object(Cake\Http\MiddlewareQueue), Object(Cake\Http\ServerRequest), Object(App\Application))
#9 /var/www/html/vendor/cakephp/cakephp/src/TestSuite/MiddlewareDispatcher.php(190): Cake\Http\Server->run(Object(Cake\Http\ServerRequest))
#10 /var/www/html/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestTrait.php(499): Cake\TestSuite\MiddlewareDispatcher->execute(Array)
#11 /var/www/html/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestTrait.php(401): App\Test\TestCase\Controller\Api\EmployeesControllerTest->_sendRequest('/api/employees/...', 'POST', Array)
#12 /var/www/html/tests/TestCase/Controller/Api/EmployeesControllerTest.php(41): App\Test\TestCase\Controller\Api\EmployeesControllerTest->post('/api/employees/...', Array)
#13 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(1415): App\Test\TestCase\Controller\Api\EmployeesControllerTest->testJwtTokenPost()
#14 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(1035): PHPUnit\Framework\TestCase->runTest()
#15 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestResult.php(691): PHPUnit\Framework\TestCase->runBare()
#16 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(763): PHPUnit\Framework\TestResult->run(Object(App\Test\TestCase\Controller\Api\EmployeesControllerTest))
#17 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestSuite.php(597): PHPUnit\Framework\TestCase->run(Object(PHPUnit\Framework\TestResult))
#18 /var/www/html/vendor/phpunit/phpunit/src/TextUI/TestRunner.php(627): PHPUnit\Framework\TestSuite->run(Object(PHPUnit\Framework\TestResult))
#19 /var/www/html/vendor/phpunit/phpunit/src/TextUI/Command.php(204): PHPUnit\TextUI\TestRunner->doRun(Object(PHPUnit\Framework\TestSuite), Array, Array, true)
#20 /var/www/html/vendor/phpunit/phpunit/src/TextUI/Command.php(163): PHPUnit\TextUI\Command->run(Array, true)
#21 /var/www/html/vendor/phpunit/phpunit/phpunit(61): PHPUnit\TextUI\Command::main()
#22 {main}
and below is the token method
public function token()
{
$this->getRequest()->allowMethod('post');
$employee = $this->Employees
->find()
->select(['Employees.id','Employees.project_id', 'Employees.name'])
->where(['Employees.pin_code' => $this->request->getData('pin_code')])
->firstOrFail()
->toArray();
$sites = TableRegistry::getTableLocator()->get('Sites');
$currentSite = array('id' => 0, 'name'=> 0);
$currentTransactionId = 0;
$transactions = TableRegistry::getTableLocator()->get('Transactions');
$previousTransaction = $transactions->find()->where([
'Transactions.employee_id' => $employee['id']
])->order([
'Transactions.created' => 'DESC'
])->first();
if(!empty($previousTransaction) && empty($previousTransaction->photo_out)) {
$currentSite = $sites->get($previousTransaction->site_id);
$currentTransactionId = $previousTransaction->id;
}
$this->set([
'success' => true,
'employee' => $employee,
'current_site' => $currentSite,
'sites' => $sites->find()->matching('Projects', function ($q) use ($employee) {
return $q->where(['Projects.id' => $employee["project_id"]]);
}),
'transaction_id' => $currentTransactionId,
'data' => [
'token' => JWT::encode([
'sub' => $employee['id'],
'exp' => time() + 604800
],
Security::getSalt())
],
]);
// Specify which view vars JsonView should serialize.
$this->viewBuilder()->setOption('serialize', ['success', 'employee', 'current_site', 'sites', 'transaction_id', 'data']);
}
and yes the middleware is set up in src/Application.php
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(Configure::read('Error')))
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime'),
]))
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance. For that when
// creating the middleware instance specify the cache config name by
// using it's second constructor argument:
// `new RoutingMiddleware($this, '_cake_routes_')`
->add(new RoutingMiddleware($this))
// Parse various types of encoded request bodies so that they are
// available as array through $request->getData()
// https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
->add(new BodyParserMiddleware())
// Cross Site Request Forgery (CSRF) Protection Middleware
// https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware
// ->add(new CsrfProtectionMiddleware([
// 'httponly' => false,
// ]))
// Add the middleware to the middleware queue
->add(new AuthenticationMiddleware($this));
return $middlewareQueue;
}
and below is the test method
public function testJwtTokenPost() {
$this->configRequest([
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8'
]
]);
// $this->enableCsrfToken();
$this->post('/api/employees/token', [
'pin_code' => '1001'
]);
$this->assertResponseOk();
$this->assertResponseContains('success');
$this->assertResponseContains('employee');
$this->assertResponseContains('current_site');
$this->assertResponseContains('transaction_id');
$this->assertResponseContains('sites');
$this->assertResponseContains('data');
}
Below is my postman json call
When testing non-application/x-www-form-urlencoded requests you must pass the data as a string, as the test case can't reliably make assumptions about how to possibly transform the data into a string itself.
ie, pass a JSON string as POST data, not an array, a string is how application/json data would be exposed by PHP for an actual HTTP request:
$this->post('/api/employees/token', json_encode([
'pin_code' => '1001'
]));
There's no need to further configure the body parser middleware for this, it supports JSON out of the box.

Logstash - How to trigger Celery tasks through RabbitMQ

Can someone explain to me how I can trigger Celery tasks through Logstash?
Is it possible?
If I try to do that in PHP through the 'php-amqplib' library it works fine: (without using Logstash)
$connection = new AMQPStreamConnection(
'rabbitmq.local',
5672,
'guest',
'guest'
);
$channel = $connection->channel();
$channel->queue_declare(
'celery',
false,
true,
false,
false
);
$taskId = rand(1000, 10000);
$props = array(
'content_type' => 'application/json',
'content_encoding' => 'utf-8',
);
$body = array(
'task' => 'process_next_task',
'lang' => 'py',
'args' => array('ktest' => 'vtest'),
'kwargs' => array('ktest' => 'vtest'),
'origin' => '#'.'mytest',
'id' => $taskId,
);
$msg = new AMQPMessage(json_encode($body), $props);
$channel->basic_publish($msg, 'celery', 'celery');
According to the Celery docs:
http://docs.celeryproject.org/en/latest/internals/protocol.html
I'm trying to send the request in the json format, this is my Logstash filter:
ruby
{
remove_field => ['headers', '#timestamp', '#version', 'host', 'type']
code => "
event.set('properties',
{
:content_type => 'application/json',
:content_encoding => 'utf-8'
})
"
}
And Celery answer is:
[2017-05-05 14:35:09,090: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!
{content_type:None content_encoding:None delivery_info:{'exchange': 'celery', 'routing_key': 'celery', 'redelivered': False, 'consumer_tag': 'None4', 'delivery_tag': 66} headers={}}
Basically, Celery is not able to decode my message format or better... I'm not able to set the request in the JSON format :)
It's driving me crazy, thank you in advance for any clues :)
Forgot it, this is my output plugin in Logstash
rabbitmq
{
key => "celery"
exchange => "celery"
exchange_type => "direct"
user => "${RABBITMQ_USER}"
password => "${RABBITMQ_PASSWORD}"
host => "${RABBITMQ_HOST}"
port => "${RABBITMQ_PORT}"
durable => true
persistent => true
codec => json
}
From the information provided in this question, you can't.
When you're playing with the event in the ruby filter, you're actually playing with what will be put in the body of the message, while you'd like to set the rabbitmq headers and properties of your message.
Till that functionality has been tackled, I do not think you'll be able to achieve it unless of course you implement it yourself. After all, the plugin is available on github.
As Olivier said, right now is not possible but I've created a pull request to the official project.
https://github.com/logstash-plugins/logstash-output-rabbitmq/pull/59
If you are looking for a working version take a look to my clone:
https://github.com/useless-stuff/logstash-output-rabbitmq
You should be seriously scared about that code :)
I'm completely far away to be a Ruby developer
But it works :)

Through an error using Unisharp laravel file manager

i have update laravel 5.3 to 5.4 than i got this error for using laravel filemanager package Unisharp.
FatalErrorException in ItemsController.php line 0: Method
Illuminate\View\View::__toString() must not throw an exception, caught
ErrorException: Cannot use object of type stdClass as array (View:
ProjectName\resources\views\vendor\laravel-filemanager\item.blade.php)
(View:
ProjectName\resources\views\vendor\laravel-filemanager\item.blade.php)
return [
'html' => (string)view($this->getView())->with([
'files' => $files,
'directories' => $directories,
'items' => array_merge($directories, $files)
]),
'working_dir' => parent::getInternalPath($path)
];
add in the vendor views item.blade.php in the line 0
<?php $file = json_decode(json_encode($file),true) ; ?>

Laravel save image using dropzone.js into MySQL

I'm just trying out dropzone for the first time and would need assistance to set it up. I am getting error 500 thus:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is the controller:
public function storeDocument(Request $request){
$file = $request->file('file');
$fileName = uniqid().$file->getClientOriginalName();
$file->move('gallery/images', $fileName);
$productVerificationValidation = ProductVerificationValidation::findOrFail($request->productDocumentNameId);
$documentsUploaded = $productVerificationValidation->productDocumentUpload()->create([
'gallery_id' => $request->productDocumentNameId,
'user_id' => Auth::user()->id,
'company_id' => $request->company_id,
'product_id' => $request->product_id,
'file_name' => $fileName,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => 'gallery/images'. $fileName
]);
}
This is the route to store the image credentials:
Route::post('product/document/upload/save', array('before'=>'csrf', 'uses'=>'ProductVerificationValidationController#storeDocument'));
This is the form for Dropzone:
<form action="{{url('product/document/upload/save' )}}"
class="dropzone first-input-div" id="addImages">{{csrf_field()}}
{!!Form::hidden('productDocumentNameId', $productVerificationValidation->id)!!}
{!!Form::hidden('product_id', $productVerificationValidation->product_id)!!}
{!!Form::hidden('company_id', $productVerificationValidation->company_id)!!}</form>
This is the model setup:
public function productDocumentUpload(){
return $this->hasMany('App\ProductDocumentUpload');
}
I'm yet to understand what I need to do right. Please help out.