<commit_before>// Appium webserver controller methods
// https://github.com/hugs/appium/blob/master/appium/server.py
"use strict";
var status = require('./uiauto/lib/status')
  , logger = require('../logger.js').get('appium')
  , _s = require("underscore.string")
  , _ = require('underscore');

function getResponseHandler(req, res) {
  var responseHandler = function(err, response) {
    if (typeof response === "undefined" || response === null) {
      response = {};
    }
    if (err !== null && typeof err !== "undefined") {
      if (typeof err.name !== 'undefined') {
        if (err.name == 'NotImplementedError') {
          notImplementedInThisContext(req, res);
        } else if (err.name == "NotYetImplementedError") {
          exports.notYetImplemented(req, res);
        }
      } else {
        var value = response.value;
        if (typeof value === "undefined") {
          value = '';
        }
        respondError(req, res, err.message, value);
      }
    } else {
      if (response.status === 0) {
        respondSuccess(req, res, response.value, response.sessionId);
      } else {
        respondError(req, res, response.status, response.value);
      }
    }
  };
  return responseHandler;
}

var getSessionId = function(req, response) {
  var sessionId = (typeof response == 'undefined') ? undefined : response.sessionId;
  if (typeof sessionId === "undefined") {
    if (req.appium) {
      sessionId = req.appium.sessionId || null;
    } else {
      sessionId = null;
    }
  }
  if (typeof sessionId !== "string" && sessionId !== null) {
    sessionId = null;
  }
  return sessionId;
};

var respondError = function(req, res, statusObj, value) {
  var code = 1, message = "An unknown error occurred";
  var newValue = value;
  if (typeof statusObj === "string") {
    message = statusObj;
  } else if (typeof statusObj === "undefined") {
    message = "undefined status object";
  } else if (typeof statusObj === "number") {
    code = statusObj;
    message = status.getSummaryByCode(code);
  } else if (typeof statusObj.code !== "undefined") {
    code = statusObj.code;
    message = statusObj.summary;
  } else if (typeof statusObj.message !== "undefined") {
    message = statusObj.message;
  }

  if (typeof newValue === "object") {
    newValue = _.extend({message: message}, value);
  }
  var response = {status: code, value: newValue};
  response.sessionId = getSessionId(req, response);
  logger.info("Responding to client with error: " + JSON.stringify(response));
  res.send(500, response);
};

var respondSuccess = function(req, res, value, sid) {
  var response = {status: status.codes.Success.code, value: value};
  response.sessionId = getSessionId(req, response) || sid;
  if (typeof response.value === "undefined") {
    response.value = '';
  }
  logger.info("Responding to client with success: " + JSON.stringify(response));
  res.send(response);
};

var checkMissingParams = function(res, params) {
  var missingParamNames = [];
  _.each(params, function(param, paramName) {
    if (typeof param === "undefined") {
      missingParamNames.push(paramName);
    }
  });
  if (missingParamNames.length > 0) {
    var missingList = JSON.stringify(missingParamNames);
    logger.info("Missing params for request: " + missingList);
    res.send(400, "Missing parameters: " + missingList);
    return false;
  } else {
    return true;
  }
};

exports.sessionBeforeFilter = function(req, res, next) {
  var match = new RegExp("([^/]+)").exec(req.params[0]);
  var sessId = match ? match[1] : null;
  // if we don't actually have a valid session, respond with an error
  if (sessId && (!req.device || req.appium.sessionId != sessId)) {
    res.send(404, {sessionId: null, status: status.codes.NoSuchDriver.code, value: ''});
  } else {
    next();
  }
};

exports.getStatus = function(req, res) {
  // Return a static JSON object to the client
  respondSuccess(req, res, {
    build: {version: 'Appium 1.0'}
  });
};

