Google Apiclient, Google Drive, after uploaded file empty - php

I upload file some formats and in google drive have file with empty body. Why not understand
I install google api client
"name": "google/apiclient",
"version": "1.1.7",
and try upload file in google dics
I get access token help with HWIO bundle, add scope
scope:
"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/drive"
and get accesToken like this
{"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
"expires_in":3600, "id_token":"TOKEN", "created":1320790426}
beign I try upload exist file (doc, pdf, img)
$client = $this->get('artel.google.api.client');
/** #var CodeUserReference[] $accessToken */
$accessToken = $this->get('doctrine.orm.entity_manager')->getRepository('ArtelProfileBundle:CodeUserReference')
->getReferenceAccessClient($user);
if ($accessToken) {
$client->setAccessToken($accessToken[0]->getAccessTokenClient());
} else {
$view = $this->view(['No accessToken was found for this user id'], 400);
return $this->handleView($view);
}
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setName($request->request->get('title')
? $request->request->get('title')
: $request->files->get('file')->getClientOriginalName()
);
$file->setDescription($request->request->get('description'));
$file->setMimeType($request->request->get('mimeType')
? $request->request->get('mimeType')
: $request->files->get('file')->getClientMimeType()
);
// Set the parent folder.Google_Service_Drive_ParentReferen, this class not find in google/apiclient, version": "1.1.7", I don\'t know why..(
if ($request->request->get('parentId') != null) {
$parent = new Google_Service_Drive_ParentReferen();
$parent->setId($request->request->get('parentId'));
$file->setParents(array($parent));
}
try {
$data = $request->files->get('file');
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => $request->request->get('mimeType')
? $request->request->get('mimeType')
: $request->files->get('file')->getClientMimeType(),
'uploadType' => 'media'
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return View::create()
->setStatusCode(200)
->setData([$createdFile]);
} catch (\Exception $e) {
$view = $this->view((array) $e->getMessage(), 400);
return $this->handleView($view);
}
have response
{
"internal_gapi_mappings": [],
"model_data": [],
"processed": [],
"collection_key": "spaces",
"capabilities_type": "Google_Service_Drive_DriveFileCapabilities",
"capabilities_data_type": "",
"content_hints_type": "Google_Service_Drive_DriveFileContentHints",
"content_hints_data_type": "",
"id": "0B2_i_Tc5Vr8UWV9Jc2psQkhqS3M",
"image_media_metadata_type": "Google_Service_Drive_DriveFileImageMediaMetadata",
"image_media_metadata_data_type": "",
"kind": "drive#file",
"last_modifying_user_type": "Google_Service_Drive_User",
"last_modifying_user_data_type": "",
"mime_type": "application/msword",
"name": "Resume — Symfony Backend Developer, PHP, Shuba Ivan.doc",
"owners_type": "Google_Service_Drive_User",
"owners_data_type": "array",
"permissions_type": "Google_Service_Drive_Permission",
"permissions_data_type": "array",
"sharing_user_type": "Google_Service_Drive_User",
"sharing_user_data_type": "",
"video_media_metadata_type": "Google_Service_Drive_DriveFileVideoMediaMetadata",
"video_media_metadata_data_type": ""
}
all I have in file this:
/tmp/phpaPpHBp
I use this doc v3 because in "name": "google/apiclient", "version": "1.1.7" no find function "insert",
So, mime_type correct but inside emty, only like this - /tmp/phpaPpHBp
I try some uploadType - media, multipart, resumable but stil empty
When try pdf mime_type = application/pdf but still emty
What I\'am doing wrong and why I have emty file in google drive?
anybody, who knows, help

add file_get_content and work fine :
if ($request->request->get('parentId') !== null) {
$parent = new \Google_Service_Drive_ParentReference();
$parent->setId($request->request->get('parentId'));
$file->setParents(array($parent));
}
$insertArray = [
'mimeType' => isset($fileUpload) ? $fileUpload->getClientMimeType() : $request->request->get('mimeType')
];
if (isset($fileUpload)) {
$insertArray ['uploadType'] = 'media';
$insertArray ['data'] = file_get_contents($fileUpload);
}
try {
$createdFile = $service->files->insert($file, $insertArray);
return View::create()
->setStatusCode(200)
->setData([$createdFile]);
} catch (\Exception $e) {
$view = $this->view((array) self::ERROR_OCCURRED . $e->getMessage(), 400);
return $this->handleView($view);
}

Related

Video uploaded through YouTube Data API is becoming private

