<commit_before>/*
*  This module is a collection of classes designed to make working with
*  the Apigee App Services API as easy as possible.
*  Learn more at http://apigee.com/docs/usergrid
*
*   Copyright 2012 Apigee Corporation
*
*  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.
*
*  @author <NAME> (<EMAIL>)
*/

var request = require('request');
var Usergrid = {};
Usergrid.USERGRID_SDK_VERSION = '0.10.07';

//authentication type constants
var AUTH_CLIENT_ID = 'CLIENT_ID';
var AUTH_APP_USER = 'APP_USER';
var AUTH_NONE = 'NONE';

  Usergrid.Client = function(options) {
    //usergrid enpoint
    this.URI = options.URI || 'https://api.usergrid.com';

    //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
    if (options.orgName) {
      this.set('orgName', options.orgName);
    }
    if (options.appName) {
      this.set('appName', options.appName);
    }

    //authentication data
    this.authType = options.authType || AUTH_NONE;
    this.clientId = options.clientId;
    this.clientSecret = options.clientSecret;
    this.token = options.token || null;

    //other options
    this.buildCurl = options.buildCurl || false;
    this.logging = options.logging || false;

    //timeout and callbacks
    this._callTimeout =  options.callTimeout || 30000; //default to 30 seconds
    this._callTimeoutCallback =  options.callTimeoutCallback || null;
    this.logoutCallback =  options.logoutCallback || null;
  };

  /*
  *  Main function for making requests to the API.  Can be called directly.
  *
  *  options object:
  *  `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
  *  `qs` - object containing querystring values to be appended to the uri
  *  `body` - object containing entity body for POST and PUT requests
  *  `endpoint` - API endpoint, for example 'users/fred'
  *  `mQuery` - boolean, set to true if running management query, defaults to false
  *
  *  @method request
  *  @public
  *  @params {object} options
  *  @param {function} callback
  *  @return {callback} callback(err, data)
  */
  Usergrid.Client.prototype.request = function (options, callback) {
    var self = this;
    var method = options.method || 'GET';
    var endpoint = options.endpoint;
    var body = options.body || {};
    var qs = options.qs || {};
    var mQuery = options.mQuery || false; //is this a query to the management endpoint?
    var orgName = this.get('orgName');
    var appName = this.get('appName');
    if(!mQuery && !orgName && !appName){
      if (typeof(this.logoutCallback) === 'function') {
        return this.logoutCallback(true, 'no_org_or_app_name_specified');
      }
    }
    if (mQuery) {
      var uri = this.URI + '/' + endpoint;
    } else {
      var uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint;
    }

    if (this.authType === AUTH_CLIENT_ID) {
      qs['client_id'] = this.clientId;
      qs['client_secret'] = this.clientSecret;
    } else if (this.authType === AUTH_APP_USER && self.getToken()) {
      qs['access_token'] = self.getToken();
    }

    if (this.logging) {
      console.log('calling: ' + method + ' ' + uri);
    }
    this._start = new Date().getTime();
    var callOptions = {
      method: method,
      uri: uri,
      json: body,
      qs: qs
    };
    request(callOptions, function (err, r, data) {
      if (self.buildCurl) {
        options.uri = r.request.uri.href;
        self.buildCurlCall(options);
      }
      self._end = new Date().getTime();
      if(r.statusCode === 200) {
        if (self.logging) {
          console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
        }
        callback(err, data);
      } else {
        err = true;
        if ((r.error === 'auth_expired_session_token') ||
          (r.error === 'auth_missing_credentials')   ||
          (r.error == 'auth_unverified_oath')       ||
          (r.error === 'expired_token')   ||
          (r.error === 'unauthorized')   ||
          (r.error === 'auth_invalid')) {
          //this error type means the user is not authorized. If a logout function is defined, call it
          var error = r.body.error;
          var errorDesc = r.body.error_description;
          if (self.logging) {
            console.log('Error (' + r.statusCode + ')(' + error + '): ' + errorDesc)
          }
          //if the user has specified a logout callback:
          if (typeof(self.logoutCallback) === 'function') {
            self.logoutCallback(err, data);
          } else  if (typeof(callback) === 'function') {
            callback(err, data);
          }
        } else {
          var error = r.body.error;
          var errorDesc = r.body.error_description;
          if (self.logging) {
            console.log('Error (' + r.statusCode + ')(' + error + '): ' + errorDesc);
          }
          if (typeof(callback) === 'function') {
            callback(err, data);
          }
        }
      }
    });
  }
  /*
   *  function for building asset urls
   *
   *  @method buildAssetURL<commit_msg>return the statusCode with the error<commit_after>/*
*  This module is a collection of classes designed to make working with
*  the Apigee App Services API as easy as possible.
*  Learn more at http://apigee.com/docs/usergrid
*
*   Copyright 2012 Apigee Corporation
*
*  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.
*
*  @author <NAME> (<EMAIL>)
*/

