How to use the googleapis.drive function in googleapis

To help you get started, we’ve selected a few googleapis examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mhawksey / Cloud-Functions-for-Firebase-in-Google-Apps-Script / src / index.js View on Github external
var token = req.query.token;
	var filename = req.query.filename || "temp_file";
	
	// writing to the Firebase log https://firebase.google.com/docs/functions/writing-and-viewing-logs 
	console.log(filename);
	
	// handling auth to write file to Drive
	var auth = new googleAuth();
	var oauth2Client = new auth.OAuth2();
	oauth2Client.setCredentials({
		access_token: token
	});

	// setting Drive access
	var drive = google.drive('v3');
	
	var media = {
		body: request(req.query.url)  //stream!
	};
	
	// create file on Drive
	drive.files.create({
			resource: {'name': filename},
			media: media,
			fields: 'id',
			auth: oauth2Client
		}, function(err, file) {
			if (err) {
				// Handle error
				console.log(err);
				res.send(err);
github Autodesk-Forge / forge-view.googledrive.models / server / model.derivative.google.drive.integration.js View on Github external
tokenSession.getTokenInternal(function (tokenInternal) {

    oauth2Client.setCredentials({
      access_token: tokenSession.getGoogleToken()
    });
    var drive = google.drive({version: 'v2', auth: oauth2Client});


    var people = google.people({version: 'v1', auth: oauth2Client});
    people.people.get({ resourceName: 'people/me', personFields: 'emailAddresses,names' }, function (err, user) {
      if (err || user == null) {
        console.log('model.derivative.google.drive.integration:sentToTranslation:google.user.get => ' + err);
        res.status(500).json({error: 'Cannot get Google user information, please try again.'});
        return;
      }

      // ForgeSDK OSS Bucket Name: username + userId (no spaces, lower case)
      // that way we have one bucket for each Google account using this application
      var ossBucketKey = 
          config.credentials.client_id.toLowerCase() + 
          (
            user.names[0].displayName.replace(/\W+/g, '') +
github thejinx0r / node-gdrive-fuse / src / common.es6.js View on Github external
if(!config.refreshDelay)
	config.refreshDelay = 60000;

var maxCache;
if(config.maxCacheSize){
   maxCache =  config.maxCacheSize * 1024 * 1024;
}else{
  logger.info( "max cache size was not set. you should exit and manually set it");
  logger.info( "defaulting to a 10 GB cache");
   maxCache = 10737418240;
}


// setup oauth client
const google = require('googleapis');
const GDrive = google.drive({ version: 'v2' });
const OAuth2Client = google.auth.OAuth2;
const oauth2Client = new OAuth2Client(config.clientId || "520595891712-6n4r5q6runjds8m5t39rbeb6bpa3bf6h.apps.googleusercontent.com"  , config.clientSecret || "cNy6nr-immKnVIzlUsvKgSW8", config.redirectUrl || "urn:ietf:wg:oauth:2.0:oob");
oauth2Client.setCredentials(config.accessToken);
google.options({ auth: oauth2Client });

// ensure directory exist for upload, download and data folders
const uploadLocation = pth.join(config.cacheLocation, 'upload');
fs.ensureDirSync(uploadLocation);
const downloadLocation = pth.join(config.cacheLocation, 'download');
fs.ensureDirSync(downloadLocation);
const dataLocation = pth.join(config.cacheLocation, 'data');
fs.ensureDirSync(dataLocation);

function printDate(){
  const d = new Date();
  return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}T${d.getHours()}:${d.getMinutes()}::${d.getSeconds()}`;
github omriiluz / gdrive-sync / gsync.js View on Github external
function discoverGAPI(callback){
  auth = new googleapis.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
  auth.credentials=tokens;
  googleapis.options({auth: auth});
  drive = googleapis.drive('v2')
  callback();
}
github acucciniello / alexa-open-doc / google / list-files.js View on Github external
module.exports = function listFiles (auth, callback) {
  var service = google.drive('v3')
  service.files.list({
    auth: auth,
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)'
  }, function (err, response) {
    if (err) {
      var apiError = 'The API return an error: ' + err
      callback(apiError)
      return
    }
    var files = response.files
    if (files.length === 0) {
      var noFilesFound = 'No files found.'
      callback(noFilesFound)
    } else {
      callback(null, files)
github thkl / homebridge-homematic / ChannelServices / google_drive.js View on Github external
function uploadPicture (folder, prefix, picture) {
  var drive = Google.drive('v3')
  var d = new Date()
  var parsedUrl = url.parse(prefix.substr(prefix.search('http')), true, true)
  var name = prefix.replace(/ /g, '_') + '_' + d.toLocaleString().replace(/ /g, '_').replace(/,/g, '') + '.jpeg'

  debug('upload picture', folder, name)

  var fileMetadata = {
    'name': name,
    parents: [folder]
  }
  var media = {
    mimeType: 'image/jpeg',
    body: picture
  }

  drive.files.create({
github paulirish / pwmetrics / lib / drive / gdrive.ts View on Github external
async setSharingPermissions(fileId: string): Promise {
    try {
      const drive = google.drive({
        version: 'v3',
        auth: await this.getOauth()
      });

      const body = {
        resource: {
          'type': 'anyone',
          'role': 'writer'
        },
        fileId: fileId
      };

      return await promisify(drive.permissions.create)(body);
    } catch (error) {
      throw new Error(error);
    }
github brownplt / code.pyret.org / src / server.js View on Github external
function getDriveClient(token, version) {
    var client = new gapi.auth.OAuth2(
        config.google.clientId,
        config.google.clientSecret,
        config.baseUrl + config.google.redirect
      );
    client.setCredentials({
      access_token: token
    });

    var drive = gapi.drive({ version: version, auth: client });
    return drive;
  }
github paulirish / pwmetrics / lib / drive / gdrive.ts View on Github external
async uploadToDrive(data: any, fileName: string): Promise {
    try {
      logger.log(messages.getMessage('G_DRIVE_UPLOADING'));
      const drive = google.drive({
        version: 'v3',
        auth: await this.getOauth()
      });

      const body = {
        resource: {
          name: fileName,
          mimeType: 'application/json',
        },
        media: {
          mimeType: 'application/json',
          body: JSON.stringify(data)
        }
      };

      const driveResponse: DriveResponse = await promisify(drive.files.create)(body);
github soixantecircuits / altruist / actions / googledrive.js View on Github external
var userProfile = JSON.parse(localStorage.getItem('googledrive-profile')) || {}
var uploadDirectoryID = settings.actions.googledrive.uploadDirectoryID ? settings.actions.googledrive.uploadDirectoryID : ''

const loginURL = settings.actions.googledrive.loginURL || '/login/gdrive'
const callbackURL = settings.actions.googledrive.callbackURL || '/login/gdrive/return'
const failureURL = settings.actions.googledrive.failureURL || '/?failure=drive'
const successURL = settings.actions.googledrive.successURL || '/?success=drive'
const profileURL = settings.actions.googledrive.profileURL || '/profile/gdrive'

var OAuth2 = google.auth.OAuth2
var googleAuth = new OAuth2(
  settings.actions.googledrive.clientID,
  settings.actions.googledrive.clientSecret,
  settings.actions.googledrive.callbackURL
)
var drive = google.drive({ version: 'v3', auth: googleAuth })

function storeTokens (atoken, rtoken) {
  driveSession.accessToken = atoken
  driveSession.refreshToken = rtoken
  localStorage.setItem('googledrive-session', JSON.stringify(driveSession))
}

function storeProfile (profile) {
  userProfile = profile
  localStorage.setItem('googledrive-profile', JSON.stringify(userProfile))
}

function uploadFile (options, resolve, reject) {
  let fileResource = {
    name: (options.filename && options.filename !== '') ? options.filename : options.media.filename,
    mimeType: options.media.contentType