Push the local google script file back to remote

@param {google.auth.OAuth2} auth - An authorized OAuth2 client.
@param {String} projectId - Id of the Google Apps Script project.
@returns {Promise} - A promise resolving no value
542261
function getDeployments(auth, projectId) {
    return new Promise((resolve, reject) => {
        const script = google.script('v1');
        script.projects.deployments.list({
            auth,
            scriptId: projectId,
        }, (error, deployments) => {
            if (error) {
                triageGoogleError(error, 'getDeployments').then((triaged) => {
                    reject(triaged);
                }).catch((notTriaged) => {
                    reject(notTriaged);
                });
            } else {
                resolve(deployments.data);
            }
            return;
        });
    });
}
531123
async function authWithFirebase(auth) {
    try {
        const config = {
            apiKey: constants.FIREBASE_DATABASE_PUBLIC_APIKEY,
            databaseURL: constants.FIREBASE_DATABASE_URL,
        };

        if (!firebase.apps.length) {
            firebase.initializeApp(config);
        }

        const credential = firebase.auth.GoogleAuthProvider.credential(auth.credentials.id_token);
        await firebase.auth().signInAndRetrieveDataWithCredential(credential);

        return true;
    } catch (err) {
        err.origin = 'authWithFirebase';
        await error.log(err);
        return false;
    }
}
1307095
public static function create(AuthApiInterface $authProvider, $projectId, $logger = null)
    {

        $client = self::initializeHttpClient(self::ENDPOINT_URL);

        $instance = new self($projectId, $client, $logger, self::ENDPOINT_URL);
        $instance->setAuth($authProvider);

        return $instance;
    }
1330768
private void sendAsyncAuthenticationRequest(final int appId, final String bridgeId,
      final CallStatsHttp2Client httpClient) {
    synchronized (isAuthenticationInProgress) {
      if (isAuthenticationInProgress)
        return;
      isAuthenticationInProgress = true;

    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("client_id", bridgeId + "@" + appId));
    params.add(new NameValuePair("code", tokenGenerator.generateToken(forcenewtoken)));
    params.add(new NameValuePair("grant_type", "authorization_code"));

    httpClient.sendAuthRequest(authenticateUrl, params, new CallStatsHttp2ResponseListener() {
      public void onResponse(Response response) {
        isAuthenticationInProgress = false;
        int responseStatus = response.code();
        if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
          AuthenticateResponse authResponseMessage;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessage = gson.fromJson(responseString, AuthenticateResponse.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          logger.info(
              "Authentication response " + responseStatus + " " + authResponseMessage.getToken());
          // expires = authResponseMessage.getAuthenticateBody().getExpires();
          token = authResponseMessage.getToken();
          CallStatsConfigProvider.setURLs(authResponseMessage.getMetadata().getEventsUrl(),
              authResponseMessage.getMetadata().getStatsUrl());
          listener.onInitialized(authSuccessString);
        } else if (responseStatus == CallStatsResponseStatus.INVALID_REQUEST) {
          AuthenticateResponseError authResponseMessageError;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessageError =
                gson.fromJson(responseString, AuthenticateResponseError.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          for (AuthenticateErrorAction action : authResponseMessageError.getErrorActions()) {
            if (action.getAction() == AuthenticateErrorActionType.GET_NEW_TOKEN) {
              forcenewtoken = true;
            } else if (action.getAction() == AuthenticateErrorActionType.RETRY) {
              authenticationRetryTimeout =
                  ((AuthenticateRetryActionParams) action.getParams()).getTimeout();
              scheduleAuthentication(appId, bridgeId, httpClient);
            }
          }
          listener.onError(CallStatsErrors.AUTH_ERROR, authErrString);
        } else if (responseStatus == CallStatsResponseStatus.GATEWAY_ERROR) {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.APP_CONNECTIVITY_ERROR, authErrString);
        } else {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.HTTP_ERROR, authErrString);
        }

      }


      public void onFailure(Exception e) {
        isAuthenticationInProgress = false;
        listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
      }

    });
  }