var request = require('request');
var Usergrid = {};
Usergrid.USERGRID_SDK_VERSION = '0.10.07';

//authentication type constants
var AUTH_CLIENT_ID = 'CLIENT_ID';
var AUTH_APP_USER = 'APP_USER';
var AUTH_NONE = 'NONE';

  Usergrid.Client = function(options) {
    //usergrid enpoint
    this.URI = options.URI || 'https://api.usergrid.com';

    //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
    if (options.orgName) {
      this.set('orgName', options.orgName);
    }
    if (options.appName) {
      this.set('appName', options.appName);
    }

    //authentication data
    this.authType = options.authType || AUTH_NONE;
    this.clientId = options.clientId;
    this.clientSecret = options.clientSecret;
    this.token = options.token || null;

    //other options
    this.buildCurl = options.buildCurl || false;
    this.logging = options.logging || false;

    //timeout and callbacks
    this._callTimeout =  options.callTimeout || 30000; //default to 30 seconds
    this._callTimeoutCallback =  options.callTimeoutCallback || null;
    this.logoutCallback =  options.logoutCallback || null;
  };

  /*
  *  Main function for making requests to the API.  Can be called directly.
  *
  *  options object:
  *  `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
  *  `qs` - object containing querystring values to be appended to the uri
  *  `body` - object containing entity body for POST and PUT requests
  *  `endpoint` - API endpoint, for example 'users/fred'
  *  `mQuery` - boolean, set to true if running management query, defaults to false
  *
  *  @method request
  *  @public
  *  @params {object} options
  *  @param {function} callback
  *  @return {callback} callback(err, data)
  */
  Usergrid.client.prototype.request = function (options, callback) {
    var self = this;
    var method = options.method || 'GET';
    var endpoint = options.endpoint;
    var body = options.body || {};
    var qs = options.qs || {};
    var mQuery = options.mQuery || false; //is this a query to the management endpoint?
    var orgName = this.get('orgName');
    var appName = this.get('appName');
    if(!mQuery && !orgName && !appName){
      if (typeof(this.logoutCallback) === 'function') {
        return this.logoutCallback(true, 'no_org_or_app_name_specified');
      }
    }
    var uri;
    if (mQuery) {
      uri = this.URI + '/' + endpoint;
    } else {
      uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint;
    }

    if (this.authType === AUTH_CLIENT_ID) {
      qs['client_id'] = this.clientId;
      qs['client_secret'] = this.clientSecret;
    } else if (this.authType === AUTH_APP_USER && self.getToken()) {
      qs['access_token'] = self.getToken();
    }

    if (this.logging) {
      console.log('calling: ' + method + ' ' + uri);
    }
    this._start = new Date().getTime();
    var callOptions = {
      method: method,
      uri: uri,
      json: body,
      qs: qs
    };
    request(callOptions, function (err, r, data) {
      if (self.buildCurl) {
        options.uri = r.request.uri.href;
        self.buildCurlCall(options);
      }
      self._end = new Date().getTime();
      if(r.statusCode === 200) {
        if (self.logging) {
          console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
        }
        callback(err, data);
      } else {
        err = true;
        data.statusCode = r.statusCode;
        if ((r.error === 'auth_expired_session_token') ||
          (r.error === 'auth_missing_credentials')   ||
          (r.error == 'auth_unverified_oath')       ||
          (r.error === 'expired_token')   ||
          (r.error === 'unauthorized')   ||
          (r.error === 'auth_invalid')) {
          //this error type means the user is not authorized. If a logout function is defined, call it
          var error = r.body.error;
          var errorDesc = r.body.error_description;
          if (self.logging) {
            console.log('Error (' + r.statusCode + ')(' + error + '): ' + errorDesc)
          }
          //if the user has specified a logout callback:
          if (typeof(self.logoutCallback) === 'function') {
            self.logoutCallback(err, data);
          } else  if (typeof(callback) === 'function') {
            callback(err, data);
          }
        } else {
          var error = r.body.error;
          var errorDesc = r.body.error_description;
          if (self.logging) {
            console.log('Error (' + r.statusCode + ')(' + error + '): ' + errorDesc);
          }
          if (typeof(callback) === 'function') {
            callback(err, data);
          }
        }
      }
    });
  };
  /*
   *  function for building asset urls
   *
   *  @method buildAssetURL
{'fraction_non_alphanumeric': 0.132509624854508, 'fraction_numerical': 0.0041185423941266005, 'mean_word_length': 2.493900531748514, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3280110', 'n_tokens_mistral': 3446, 'n_tokens_neox': 3387, 'n_words': 952}