I have tried uploading a video to YouTube channels using by the YouTube Data API, by composer:
"require": {
"google/apiclient": "^2.7",
"hybridauth/hybridauth": "~3.4.0",
"guzzlehttp/guzzle": "^7.0"
}
The video is uploaded successfully, but YouTube marks every video uploaded into it as private. Does anybody know how to fix this scenario?
public function upload_video_on_youtube($id, $arr_data)
{
$result_data = array();
$channel_id = $id;
$uploaded = false;
$stopper = 0;
while ($uploaded == false && $stopper == 0) {
$arr_data['summary'] = $this->getrandomstring(10);
$arr_data['title'] = $this->getrandomstring(10);
$client = new Google_Client();
$arr_token = $this->getAccessToken($channel_id);
if ($arr_token['error'] == false) {
$res = array();
$accessToken = array(
'access_token' => $arr_token['access_token']
);
$client->setAccessToken($accessToken);
$service = new Google_Service_YouTube($client);
$video = new Google_Service_YouTube_Video();
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setDescription($arr_data['summary']);
$videoSnippet->setTitle($arr_data['title']);
$video->setSnippet($videoSnippet);
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setPrivacyStatus('unlisted');
$video->setStatus($videoStatus);
try {
$response = $service->videos->insert(
'snippet,status',
$video,
array(
'data' => file_get_contents($arr_data['video_path']),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
)
);
if (isset($response->id)) {
$video_id = $response->id;
$res['error'] = false;
$res['response'] = $video_id;
array_push($result_data, $res);
$uploaded = true;
return $result_data;
}
} catch (Exception $e) {
if (401 == $e->getCode()) {
// echo ($arr_token['email'] . " Youtube Access token expired");
$refresh_token = $this->get_refersh_token($channel_id);
$client = new GuzzleHttp\Client(['base_uri' => 'https://accounts.google.com']);
$response = $client->request('POST', '/o/oauth2/token', [
'form_params' => [
"grant_type" => "refresh_token",
"refresh_token" => $refresh_token,
"client_id" => $arr_token['client_id'],
"client_secret" => $arr_token['client_secret'],
],
]);
$data = json_decode($response->getBody());
$data->refresh_token = $refresh_token;
$this->update_access_token($channel_id, json_encode($data));
$uploaded = false;
} elseif (403 == $e->getCode()) {
// echo ($arr_token['email'] . ' Youtube channel quota exceeded');
$channel_id = $channel_id + 1;
$uploaded = false;
}
}
} else if ($arr_token['error'] == true) {
$res['error'] = true;
$res['response'] = "Your Daily Upload Quota is Exceeded";
array_push($result_data, $res);
$stopper = 1;
return $result_data;
}
}
}
If you check the documentation for videos.insert you will see that all videos that are uploaded by apps that have not gone through the verification process will be set to private.
Once you go through the verification process you will be able to set your videos to public
This is an update after some clarity from Google.
At the top of the Video.insert page you will see it states.
Apps that dont need to be verified can just go though an audit is not verification, these are two different things. You need to apply for an audit. YouTube API Services - Audit and Quota Extension Form

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

Amazon Transcribe Streaming service request in PHP or Laravel?

I'm a PHP developer, I would like to use transcribe real time transcriptions, but I haven't found documentation for PHP about this tool, do you have a strength?
For audio translation, I found it, but I didn't find real time.
Below audio conversion example:
//Storage::disk('temp')->get('1.mp3');
// // https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-transcribe-2017-10-26.html
// https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html
public function transcribeVoice(Request $request)
{
$client = AWS::createClient('transcribeService');
$path = 'https://audio-job.s3.us-east-2.amazonaws.com/audio.mp3';
try {
$result = $client->getTranscriptionJob([
'TranscriptionJobName' => 'audio-job'
]);
if ($result['TranscriptionJob']['TranscriptionJobStatus'] == 'IN_PROGRESS') {
return redirect('/')->with('status', 'Progressing now');
} else if ($result['TranscriptionJob']['TranscriptionJobStatus'] == 'COMPLETED') {
$file = file_get_contents($result['TranscriptionJob']['Transcript']['TranscriptFileUri']);
$json = json_decode($file);
$transcript = $json->results->transcripts[0]->transcript;
$client->deleteTranscriptionJob([
'TranscriptionJobName' => 'audio-job', // REQUIRED
]);
return redirect('/transcribeVoice')->with('result', $transcript);
}
} catch (Aws\TranscribeService\Exception\TranscribeServiceException $e) {
$result = $client->startTranscriptionJob([
'LanguageCode' => 'pt-BR', // REQUIRED
'Media' => [ // REQUIRED
'MediaFileUri' => $path,
],
'MediaFormat' => 'mp3', // REQUIRED
'TranscriptionJobName' => 'audio-job', // REQUIRED
]);
return redirect('/transcribeVoice')->with('status', 'Progressing now');
}
}
}
// StartStreamTranscription – Starts a bi-directional HTTP/2 stream where audio is streamed to Amazon Transcribe and the transcription results are streamed to your application.
// https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.TranscribeService.TranscribeServiceClient.html