663200
function(projectName, forceRefresh) {
      var deferred = $q.defer();
      currentProject = projectName;
      var projectRules = cachedRulesByProject.get(projectName);
      var rulesResource = "selfsubjectrulesreviews";
      if (!projectRules || projectRules.forceRefresh || forceRefresh) {
        // Check if APIserver contains 'selfsubjectrulesreviews' resource. If not switch to permissive mode.
        if (APIService.apiInfo(rulesResource)) {
          // If a request is already in flight, return the promise for that request.
          if (inFlightRulesRequests[projectName]) {
            return inFlightRulesRequests[projectName];
          }

          Logger.log("AuthorizationService, loading user rules for " + projectName + " project");
          inFlightRulesRequests[projectName] = deferred.promise;
          var resourceGroupVersion = {
            kind: "SelfSubjectRulesReview",
            apiVersion: "v1"
          };
          DataService.create(rulesResource, null, resourceGroupVersion, {namespace: projectName}).then(
            function(data) {
              var normalizedData = normalizeRules(data.status.rules);
              var canUserAddToProject = canAddToProjectCheck(data.status.rules);
              cachedRulesByProject.put(projectName, {rules: normalizedData,
                                                      canAddToProject: canUserAddToProject,
                                                      forceRefresh: false,
                                                      cacheTimestamp: _.now()
                                                    });
              deferred.resolve();
            }, function() {
              permissiveMode = true;
              deferred.resolve();
          }).finally(function() {
            delete inFlightRulesRequests[projectName];
          });
        } else {
          Logger.log("AuthorizationService, resource 'selfsubjectrulesreviews' is not part of APIserver. Switching into permissive mode.");
          permissiveMode = true;
          deferred.resolve();
        }
      } else {
        // Using cached data.
        Logger.log("AuthorizationService, using cached rules for " + projectName + " project");
        if ((_.now() - projectRules.cacheTimestamp) >= 600000) {
          projectRules.forceRefresh = true;
        }
        deferred.resolve();
      }
      return deferred.promise;
    }
