Google api php How to edit Google table - php

Good afternoon!
I can download files from the disc with a Google api method:
function downloadFile($service, $downloadUrl,$client) {
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$SignhttpRequest = $client->getAuth()->sign($request);
$httpRequest = $client->getIo()->makeRequest($SignhttpRequest);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
But I can not download a file created on the Google Tables. No links in "downloadUrl".
Tell me how you can download and edit the file created on the Google Tables?

Related

Symfony2 API - Best way to import and save a CSV file

I need to create an API that receives via POST a .csv file that in a second moment has to be saved to the DB.
This is how I wrote the function:
/**
* #Route("/importCSV", name = "import_csv")
* #Method("POST")
**/
public function importCSVAction(Request $request) {
if ($this->getRequest()->files) {
$type = "csv";
$filename = date('Ymd').'-'.$type.'-filename';
$directory = $this->container->getParameter('kernel.root_dir') . '/../Documents';
$request = $this->get('request');
$data = $request->getContent();
try {
$fs = new Filesystem();
$fs->dumpFile($filename, $data);
move_uploaded_file($filename, $directory);
}
catch(IOException $e) {
return new Response ("File not saved!", 500, array('Content-Type' => 'application/json'));
}
return new Response($data);
}
else return new Response("Error!", 500, array('Content-Type' => 'application/json'));
}
1 One problem is that the file is saved under the web folder and not under Documents as I wanted.
Also, how can I check if the file I'm importing is a .csv file?
2 I searched on the web but I did not found many resources on this subject.
I just want to know if this is generally a correct way to save the .csv file.
Thanks!

PHP Error Class 'Google_Http_Request' not found

I'm trying to download or convert a file from Google Drive. I am using the below code, and I get the error "Class 'Google_Http_Request' not found". I can't seem to find what I'm missing. Am I missing something? A required file?
I'm using php-google-api-php-client (0.6.2-1) [universe].
Thanks.
$file = $service->files->get($drive_id);
//if actual file
//$downloadUrl = $file->getDownloadUrl();
//if a google doc
$downloadUrl = $file->getExportLinks();
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
In general, php does not autoload any classes. In basic terms, you would need to require() the right file to load Google_Http_Request, but you will run into more issues as google drive api requires authentication.
I suggest you follow much newer instructions provided on the Google's Developer Center: https://developers.google.com/drive/web/quickstart/php. The quickstart even goes as far as list files.

How to call "asp.net api upload file" from php

I create a serive api using asp.net and a methoad POST upload a any file, and I want using code php call that api, but i don't known how.
Code asp.net api upload file as follows:
public Task<IEnumerable<string>> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
string fullPath = HttpContext.Current.Server.MapPath("~/uploads");
MyMultipartFormDataStreamProvider streamProvider = new MyMultipartFormDataStreamProvider(fullPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return "File uploaded as " + info.FullName + " (" + info.Length + ")";
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
}
}
And class:
public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string fileName;
if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
{
fileName = headers.ContentDisposition.FileName;
}
else
{
fileName = Guid.NewGuid().ToString() + ".data";
}
return fileName.Replace("\"", string.Empty);
}
}
So, how to I can call this api using code php ?
I referenced code to: http://www.codeguru.com/csharp/.net/uploading-files-asynchronously-using-asp.net-web-api.htm
To me it looks like you have a php website and looked on the web for an upload example and found a asp.net one.
If you got php running why not use php for the upload?

No thumbnails are returned in youtube api