Google API PHP Update File

I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!

Zend\File\Transfer\Adapter\Http on receive : error "File was not found" with jQuery File Upload

Here is already two questions about this problem
Zf2 file upload by jQuery File Upload - file was not found
Can't get blueimp / jQuery-File-Upload and ZF2 running
without ansers. And i'm create issue on ZF2 with code examples.
github.com/zendframework/zf2/issues/6291
And also have request from another developer on my email with question, how to implement jQuery File Upload with ZF2.
github.com/blueimp/jQuery-File-Upload
So, there is real problem for many peple, and no any manuals, no answers.
Please, before send me to read documentation, notice, that i'm spend many hours on problem and already read all documentation and not only i'm have this problem.
Please, write manual with code examples, like How to implement it. Or just answer, why we have this error and how to resolve it?
There i'm copy my example from ZF2 issue.
I'm try use jQuery-File-Upload
Just copy standard tpl, include css and scrypts and it's work, send files to my controller.
But controller doesn't work.
Here is my code
public function processjqueryAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$jsonModel = new \Zend\View\Model\JsonModel();
if ($request->isPost()) {
try {
$datas = [];
$datas['files'] = [];
$uploadPath = $this->getFileUploadLocation();
$uploadFiles = $this->params()->fromFiles('files');
// throw new \Exception(json_encode("FILES " . serialize($_FILES)));
// Сохранение выгруженного файла
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($uploadPath);
$adapter->setValidators(array(
new \Zend\Validator\File\Extension(array(
'extension' => array('jpg', 'jpeg', 'png', 'rtf')
)
),
// new \Zend\Validator\File\Upload()
));
if (!$adapter->isValid()) {
throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
}
$files = $adapter->getFileInfo();
// throw new \Exception(json_encode($files));
foreach ($files as $file => $info) {
// throw new \Exception(json_encode($info));
$name = $adapter->getFileName($file);
// file uploaded & is valid
if (!$adapter->isUploaded($file)) {
throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages()));
continue;
}
if (!$adapter->isValid($file)) {
throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
continue;
}
// receive the files into the user directory
$check = $adapter->receive($file); // this has to be on top
if (!$check) {
throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages())));
}
/**
* "name": "picture1.jpg",
"size": 902604,
"url": "http:\/\/example.org\/files\/picture1.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
"deleteType": "DELETE"
*/
$fileclass = new stdClass();
// we stripped out the image thumbnail for our purpose, primarily for security reasons
// you could add it back in here.
$fileclass->name = $name;
$fileclass->size = $adapter->getFileSize($name);
$fileclass->type = $adapter->getMimeType($name);
$fileclass->deleteUrl = '/uploads/delete';
$fileclass->deleteType = 'DELETE';
//$fileclass->error = 'null';
$fileclass->url = '/';
$datas['files'][] = $fileclass;
}
$response->getHeaders()->addHeaders(array(
'Pragma' => 'no-cache',
'Cache-Control' => 'private, no-cache',
"Content-Type" => 'application/json'
));
// return $response->setContent(json_encode(array('files' => $files)));
return $response->setContent(json_encode($datas));
} catch (\Exception $e) {
return $response->setContent(json_encode($e->getMessage()));
}
}
return $jsonModel;
}
Sorry for debug code, but with it you can see, i'm try hard to make it work, over 3 hours.
Error is
"File 'CIMG0042.JPG' was not found"
When i'm call $adapter->isValid()
Or when call it with file name, same error.
Path, where files uploaded, is correct and writable. $_FILES array is exist and valid.
Here is $_FILES json
FILES a:1:{s:5:\"files\";a:5:{s:4:\"name\";a:1:{i:0;s:28:\"52876065d17dce0a7472e5d6.jpg\";}s:4:\"type\";a:1:{i:0;s:10:\"image\/jpeg\";}s:8:\"tmp_name\";a:1:{i:0;s:14:\"\/tmp\/phpmfT2mB\";}s:5:\"error\";a:1:{i:0;i:0;}s:4:\"size\";a:1:{i:0;i:82640;}}}
And result of $files = $adapter->getFileInfo();
"{"files_0_":{"name":"52876065d17dce0a7472e5d6.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpF6VoO9","error":0,"size":"82640","options":{"ignoreNoFile":false,"useByteString":true,"magicFile":null,"detectInfos":true},"validated":false,"received":false,"filtered":false,"validators":["Zend\\Validator\\File\\Upload","Zend\\Validator\\File\\Extension"],"destination":"\/home\/seyfer\/www\/zend2-tutorial.me\/module\/Users\/config\/..\/..\/..\/data\/uploads"}}"
isUploaded passes, but isValid not.
What i'm doing wrong?
Documentation say this
Zend_File_Transfer has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.
Maybe it's mean, that Form need to be used for file uploading in any way?
UPD 25.05.14
Now i'm add form
class UploadJqueryForm extends BaseForm
{
public function __construct()
{
parent::__construct(__CLASS__);
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->init();
}
public function init()
{
$fileupload = new Element\File('files');
$fileupload->setLabel("files");
$fileupload->setAttribute('multiple', 'multiple');
$this->add($fileupload);
$button = new Element\Button('start');
$button->setAttribute("type", 'submit');
$button->setValue("Start upload")->setLabel("Start upload");
$this->add($button);
$button = new Element\Button('cancel');
$button->setAttribute("type", 'reset');
$button->setValue("Cancel upload")->setLabel("Cancel upload");
$this->add($button);
$button = new Element\Button('delete');
$button->setAttribute("type", 'button');
$button->setValue("Delete")->setLabel("Delete");
$this->add($button);
$checkbox = new Element\Checkbox('toggle');
$checkbox->setValue("Toggle")->setLabel("Toggle");
$checkbox->setAttribute("required", "");
$this->add($checkbox);
}
}
Use it
public function processjqueryAction()
{
$form = new \Users\Form\UploadJqueryForm();
$request = $this->getRequest();
$response = $this->getResponse();
$jsonModel = new \Zend\View\Model\JsonModel();
try {
if ($request->isPost()) {
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
);
// throw new \Exception(json_encode("data " . serialize($data)));
$form->setData($data);
if ($form->isValid()) {
$datas = [];
$datas['files'] = [];
$uploadPath = $this->getFileUploadLocation();
// $uploadFiles = $this->params()->fromFiles('files');
// throw new \Exception(json_encode("FILES " . serialize($_FILES)));
// Сохранение выгруженного файла
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($uploadPath);
$adapter->setValidators(array(
new \Zend\Validator\File\Extension(array(
'extension' => array('jpg', 'jpeg', 'png', 'rtf')
)
),
));
if (!$adapter->isValid()) {
throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
}
$files = $adapter->getFileInfo();
// throw new \Exception(json_encode($files));
foreach ($files as $file => $info) {
// throw new \Exception(json_encode($info));
$name = $adapter->getFileName($file);
// file uploaded & is valid
if (!$adapter->isUploaded($file)) {
throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages()));
continue;
}
if (!$adapter->isValid($file)) {
throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
continue;
}
// receive the files into the user directory
$check = $adapter->receive($file); // this has to be on top
if (!$check) {
throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages())));
}
/**
* "name": "picture1.jpg",
"size": 902604,
"url": "http:\/\/example.org\/files\/picture1.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
"deleteType": "DELETE"
*/
$fileclass = new stdClass();
// we stripped out the image thumbnail for our purpose, primarily for security reasons
// you could add it back in here.
$fileclass->name = $name;
$fileclass->size = $adapter->getFileSize($name);
$fileclass->type = $adapter->getMimeType($name);
$fileclass->deleteUrl = '/uploads/delete';
$fileclass->deleteType = 'DELETE';
//$fileclass->error = 'null';
$fileclass->url = '/';
$datas['files'][] = $fileclass;
}
$response->getHeaders()->addHeaders(array(
'Pragma' => 'no-cache',
'Cache-Control' => 'private, no-cache',
"Content-Type" => 'application/json'
));
return $response->setContent(json_encode($datas));
} else {
throw new \Exception(json_encode("!isValid form" . serialize($form->getMessages())));
}
}
} catch (\Exception $e) {
return $response->setContent(json_encode($e->getMessage()));
}
return $jsonModel;
And still get error
File '24866-fu-blyad-otvratitelno.jpg' was not found
Also I tried with InputFilter
class UploadJqueryFilter extends InputFilter implements
InputFilterAwareInterface
{
public function __construct()
{
$this->getInputFilter();
}
public function getInputFilter()
{
$toggle = new Input('toggle');
$toggle->setRequired(FALSE);
$this->add($toggle);
$files = new \Zend\InputFilter\FileInput('files');
$files->setRequired(TRUE);
$files->getValidatorChain()->attach(new Validator\File\UploadFile);
$files->getFilterChain()->attach(new \Zend\Filter\File\RenameUpload(array(
'target' => __DIR__ . '/../../../../../../tmpuploads/tmp',
'randomize' => true,
)));
$this->add($files);
return $this;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
return false;
}
}
And have same error.
I had this problem too. Wasting several hours before found the problem. Turn out it's because the name attribute for input tag cannot be set as 'files'.
So this is a no:
<input id="files" type="file" name="files" data-url="/upload-action" />
Changing the name attribute to any string other than files such as file will solve this problem.
<input id="files" type="file" name="file" data-url="/upload-action" />
I see from $_FILES that you had set name as files. Try changing that.
Make sure you update the reference you made in your controller too.

Categories