992020
function MongoProject(projectId, collection) {
        this.projectId = projectId;
        this._collection = collection;

        this.closeProject = function (callback) {
            var deferred = Q.defer();
            //TODO: Does this really do something?
            collection = null;
            deferred.resolve();
            return deferred.promise.nodeify(callback);
        };

        this.loadObject = function (hash, callback) {
            var deferred = Q.defer();
            if (typeof hash !== 'string') {
                deferred.reject(new Error('loadObject - given hash is not a string : ' + typeof hash));
            } else if (!REGEXP.HASH.test(hash)) {
                deferred.reject(new Error('loadObject - invalid hash :' + hash));
            } else {
                logger.debug('loadObject ' + hash);
                collection.findOne({_id: hash}, function (err, obj) {
                    if (err) {
                        logger.error(err);
                        deferred.reject(err);
                    } else if (obj) {
                        deferred.resolve(obj);
                    } else {
                        logger.error('object does not exist ' + hash);
                        deferred.reject(new Error('object does not exist ' + hash));
                    }
                });
            }

            return deferred.promise.nodeify(callback);
        };

        this.insertObject = function (object, callback) {
            var deferred = Q.defer(),
                rejected = false;
            if (object === null || typeof object !== 'object') {
                deferred.reject(new Error('object is not an object'));
                rejected = true;
            } else if (typeof object._id !== 'string' || !REGEXP.HASH.test(object._id)) {
                deferred.reject(new Error('object._id is not a valid hash.'));
                rejected = true;
            }
            if (rejected === false) {
                collection.insertOne(object, function (err) {
                    // manually check duplicate keys
                    if (err && err.code === 11000) {
                        collection.findOne({
                            _id: object._id
                        }, function (err2, data) {
                            var errMsg;
                            if (err2) {
                                deferred.reject(err2);
                            } else {
                                if (CANON.stringify(object) === CANON.stringify(data)) {
                                    logger.debug('tried to insert existing hash - the two objects were equal',
                                        object._id);
                                    deferred.resolve();
                                } else {
                                    errMsg = 'tried to insert existing hash - the two objects were NOT equal ';
                                    logger.error(errMsg, {
                                        metadata: {
                                            newObject: object,
                                            oldObject: data
                                        }
                                    });
                                    deferred.reject(new Error(errMsg + object._id));
                                }
                            }
                        });
                    } else if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            }

            return deferred.promise.nodeify(callback);
        };

        this.getBranches = function (callback) {
            var mongoFind = collection.find({
                _id: {
                    $regex: REGEXP.RAW_BRANCH.source
                }
            });

            return Q.ninvoke(mongoFind, 'toArray')
                .then(function (docs) {
                    var branches = {};
                    for (var i = 0; i < docs.length; ++i) {
                        branches[docs[i]._id.slice(1)] = docs[i].hash;
                    }
                    return Q(branches);
                })
                .nodeify(callback);
        };

        this.getBranchHash = function (branch, callback) {
            branch = '*' + branch;

            return Q.ninvoke(collection, 'findOne', {_id: branch})
                .then(function (branchObj) {
                    // FIXME: This behaviour of return empty string rather than an error is the same as before.
                    // FIXME: Consider returning with an error in style with 'Branch does not exist'.
                    return Q((branchObj && branchObj.hash) || '');
                }).nodeify(callback);
        };

        this.setBranchHash = function (branch, oldhash, newhash, callback) {
            var deferred = Q.defer();
            branch = '*' + branch;

            if (oldhash === newhash) {
                collection.findOne({
                    _id: branch
                }, function (err, obj) {
                    if (!err && oldhash !== ((obj && obj.hash) || '')) {
                        err = new Error('branch hash mismatch');
                    }
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            } else if (newhash === '') {
                collection.deleteOne({
                    _id: branch,
                    hash: oldhash
                }, function (err, result) {
                    if (!err && result.deletedCount !== 1) {
                        collection.findOne({_id: branch}, function (err, obj) {
                            if (!err && obj) {
                                err = new Error('branch hash mismatch');
                            }
                            if (err) {
                                deferred.reject(err);
                            } else {
                                deferred.resolve();
                            }
                        });
                    } else if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            } else if (oldhash === '') {
                collection.insertOne({
                    _id: branch,
                    hash: newhash
                }, function (err) {
                    if (err) {
                        if (err.code === 11000) {
                            // insertDocument :: caused by :: 11000 E11000 duplicate key error...
                            deferred.reject(new Error('branch hash mismatch'));
                        } else {
                            deferred.reject(err);
                        }
                    } else {
                        deferred.resolve();
                    }
                });
            } else {
                collection.updateOne({
                    _id: branch,
                    hash: oldhash
                }, {
                    $set: {
                        hash: newhash
                    }
                }, function (err, result) {
                    if (!err && result.modifiedCount !== 1) {
                        err = new Error('branch hash mismatch');
                    }
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            }

            return deferred.promise.nodeify(callback);
        };

        this.getCommits = function (before, number, callback) {
            var mongoFind = collection.find({
                type: CONSTANTS.COMMIT_TYPE,
                time: {
                    $lt: before
                }
            }).limit(number).sort({
                time: -1
            });

            return Q.ninvoke(mongoFind, 'toArray')
                .then(function (docs) {
                    return Q(docs);
                })
                .nodeify(callback);
        };

        this.createTag = function (name, commitHash, callback) {
            var deferred = Q.defer(),
                query = {
                    _id: self.CONSTANTS.TAGS,
                },
                update = {
                    $set: {}
                };

            query[name] = {
                $exists: false
            };

            update.$set[name] = commitHash;

            collection.updateOne(query, update, {upsert: true}, function (err/*, num*/) {
                if (err) {
                    if (err.code === 11000) {
                        deferred.reject(new Error('Tag already exists [' + name + ']'));
                    } else {
                        deferred.reject(err);
                    }
                } else {
                    deferred.resolve();
                }
            });

            return deferred.promise.nodeify(callback);
        };

        this.deleteTag = function (name, callback) {
            var deferred = Q.defer(),
                query = {
                    _id: self.CONSTANTS.TAGS,
                },
                update = {
                    $unset: {}
                };

            update.$unset[name] = '';

            collection.updateOne(query, update, function (err/*, num*/) {
                if (err) {
                    deferred.reject(err);
                } else {
                    deferred.resolve();
                }
            });

            return deferred.promise.nodeify(callback);
        };

        this.getTags = function (callback) {
            var deferred = Q.defer();

            collection.findOne({_id: self.CONSTANTS.TAGS}, {}, function (err, result) {
                if (err) {
                    deferred.reject(err);
                } else if (result) {
                    delete result._id;
                    deferred.resolve(result);
                } else {
                    deferred.resolve({});
                }
            });

            return deferred.promise.nodeify(callback);
        };

        this.traverse = function (visitFn, callback) {
            var deferred = Q.defer(),
                cursor = collection.find(),
                finished = false,
                ongoingVisits = 0,
                error = null,
                next = function (err) {
                    error = error || err;
                    ongoingVisits -= 1;
                    if (finished && ongoingVisits === 0) {
                        if (error) {
                            deferred.reject(error);
                        } else {
                            deferred.resolve();
                        }
                    }
                };

            cursor.batchSize(1000).each(function (err, object) {
                error = error || err;
                if (err === null) {
                    if (object === null) {
                        finished = true;
                    } else {
                        ongoingVisits += 1;
                        visitFn(object, next);
                    }
                } else {
                    finished = true;
                }

                if (finished && ongoingVisits === 0) {
                    if (error) {
                        deferred.reject(error);
                    } else {
                        deferred.resolve();
                    }
                }
            });

            return deferred.promise.nodeify(callback);
        };
    }
227429
function performAuth(opts) {
  var localAuth = opts.localAuth;
  return function(req, res, next) {
    if (fh && fh.auth && fh.auth.performAuth) {
      req.pause();
      fh.auth.performAuth(req, localAuth, function(err, fhres) {
        req.resume();

        if (err || !fhres) {
          next(err || new Error("No response sent by authentication endpoint"));
        } else {
          sendResponse(fhres.status, fhres.body, res, next);
        }
      });
    } else {
      return res.status(404).end();
    }
  };
}
548647
public static Object executeAsyncScript(String script, Object... args) {
        return driver().executeAsyncScript(script, args);
    }
214104
function SendMessage (auth, apiVersion) {
  if (!(this instanceof SendMessage)) return new SendMessage(auth, apiVersion)
  this._noopCallback = function () {}
  this._headers = {
    'Accept': 'application/json',
    'Authorization': 'Basic ' + auth.basicAuth
  }
  this.versionNumber = apiVersion || 'v3'
  this.lastQueryTime = 0
  this.setContextPath()
}
193567
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
    req.authClient.credentials = req.session.googleCredentials;
    return next();
  }
  res.redirect('/');
}
923346
function listFiles(auth) {
    var drive = google.drive('v3');
    drive.files.list({
        auth: auth,
        pageSize: 30,
        fields: "nextPageToken, files(id, name)"
    }, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var files = response.files;
        if (files.length == 0) {
            debug('No files found.');
        } else {
            debug('Files:');
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                debug('%s (%s)', JSON.stringify(file, null, 2), file.name, file.id);
            }
        }
    });
}
334905
async function runSample(projectId = 'your-project-id') {
  // A unique identifier for the given session
  const sessionId = uuid.v4();

  // Create a new session
  const sessionClient = new dialogflow.SessionsClient();
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        // The query to send to the dialogflow agent
        text: 'hello',
        // The language used by the client (en-US)
        languageCode: 'en-US',
      },
    },
  };

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(`  Query: ${result.queryText}`);
  console.log(`  Response: ${result.fulfillmentText}`);
  if (result.intent) {
    console.log(`  Intent: ${result.intent.displayName}`);
  } else {
    console.log(`  No intent matched.`);
  }
}
1186930
@ObjectiveCName("registerGooglePushWithProjectId:withToken:")
    public void registerGooglePush(long projectId, String token) {
        modules.getPushesModule().registerGooglePush(projectId, token);
    }
616478
async function publish(auth, rootPath) {
    // check if version does not exist yet
    // check if user is allowed to publish
    // check if version is larger than last version
    // names cant contain _- etc, maybe just stick to lowercase letters?
    // if projectKey, check that we can access the file?

    package = fs.readJsonSync(path.join(rootPath, constants.INCLUDE_FILE));
    code = fs.readJsonSync(path.join(rootPath, '.gas/publish.json'));

    const versionUrl = package.version.replace(/\./g, '_');
    // TODO
    // console.log(semver.valid(package.version));
    // console.log(versionUrl);

    try {
        const authenticated = await authWithFirebase(auth);
        const token = await firebase.auth().currentUser.getIdToken();
        const userId = firebase.auth().currentUser.uid;
        let url;
        let result;

        // Set a packageName to active
        url = `${constants.FIREBASE_DATABASE_URL}/packages/${package.name}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                status: 'active',
            },
        });

        // Patch users in a package
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/userIds/${userId}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                status: 'active',
            },
        });

        // Set version of a package to active
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/versions.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                [versionUrl]: true,
            },
        });

        // Patch a version in a package
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/version/${versionUrl}.json?auth=${token}`;
        result = await request({
            url,
            method: "PATCH",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: {
                code,
                dependencies: package.dependencies,
                description: package.description,
                homepage: package.homepage,
                license: package.license,
                readme: 'README.md',
                repository: package.repository,
                projectKey: package.projectKey,
                timestamp: {
                    ".sv": "timestamp",
                },
                userId,
            },
        });

        return true;
    } catch (err) {
        err.origin = 'test';
        await error.log(err);
        return false;
    }
}
1222760
def do_local_server_auth_flow(session_params=None, force_new_client=False):
    
    session_params = session_params or {}

    # start local server and create matching redirect_uri
    with start_local_server(listen=("127.0.0.1", 0)) as server:
        _, port = server.socket.getsockname()
        redirect_uri = "http://localhost:{}".format(port)

        # get the ConfidentialApp client object and start a flow
        auth_client = internal_auth_client(
            requires_instance=True, force_new_client=force_new_client
        )
        auth_client.oauth2_start_flow(
            refresh_tokens=True, redirect_uri=redirect_uri, requested_scopes=SCOPES
        )
        additional_params = {"prompt": "login"}
        additional_params.update(session_params)
        url = auth_client.oauth2_get_authorize_url(additional_params=additional_params)

        # open web-browser for user to log in, get auth code
        webbrowser.open(url, new=1)
        auth_code = server.wait_for_code()

    if isinstance(auth_code, LocalServerError):
        safeprint("Authorization failed: {}".format(auth_code), write_to_stderr=True)
        click.get_current_context().exit(1)
    elif isinstance(auth_code, Exception):
        safeprint(
            "Authorization failed with unexpected error:\n{}".format(auth_code),
            write_to_stderr=True,
        )
        click.get_current_context().exit(1)

    # finish auth flow and return true
    exchange_code_and_store_config(auth_client, auth_code)
    return True
1158754
function (project_id, copy_options, cb) {

            _util.buildQuery('projects/' + project_id + '/copy', copy_options, function (error, data) {

                return cb(error, data);

            });

        }
163681
async function encrypt(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  plaintextFileName = './path/to/plaintext.txt',
  ciphertextFileName = './path/to/plaintext.txt.encrypted'
) {
  const fs = require('fs');
  const {promisify} = require('util');

  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Reads the file to be encrypted
  const readFile = promisify(fs.readFile);
  const contentsBuffer = await readFile(plaintextFileName);
  const plaintext = contentsBuffer.toString('base64');
  const name = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Encrypts the file using the specified crypto key
  const [result] = await client.encrypt({name, plaintext});
  const writeFile = promisify(fs.writeFile);
  await writeFile(ciphertextFileName, Buffer.from(result.ciphertext, 'base64'));
  console.log(`Encrypted ${plaintextFileName} using ${result.name}.`);
  console.log(`Result saved to ${ciphertextFileName}.`);
}