Google Drive API - Fetch Shared Files Download Links

回眸只為那壹抹淺笑 提交于 2020-01-01 19:30:31

问题


I am new to Google Drive and have uploaded many files. I have changed the status of all files to be shared if the download link is known.

I would like to use PHP to generate a list of all of the direct download links for the files. The PHP script is run on my localhost and I just need the array to be saved to a text file to be used later.

I have had a very hard time trying to get Oauth working but came across this script that looks like what I need. I set up my service account and have my service account email and .p12 file.

I downloaded the Google PHP client code base and set up a test script on my localhost. This is what I have

require_once "Google/Client.php";
require_once "Google/Service/Drive.php";
require_once "Google/Service/Oauth2.php";
require_once "Google/Auth/AssertionCredentials.php";

session_start();


function buildService($userEmail) {

$SERVICE_ACCOUNT_EMAIL = '12345@developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '12345-privatekey.p12';

$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array('https://www.googleapis.com/auth/drive'),
$key);
$auth->sub = $userEmail;
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);

return new Google_DriveService($client);
}

//... function retrieveAllFiles($service)

$service = buildService("myemail@gmail.com");
$allFiles = retrieveAllFiles($service);
print_r($allFiles);

I am working off of this example

http://stackoverflow.com/questions/21046631/google-drive-api-php-cant-list-files

and this

https://developers.google.com/drive/web/delegation#instantiate_a_drive_service_object

I am unsure what to do, I have added the required libraries but the following functions are coming up as being unknown in the PHP script

Google_AssertionCredentials

setUseObjects

Google_DriveService

retrieveAllFiles

Am I missing an obvious library? They are named different in the example but I'm guessing the base names have changed since there were updates... I have spent a lot of time reading up on Google Drive and Oauth without any luck. My only goal with this script is to get a list of the direct download links. I can do it manually but there are too many files.

Any help would be great.

Thanks.


* EDIT: *


So I this is what I have tried to obtain my token:

I am following this quick start guide:

https://developers.google.com/drive/web/quickstart/quickstart-php

Here is my code

<?php

require_once 'Google/client.php';
require_once 'Google/Service/drive.php';

defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); //I had to add this part as I was getting an undefined error for STDIN 

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://localhost/test/fetch.php'); //same as registered one
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_Service_Drive($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

This results in error

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Invalid code' in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php:95 Stack trace: #0 C:\Apache24\htdocs\test\Google\Client.php(135): Google_Auth_OAuth2->authenticate('') #1 C:\Apache24\htdocs\test\new.php(26): Google_Client->authenticate('') #2 {main} thrown in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php on line 95

Any thoughts ?

Thanks.


ANOTHER EDIT


So I have reverted to the old Drive PHP library as the new Drive PHP library has no documentation or examples.

This is my attempt to obtain a token and fetch the direct download file links

require_once 'google-old/google-api-php-client/src/Google_Client.php';
require_once 'google-old/google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xx.apps.googleusercontent.com');
$client->setClientSecret('xx');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_DriveService($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

$getAll = retrieveAllFiles($service);

print "<pre>";
print_r($getAll);
print "</pre>";

/**
 * Retrieve a list of File resources.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @return Array List of Google_DriveFile resources.
 */
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;

do {
    try {
        $parameters = array();
        if ($pageToken) {
            $parameters['pageToken'] = $pageToken;
        }
        $files = $service->files->listFiles($parameters);

        $result = array_merge($result, $files->getItems());
        $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
        $pageToken = NULL;
    }
} while ($pageToken);
return $result;
}

The problem I now face is that I am stuck at the "Paste the code into your app" part.

The

$authCode = trim(fgets(STDIN));

doesn't seem to want to execute.

Also I believe the file fetching code will just fetch the file names, and not the direct download links. I could not find an example for this.

Any suggestions would be much appreciated.

Thanks.

I am testing this on my localhost.


回答1:


Firstly, separate your learning about OAuth from your learning about Drive. As a combined problem, it's hard, but as two separate problems, it's pretty simple.

For OAuth, everything you need to know is on this one web page https://developers.google.com/accounts/docs/OAuth2WebServer

Having read that page and understood it, if you want to use a library to make the calls, go ahead. IMHO the OAuth libraries don't do a great job, but ymmv. With or without a library, it is essential that you understand what is happening.

Having cracked OAuth, you end up with a shiny access_token which you drop into the Drive API, either as an http header if you are calling the rar API, or wrapped in a credential object if you are using one of the libraries.




回答2:


Replace the STDIN stuff.

put this in instead:

if (!isset($_GET['code'])) {
    print "Please visit:\n$authUrl\n\n";
    print "Please enter the auth code:\n";
} else { $authCode = ''; }
//$authCode = trim(fgets(STDIN));

$authCode = $_GET['code'];

Google's code is buggy in terms of their thing. Having done so I'm getting file creation (it's still pumping out an error but it's producing the files).

replace their file_get_contents line with:

$data = 'blahblah blah';//file_get_contents('document.txt');

and there you go.



来源:https://stackoverflow.com/questions/21980057/google-drive-api-fetch-shared-files-download-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!