Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DO NOT MERGE: example of library usage #1540

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/apis/drive/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.

/*! THIS FILE IS AUTO-GENERATED */
/*! THIS FILE WILL EVENTUALLY BECOME AUTO-GENERATED */

import {AuthPlus, getAPI, GoogleConfigurable} from 'googleapis-common';

import {getAPI, GoogleConfigurable} from 'googleapis-common';
import {drive_v2} from './v2';
import {drive_v3} from './v3';

Expand All @@ -31,3 +32,6 @@ export function drive<T = drive_v2.Drive | drive_v3.Drive>(
versionOrOptions: 'v2'|drive_v2.Options|'v3'|drive_v3.Options) {
return getAPI<T>('drive', versionOrOptions, VERSIONS, this);
}

const auth = new AuthPlus();
export {auth};
21 changes: 14 additions & 7 deletions src/apis/drive/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
"description": "drive",
"main": "build/index.js",
"types": "build/index.d.ts",
"keywords": ["google"],
"keywords": [
"google"
],
"author": "Google LLC",
"license": "Apache-2.0",
"homepage": "https://github.com/google/google-api-nodejs-client",
"homepage": "https://github.com/googleapis/google-api-nodejs-client",
"bugs": {
"url" : "https://github.com/google/google-api-nodejs-client/issues"
alexander-fenster marked this conversation as resolved.
Show resolved Hide resolved
"url": "https://github.com/googleapis/google-api-nodejs-client/issues"
},
"repository": {
"type": "git",
"url" : "https://github.com/google/google-api-nodejs-client.git"
"url": "https://github.com/googleapis/google-api-nodejs-client.git"
},
"engines": {
"node": ">=6.0.0"
Expand All @@ -23,14 +25,19 @@
"lint": "gts check",
"compile": "tsc -p .",
"prepare": "npm run compile",
"docs": "typedoc --out docs/"
"docs": "typedoc --out docs/",
"webpack": "npx webpack"
},
"dependencies": {
"googleapis-common": "^0.4.0"
"googleapis-common": "0.6.0-webpack"
},
"devDependencies": {
"gts": "^0.9.0",
"null-loader": "^0.1.1",
"ts-loader": "^5.3.3",
"typedoc": "^0.14.0",
"typescript": "~3.2.0",
"typedoc": "^0.14.0"
"webpack": "^4.28.4",
"webpack-cli": "^3.2.1"
}
}
3 changes: 3 additions & 0 deletions src/apis/drive/samples/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

rules:
no-console: off
26 changes: 26 additions & 0 deletions src/apis/drive/samples/node/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Drive v3 API Samples

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


These samples allow you to list, download, and upload files from Google Drive.

## Running the samples

### **Note: Node.js version 8 or greater is requared to run samples.**
Set the following values in `oauth2.keys.json` (up one directory):

* `client_id`
* `project_id`
* `client_secret`

__Run the `quickstart.js` sample:__

This sample will list the files in the user's Google Drive.

You'll need to do the following before you can run this sample:

* Enable the [Google Drive API](https://console.developers.google.com/apis/api/drive.googleapis.com/overview).
* Set the redirect API in the Google Cloud Console application registration to `http://localhost:3000/oauth2callback`.

```
node quickstart.js
```

90 changes: 90 additions & 0 deletions src/apis/drive/samples/node/quickstart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright 2018, Google, LLC.

This comment was marked as spam.

This comment was marked as spam.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START main_body]
const {drive, auth} = require('@google/drive');
const express = require('express');
const opn = require('opn');
const path = require('path');
const fs = require('fs');

const keyfile = path.join(__dirname, '..', 'oauth2.keys.json');

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

const keys = JSON.parse(fs.readFileSync(keyfile));
const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

// Create an oAuth2 client to authorize the API call
const client = new auth.OAuth2(
keys.web.client_id,
keys.web.client_secret,
keys.web.redirect_uris[0]
);

// Generate the url that will be used for authorization
this.authorizeUrl = client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});

// Open an http server to accept the oauth callback. In this
// simple example, the only request to our webserver is to
// /oauth2callback?code=<code>
const app = express();
app.get('/oauth2callback', (req, res) => {

This comment was marked as spam.

const code = req.query.code;
client.getToken(code, (err, tokens) => {
if (err) {
console.error('Error getting oAuth tokens:');
throw err;
}
client.credentials = tokens;
res.send('Authentication successful! Please return to the console.');
server.close();
listFiles(client);
});
});
const server = app.listen(3000);
// open the browser to the authorize url to start the workflow
opn(this.authorizeUrl, {wait: false});

This comment was marked as spam.

This comment was marked as spam.