I've attempted to use the YouTube service API V3 and have run into an issue I'm unsure of how to proceed.
I'm calling my script through Jquery's Ajax. Nothing crazy.
Passing in an id for the video I want and away I go.
The script is as such:
session_start();
$return_msg = array();
// ===================================
// Require Google libraries
// ===================================
set_include_path("../../includes/");
if(!(#require_once('Google/Client.php')))
{
$return_msg['error'] = 'Unable to includes Google Client Library:<br>'.$e->getMessage();
return $return_msg;
}
if(!(#require_once('Google/Service/YouTube.php')))
{
$return_msg['error'] = 'Unable to includes Google YouTube Library:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Include Global settings
// ===================================
if(!(#require_once('Global-Settings.php')))
{
$return_msg['error'] = 'Unable to includes site settings:<br>'.$e->getMessage();
return $return_msg;
}
$globals = new Globals();
// Set API key
$api_key = $globals->youtube_key;
if(!isset($data['id']))
{
$return_msg['error'] = 'Unable to determine the video you are attempting to find.';
return $return_msg;
}
// ===================================
// Create Client
// ===================================
try
{
$client = new Google_Client();
$client->setApplicationName("YouTube_Test");
$client->setDeveloperKey($api_key);
}catch(Exception $e){
$return_msg['error'] = 'Error creating Google client:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Get video
// ===================================
try
{
$service = new Google_Service_YouTube($client);
$response = $service->videos->listVideos('id,snippet,contentDetails', array(
"id" => $data['id']
));
$return_msg['results'] = $response;
foreach($response->items as $video)
{
$item = array();
$item['id'] = $video['id'];
$item['snippet'] = $video['snippet'];]
$item['contentDetails'] = $video['contentDetails'];
$return_msg['items'][$item['id']] = $item;
}
}catch(Exception $e){
$return_msg['error'] = 'Error finding video:<br>'.$e->getMessage();
return $return_msg;
}
return $return_msg;
The reason I am storing the individual items in an array is because line $return_msg['results'] = $response; returns fields, yet not the items object as I'd expect.
Anywho, once I return all this to JS and log it to console, I see that inside the 'snippets' array there are no thumbnails.
Not sure why, or what I'm doing incorrectly as far as that goes. I've tried to log as much info as I could and I simply can't find any trace of the thumbnails collection.
A simple way to get thumbnail of a video from youtube is by using the video id:
http://img.youtube.com/vi/<your_video_id>/0.jpg
[0.jpg, 1.jpg, 2.jpg and 3.jpg can be used]
For Eg:
http://img.youtube.com/vi/-w8KI3A5zu4/0.jpg
if you got the video_id from youtube API, you can simply use this to get the image.

Google Drive SDK downloadFile - What does it do?

I am developing in Drupal and using the php code from the Google Drive SDK that is supposed to download a file:
/**
* Download a file's content.
*
* #param Google_DriveService $service Drive API service instance.
* #param File $file Drive File instance.
* #return String The file's content if successful, null otherwise.
*/
function downloadFile($service, $file) {
$downloadUrl = $file->getDownloadUrl();
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
It is returning a successful response code of 200 but I cannot tell that it has actually done anything. However, I can tell from observing my LAN connection status that something of the right size in bytes is being downloaded. I just don't know where it is ending up. I am using Acquia Dev Desktop so I am running the website on my PC, but I cannot find where in the website folder the downloaded file is ending up if it is indeed being stored. I then tried another function that I found here and got similar results. Can someone more familiar with this explain what is happening?
function GetFile($service, $fileId) {
$fileVars = null;
try {
/*
* Retrieve metadata for the file specified by $fileId.
*/
$file = $service->files->get($fileId);
$fileVars = get_object_vars($file);
/*
* Retrieve the file's content using download URL specified in metadata.
*/
$downloadUrl = $file->getDownloadUrl();
error_log('Download URL file from Drive: ' . $downloadUrl);
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
error_log(print_r($httpRequest, 1));
if ($httpRequest->getResponseHttpCode() == 200) {
$content = $httpRequest->getResponseBody();
$fileVars['content'] = $content?($content):'';
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error retrieving file from Drive: ' . $e->getMessage());
throw $e;
}
return json_encode($fileVars);
}
This method returns the following results:
{"alternateLink":"https:\/\/docs.google.com\/file\/d\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/edit?usp=drivesdk","appDataContents":false,"createdDate":"2013-12-05T21:05:03.026Z","defaultOpenWithLink":null,"description":"Flashum mp4","downloadUrl":"https:\/\/doc-0g-50-docs.googleusercontent.com\/docs\/securesc\/apic76cj8gku48a9ogarn9khpku0s46q\/gc9ck66nc600ebdk0ak9f58gkthnnacm\/1386345600000\/08295678552528470768\/15372451357194678536\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0?h=16653014193614665626&e=download&gd=true","editable":true,"embedLink":"https:\/\/video.google.com\/get_player?ps=docs&partnerid=30&docid=0B6ahcE1NPpIaMTJzcFRLMnNiYU0&BASE_URL=https:\/\/docs.google.com\/","etag":"\"maCRbN5nR56FjQPLihEiz9nzpho\/MTM4NjI3NzUwNDU1MA\"","explicitlyTrashed":null,"exportLinks":null,"fileExtension":"mp4","fileSize":"788456","headRevisionId":"0B6ahcE1NPpIaeVJ5b3RxdExvamlDdWNrcGFvWXdvaWg3VU5JPQ","iconLink":"https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_video_list.png","id":"0B6ahcE1NPpIaMTJzcFRLMnNiYU0","imageMediaMetadata":null,"indexableText":null,"kind":"drive#file","labels":{"hidden":false,"restricted":false,"starred":false,"trashed":false,"viewed":false},"lastModifyingUser":{"displayName":"C. David Young","isAuthenticatedUser":false,"kind":"drive#user","permissionId":"08295678552528470768","picture":{"url":"https:\/\/lh6.googleusercontent.com\/-tjPzr0pfd_4\/AAAAAAAAAAI\/AAAAAAAAAWc\/DZtQHXrxkgQ\/s64\/photo.jpg"}},"lastModifyingUserName":"C. David Young","lastViewedByMeDate":null,"md5Checksum":"00701d2dd7a1b99e8ebb68cf62305b0d","mimeType":"application\/video","modifiedByMeDate":null,"modifiedDate":"2013-12-05T21:05:04.550Z","openWithLinks":null,"originalFilename":"charlesdavidyoung#gmail.com#test.mp4","ownerNames":["C. David Young"],"owners":[{"displayName":"C. David Young","isAuthenticatedUser":false,"kind":"drive#user","permissionId":"08295678552528470768","picture":{"url":"https:\/\/lh6.googleusercontent.com\/-tjPzr0pfd_4\/AAAAAAAAAAI\/AAAAAAAAAWc\/DZtQHXrxkgQ\/s64\/photo.jpg"}}],"parents":[{"id":"0B6ahcE1NPpIaQlMyWFBPamZIeTA","isRoot":false,"kind":"drive#parentReference","parentLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaQlMyWFBPamZIeTA","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/parents\/0B6ahcE1NPpIaQlMyWFBPamZIeTA"}],"quotaBytesUsed":"788456","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0","shared":true,"sharedWithMeDate":null,"thumbnail":null,"thumbnailLink":"https:\/\/lh4.googleusercontent.com\/Ja2DZ3vzXSTn7kY_xY8VmC2N7nCeBrbvnkr-lO4GbMuOmpETwLAYlaC7qr5fOpBTTQ=s220","title":"charlesdavidyoung#gmail.com#test.mp4","userPermission":{"additionalRoles":null,"authKey":null,"etag":"\"maCRbN5nR56FjQPLihEiz9nzpho\/8jq33BWTNkV1S9Wn1TTkFYEVpVc\"","id":"me","kind":"drive#permission","name":null,"photoLink":null,"role":"writer","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/permissions\/me","type":"user","value":null,"withLink":null},"webContentLink":"https:\/\/docs.google.com\/uc?id=0B6ahcE1NPpIaMTJzcFRLMnNiYU0&export=download","webViewLink":null,"writersCanShare":true,"copyable":true,"content":null}
If you pass to your script a document id it should return you a download link under the field exportLinks. The fact that your exportLinks is null means that you cannot download the file (permissions?).

Categories