exports.createSession = function(req, res) {
  if (typeof req.body === 'string') {
    req.body = JSON.parse(req.body);
  }

  var desired = req.body.desiredCapabilities;

  var next = function(reqOrigin, sessionId, device, preLaunched) {
    var redirect = function() {
      res.set('Location', "http://"+reqOrigin+"/wd/hub/session/" + sessionId);
      res.send(303);
    };
    if (desired && desired.newCommandTimeout) {
      device.setCommandTimeout(desired.newCommandTimeout, redirect);
    } else if (preLaunched) {
      // reset timeout to something more reasonable
      device.resetCommandTimeout(redirect);
    } else {
      redirect();
    }
  };
  if (req.appium.preLaunched && req.appium.sessionId) {
    req.appium.preLaunched = false;
    next(req.headers.host, req.appium.sessionId, req.appium.device, true);
  } else {
    req.appium.start(req.body.desiredCapabilities, function(err, instance) {
      if (err) {
        logger.error("Failed to start an Appium session, err was: " + err);
        respondError(req, res, status.codes.NoSuchDriver, err);
      } else {
        logger.info("Appium session started with sessionId " + req.appium.sessionId);
        next(req.headers.host, req.appium.sessionId, instance);
      }
    });<commit_msg>Because it's not origin when you connect to appium without selenium-grid =/<commit_after>// Appium webserver controller methods
// https://github.com/hugs/appium/blob/master/appium/server.py
"use strict";
var status = require('./uiauto/lib/status')
  , logger = require('../logger.js').get('appium')
  , _s = require("underscore.string")
  , _ = require('underscore');

function getResponseHandler(req, res) {
  var responseHandler = function(err, response) {
    if (typeof response === "undefined" || response === null) {
      response = {};
    }
    if (err !== null && typeof err !== "undefined") {
      if (typeof err.name !== 'undefined') {
        if (err.name == 'NotImplementedError') {
          notImplementedInThisContext(req, res);
        } else if (err.name == "NotYetImplementedError") {
          exports.notYetImplemented(req, res);
        }
      } else {
        var value = response.value;
        if (typeof value === "undefined") {
          value = '';
        }
        respondError(req, res, err.message, value);
      }
    } else {
      if (response.status === 0) {
        respondSuccess(req, res, response.value, response.sessionId);
      } else {
        respondError(req, res, response.status, response.value);
      }
    }
  };
  return responseHandler;
}

var getSessionId = function(req, response) {
  var sessionId = (typeof response == 'undefined') ? undefined : response.sessionId;
  if (typeof sessionId === "undefined") {
    if (req.appium) {
      sessionId = req.appium.sessionId || null;
    } else {
      sessionId = null;
    }
  }
  if (typeof sessionId !== "string" && sessionId !== null) {
    sessionId = null;
  }
  return sessionId;
};

var respondError = function(req, res, statusObj, value) {
  var code = 1, message = "An unknown error occurred";
  var newValue = value;
  if (typeof statusObj === "string") {
    message = statusObj;
  } else if (typeof statusObj === "undefined") {
    message = "undefined status object";
  } else if (typeof statusObj === "number") {
    code = statusObj;
    message = status.getSummaryByCode(code);
  } else if (typeof statusObj.code !== "undefined") {
    code = statusObj.code;
    message = statusObj.summary;
  } else if (typeof statusObj.message !== "undefined") {
    message = statusObj.message;
  }

  if (typeof newValue === "object") {
    newValue = _.extend({message: message}, value);
  }
  var response = {status: code, value: newValue};
  response.sessionId = getSessionId(req, response);
  logger.info("Responding to client with error: " + JSON.stringify(response));
  res.send(500, response);
};

var respondSuccess = function(req, res, value, sid) {
  var response = {status: status.codes.Success.code, value: value};
  response.sessionId = getSessionId(req, response) || sid;
  if (typeof response.value === "undefined") {
    response.value = '';
  }
  logger.info("Responding to client with success: " + JSON.stringify(response));
  res.send(response);
};

var checkMissingParams = function(res, params) {
  var missingParamNames = [];
  _.each(params, function(param, paramName) {
    if (typeof param === "undefined") {
      missingParamNames.push(paramName);
    }
  });
  if (missingParamNames.length > 0) {
    var missingList = JSON.stringify(missingParamNames);
    logger.info("Missing params for request: " + missingList);
    res.send(400, "Missing parameters: " + missingList);
    return false;
  } else {
    return true;
  }
};

exports.sessionBeforeFilter = function(req, res, next) {
  var match = new RegExp("([^/]+)").exec(req.params[0]);
  var sessId = match ? match[1] : null;
  // if we don't actually have a valid session, respond with an error
  if (sessId && (!req.device || req.appium.sessionId != sessId)) {
    res.send(404, {sessionId: null, status: status.codes.NoSuchDriver.code, value: ''});
  } else {
    next();
  }
};

exports.getStatus = function(req, res) {
  // Return a static JSON object to the client
  respondSuccess(req, res, {
    build: {version: 'Appium 1.0'}
  });
};

exports.createSession = function(req, res) {
  if (typeof req.body === 'string') {
    req.body = JSON.parse(req.body);
  }

  var desired = req.body.desiredCapabilities;

  var next = function(reqHost, sessionId, device, preLaunched) {
    var redirect = function() {
      res.set('Location', "http://"+reqHost+"/wd/hub/session/" + sessionId);
      res.send(303);
    };
    if (desired && desired.newCommandTimeout) {
      device.setCommandTimeout(desired.newCommandTimeout, redirect);
    } else if (preLaunched) {
      // reset timeout to something more reasonable
      device.resetCommandTimeout(redirect);
    } else {
      redirect();
    }
  };
  if (req.appium.preLaunched && req.appium.sessionId) {
    req.appium.preLaunched = false;
    next(req.headers.host, req.appium.sessionId, req.appium.device, true);
  } else {
    req.appium.start(req.body.desiredCapabilities, function(err, instance) {
      if (err) {
        logger.error("Failed to start an Appium session, err was: " + err);
        respondError(req, res, status.codes.NoSuchDriver, err);
      } else {
        logger.info("Appium session started with sessionId " + req.appium.sessionId);
        next(req.headers.host, req.appium.sessionId, instance);
      }
    });
{'fraction_non_alphanumeric': 0.14956290383884455, 'fraction_numerical': 0.0036107943747624477, 'mean_word_length': 3.21, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, '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': '1408808', 'n_tokens_mistral': 3266, 'n_tokens_neox': 3214, 'n_words': 793}