/**
* Lists the names and IDs of up to 10 files.
* @param {auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {

This comment was marked as spam.

This comment was marked as spam.

const service = drive('v3');
service.files.list(
{
auth: auth,
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
},
(err, res) => {
if (err) {
console.error('The API returned an error.');
throw err;
}
const files = res.data.files;
if (files.length === 0) {
console.log('No files found.');
} else {
console.log('Files:');
for (const file of files) {
console.log(`${file.name} (${file.id})`);
}
}
}
);
}
// [END main_body]
16 changes: 16 additions & 0 deletions src/apis/drive/samples/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "google-drive-samples",
"version": "0.0.1",
alexander-fenster marked this conversation as resolved.
Show resolved Hide resolved
"description": "These samples allow you to list, download, and upload files from Google Drive.",
"main": "quickstart.js",
"scripts": {
alexander-fenster marked this conversation as resolved.
Show resolved Hide resolved
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "Apache-2.0",
"dependencies": {
"@google/drive": "0.1.0",
"express": "^4.16.4",
"opn": "^5.4.0"
}
}
36 changes: 36 additions & 0 deletions src/apis/drive/samples/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Drive v3 API Samples

These samples allow you to list files on Google Drive using this library in the browser.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


## Running the samples

### **Note: Node.js version 8 or greater is requared to run samples.**
Set the following values in `oauth2.keys.json` (up one directory):

* `client_id`
* `project_id`
* `client_secret`

__Generate the webpacked bundle of the library__

Execute the following command from the main directory (the one that contains `package.json`):

```
npm run webpack
```

__Run the webserver__

This sample will list the files in the user's Google Drive.

You'll need to do the following before you can run this sample:

* Enable the [Google Drive API](https://console.developers.google.com/apis/api/drive.googleapis.com/overview).
* Set the redirect API in the Google Cloud Console application registration to `http://localhost:3000/oauth2callback`.

```
node webserver.js
```

The script will run a webserver on port 3000 and will open a browser that will authenticate the user and show
the first ten files from the user's Google Drive.
101 changes: 101 additions & 0 deletions src/apis/drive/samples/web/index.html.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<!DOCTYPE html>

<!--
Copyright 2018, Google, LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<html>
<head>

<!-- load webpacked client library -->
<script type="text/javascript" src="drive.min.js"></script>

<script type="text/javascript">
function getStoredCredentials() {
var credentialsString = localStorage.getItem('credentials');
if (!credentialsString) {
return {};
}
const credentials = JSON.parse(credentialsString);
return credentials;
}

async function processCode(oAuth2Client, code) {
const getTokenResult = await oAuth2Client.getToken(code);
localStorage.setItem('credentials', JSON.stringify(getTokenResult.tokens));
window.location.href = '/';
}

async function runSample() {
const keys = KEYS;
const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly'];

const {drive, auth} = Drive;
const oAuth2Client = new auth.OAuth2(
keys.web.client_id,
keys.web.client_secret,
keys.web.redirect_uris[0]
);

const code = new URL(window.location).searchParams.get('code');
if (code) {
alert('we got OAuth2 code from server, now getting OAuth2 token and redirecting to the main page');
await processCode(oAuth2Client, code);
return;
}

const credentials = getStoredCredentials();
if (!credentials.access_token) {
alert('there are no saved credentials, redirecting to OAuth2');
const url = oAuth2Client.generateAuthUrl({
scope: scopes
});
window.location.href = url;
return;
}

alert('found OAuth2 credentials, running query');
oAuth2Client.credentials = credentials;
const output = document.getElementById('result');
const service = drive('v3');
try {
const result = await service.files.list(
{
auth: oAuth2Client,
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}
);
const files = result.data.files;
if (files.length === 0) {
output.innerHTML += 'No files found.<br/>\n';
} else {
output.innerHTML += 'Files:<br>\n';
for (const file of files) {
output.innerHTML += `${file.name} (${file.id})<br/>\n`;
}
}
setTimeout(() => { alert('query completed'); }, 0);
}
catch (err) {
alert(err.toString());
}
}

addEventListener('load', runSample);
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
43 changes: 43 additions & 0 deletions src/apis/drive/samples/web/webserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2018, Google, LLC.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const fs = require('fs');
const path = require('path');
const express = require('express');
const opn = require('opn');

const keyfile = path.join(__dirname, '../oauth2.keys.json');
const keysString = fs.readFileSync(keyfile).toString();
const indexHtml = fs
.readFileSync(path.join(__dirname, 'index.html.template'))
.toString()
.replace('KEYS', keysString);

const app = express();
const appRoot = path.resolve(__dirname, '..', '..');
app.get('/drive.min.js', (req, res) => {
res.sendFile(path.join('dist', 'drive.min.js'), {
root: appRoot,
});
});
app.get(/.*/, (req, res) => {
// catch-all route: send the same index.html file
res.type('html').send(indexHtml);
});

app.listen(3000);
console.log('HTTP server is listening on port 3000.');
console.log('(Ctrl+C to exit)');

// open the browser to the main page
opn('http://localhost:3000/', {wait: false});
Loading