Api Version 0.6.2
I was following this answer:
Post large video to youtube via google php client api v3
I'm getting
Failed to start the resumable upload
500 Internal Server Error - Google_Exception
Stack Trace
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/service/Google_MediaFileUpload.php at line 260 -+
if (200 == $code && true == $location) {
return $location;
}
throw new Google_Exception("Failed to start the resumable upload");
}
}
at Google_MediaFileUpload ->getResumeUri (object(Google_HttpRequest))
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/service/Google_MediaFileUpload.php at line 214 -+
public function nextChunk(Google_HttpRequest $req, $chunk=false) {
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri($req);
}
if (false == $chunk) {
at Google_MediaFileUpload ->nextChunk (object(Google_HttpRequest), '')
in /home/darko/NetBeansProjects/shekortet/src/Dalu/MediaBundle/Controller/EncodeController.php at line 284 -+
while (!$status && !feof($handle))
{
$chunk = fread($handle, $chunkSizeBytes);
$uploadStatus = $media->nextChunk($result, $chunk);
var_dump($uploadStatus);
}
When trying to post a nonresumable upload I'm getting a 400 Bad Request error.
Error Message
Error calling POST https://www.googleapis.com/youtube/v3/videos?part=status%2Csnippet&key=replacedkeystring: (400) Bad Request
Stack Trace
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/io/Google_REST.php at line 66 -+
$err .= ": ($code) $body";
}
throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
}
// Only attempt to decode the response, if the response code wasn't (204) 'no content'
at Google_REST ::decodeHttpResponse (object(Google_HttpRequest))
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/io/Google_REST.php at line 36 -+
*/
static public function execute(Google_HttpRequest $req) {
$httpRequest = Google_Client::$io->makeRequest($req);
$decodedResponse = self::decodeHttpResponse($httpRequest);
$ret = isset($decodedResponse['data'])
? $decodedResponse['data'] : $decodedResponse;
return $ret;
at Google_REST ::execute (object(Google_HttpRequest))
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/service/Google_ServiceResource.php at line 186 -+
return $httpRequest;
}
return Google_REST::execute($httpRequest);
}
public function useObjects() {
at Google_ServiceResource ->__call ('insert', array(array('part' => 'status,snippet', 'postBody' => object(Google_Video), 'mediaUpload' => object(Google_MediaFileUpload))))
in /home/darko/NetBeansProjects/shekortet/vendor/google/google-api-php-client/src/contrib/Google_YouTubeService.php at line 789 -+
public function insert($part, Google_Video $postBody, $optParams = array()) {
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Google_Video($data);
} else {
at Google_VideosServiceResource ->insert ('status,snippet', object(Google_Video), array('mediaUpload' => object(Google_MediaFileUpload)))
in /home/darko/NetBeansProjects/shekortet/src/Dalu/MediaBundle/Controller/EncodeController.php at line 277 -+
$media = new \Google_MediaFileUpload('video/x-matroska', null, false, $chunkSizeBytes);
$media->setFileSize(filesize($filename));
$result = $youtube->videos->insert("status,snippet", $gvideo, ['mediaUpload' => $media]);
$status = false;
$handle = fopen($filename, "rb");
I have authenticated a few hours ago. I saw that the token lifetime was 3600 (1h).
This is also done locally
Could this be the reason or what could be the reason?
Any help appreciated.
Related
I got
failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in php when got file from Google Drive through Google Drive API.
My code below:
public function actionGetAllImagesFromDrive($fid, $path)
{
$client = $this->getGoogleClient();
$service = new \Google_Service_Drive($client);
$optParams = array(
'q' => "'$fid' in parents and trashed=false",
'fields' => '*'
);
$results = $service->files->listFiles($optParams);
$folderMimeType = 'application/vnd.google-apps.folder';
if (count($results->getFiles()) != 0) {
if (!is_dir($path)) {
mkdir($path, 0775, true);
}
foreach ($results->getFiles() as $file) {
if($file->getMimeType() == $folderMimeType) {
$this->actionGetAllImagesFromDrive($file->getId(), $path .'/'.$file->getName());
} else {
$url = $file->getWebContentLink();
$file_name = $path .'/'. $file->getName();
print_r("Downloading: ".$file->getName()."\n");
file_put_contents( $file_name, file_get_contents($url));
}
}
} else {
print_r("Folder is empty.\n");
}
}
This code will get all image from folder and sub folder on Google Drive.
How to solve this issue?
Have you considered following the example in the library large file download
// Determine the file's size and ID
$fileId = $files[0]->id;
$fileSize = intval($files[0]->size);
// Get the authorized Guzzle HTTP client
$http = $client->authorize();
// Open a file for writing
$fp = fopen('Big File (downloaded)', 'w');
// Download in 1 MB chunks
$chunkSizeBytes = 1 * 1024 * 1024;
$chunkStart = 0;
// Iterate over each chunk and write it to our file
while ($chunkStart < $fileSize) {
$chunkEnd = $chunkStart + $chunkSizeBytes;
$response = $http->request(
'GET',
sprintf('/drive/v3/files/%s', $fileId),
[
'query' => ['alt' => 'media'],
'headers' => [
'Range' => sprintf('bytes=%s-%s', $chunkStart, $chunkEnd)
]
]
);
$chunkStart = $chunkEnd + 1;
fwrite($fp, $response->getBody()->getContents());
}
Following the instructions for these topics:
https://github.com/google/google-api-php-client/issues/788
https://developers.google.com/api-client-library/php/guide/media_upload
I tried to fix the problem below and upload files to Google Drive:
Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:187 Stack trace: #0 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::fin in /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 187
Using the APIs in PHP, when the file is less than 5 MB, it does not show the error, however, files larger than this generate the above error. Is the problem the API or the certificate? Even installing it on my linux server the error continues, does anyone know how to fix this problem? Or have you ever faced something like that?
Here is the code I'm using to upload up to 5 MB that is working.
<?php
$client = new Google_Client();
$client->setAuthConfig("client_secret.json");
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setAccessToken($access_token);
$drive_service = new Google_Service_Drive($client);
$mime_type = mime_content_type($uploadfile);
$file = new Google_Service_Drive_DriveFile();
$result = $drive_service->files->create($file, array(
"data" => file_get_contents($uploadfile),
"mimeType" => $mime_type,
"uploadType" => "media"
));
Following is the code I'm using to upload a larger 5 MB that is not working.
<?php
$client = new Google_Client();
$client->setAuthConfig("client_secret.json");
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setAccessToken($access_token);
$drive_service = new Google_Service_Drive($client);
$mime_type = mime_content_type($uploadfile);
$file = new Google_Service_Drive_DriveFile();
$file->title = $uploadname;
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$request = $drive_service->files->create($file); // insert
$media = new Google_Http_MediaFileUpload($client, $request, $mime_type, null, true, $chunkSizeBytes);
$media->setFileSize(filesize($uploadfile));
$status = false;
$handle = fopen($uploadfile, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
$client->setDefer(false);
function drupal_http_request($url, array $options = array()) {
// Allow an alternate HTTP client library to replace Drupal's default
// implementation.
$override_function = variable_get('drupal_http_request_function', FALSE);
if (!empty($override_function) && function_exists($override_function)) {
return $override_function($url, $options);
}
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
$uri = #parse_url($url);
if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}
if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}
timer_start(__FUNCTION__);
// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'Drupal (+http://drupal.org/)',
);
// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];
// Use a proxy if one is defined and the host is not on the excluded list.
$proxy_server = variable_get('proxy_server', '');
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
// Set the scheme so we open a socket to the proxy server.
$uri['scheme'] = 'proxy';
// Set the path to be the full URL.
$uri['path'] = $url;
// Since the URL is passed as the path, we won't use the parsed query.
unset($uri['query']);
// Add in username and password to Proxy-Authorization header if needed.
if ($proxy_username = variable_get('proxy_username', '')) {
$proxy_password = variable_get('proxy_password', '');
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
}
// Some proxies reject requests with any User-Agent headers, while others
// require a specific one.
$proxy_user_agent = variable_get('proxy_user_agent', '');
// The default value matches neither condition.
if ($proxy_user_agent === NULL) {
unset($options['headers']['User-Agent']);
}
elseif ($proxy_user_agent) {
$options['headers']['User-Agent'] = $proxy_user_agent;
}
}
switch ($uri['scheme']) {
case 'proxy':
// Make the socket connection to a proxy server.
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
// The Host header still needs to match the real request.
$options['headers']['Host'] = $uri['host'];
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
break;
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;
case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;
default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}
if (empty($options['context'])) {
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout']);
}
else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = #stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}
var_dump($fp);
// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket #socket', array('#socket' => $socket));
print_r($result);
exit();
// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// See system_requirements().
variable_set('drupal_http_request_fails', TRUE);
return $result;
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}
// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}
// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
}
// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';
while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);
if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);
// Parse the response status line.
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
$result->protocol = $response_status_array['http_version'];
$result->status_message = $response_status_array['reason_phrase'];
$code = $response_status_array['response_code'];
$result->headers = array();
// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
}
else {
$result->headers[$name] = trim($value);
}
}
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
}
elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects']--;
$result = drupal_http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $result->status_message;
}
return $result;
}
I'm getting the below mentioned message by doing var_dump of $fp as mentioned above on my VM machine hosted with Ubuntu 14.04
stdClass Object
(
[code] => 0
[error] => php_network_getaddresses: getaddrinfo failed: Name or service not known
)
When I'm implementing the same thing on my localhost which is XAMPP based in Windows 7 I'm getting this:
Resource id #8
Due to this I'm unable to use the drupal_http_request
As per your suggestion I've tried dns_get_record()
$dns_get_record = dns_get_record("www.google.com");
print_r($dns_get_record);
and got this as the output:
Array
(
[0] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 243
[type] => A
[ip] => 216.58.220.4
)
[1] => Array
(
[host] => www.google.com
[class] => IN
[ttl] => 257
[type] => AAAA
[ipv6] => 2404:6800:4009:805::2004
)
)
I've also checked the stream_socket_client()
var_dump(stream_socket_client());
and it returned me bool(false)
Since you've not put any proper error handling in the code, we can't tell which function is being executed. You haven't provided the parameters you are passing, so we can't tell what the cause is, but the most likely issue is that you are trying to establish a network connection and the host where the code is running is unable to resolve the hostname inside $socket.
You can very this with dns_get_record() or speak to your hosting provider.
Here is my code for deleting the image file form Amazon S3:
<?php
$s3 = new S3(awsAccessKey, awsSecretKey);
$del1 = $s3->deleteObject($bucket,$newfilename);
$del2 = $s3->deleteObject($thumb_bucket,$newfilename);
public static function deleteObject($bucket, $uri)
{
$rest = new S3Request('DELETE', $bucket, $uri, self::$endpoint);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
self::__triggerError(sprintf("S3::deleteObject(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
?>
In this, I am getting true as output, but form my bucket it is not going to be deleted. Any solution?
I have a very small script that uploads and / or update files (wrote this about 1 year ago, borrowed 80% of the lines from the examples)
No major changes in the code since march (using 1.0.0-alpha) but mid-may the file updates stopped working, raising an Internal Server Error , i upgraded to 1.0.4-beta with no success :
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling PUT https://www.googleapis.com/upload/drive/v2/ [...] (500) Internal Error' in
google-api-php-client-1.0.4-beta/src/Google/Http/REST.php:80
code:
$client->setDefer(true);
$request = $service->files->update($update_id,$file);
$media = new Google_Http_MediaFileUpload(
$client,
$request,
'text/plain',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($csvfile))
$status = false;
$handle = fopen($csvfile, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
File inserts (HTTP POST) are still working (using the same code for uploading the chunks)
any ideas ?
I can update a file ( previously created or copied from a template ) with this code :
(...)
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Oauth2.php';
require_once 'src/Google/Service/Drive.php';
(...)
$client = new Google_Client();
// set scopes ...
(...)
$GDrive_service = new Google_Service_Drive($client);
(...)
// then I set parameters
(...)
$newTitle = $title ;
$newDescription = $description ;
$newMimeType = 'text/csv' ;
$newFileName = $filename ;
$service = $GDrive_service ;
(...)
$updatedFile = updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) ;
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);
$convert = 'true' ;
$additionalParams = array(
'uploadType' => 'multipart',
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType,
'convert' => $convert,
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
(...)
// this is info of the updated file
$fileId = $updatedFile->getId() ;
// link of file
$cF_link = $updatedFile->alternateLink ;
// pdf version
$enllacos = $updatedFile->exportLinks ;
$cF_PDF_link = $enllacos['application/pdf'] ;
(...)
This code is working with the 1.0.5-beta php client
Sergi