Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request.js 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5. }) : (function(o, m, k, k2) {
  6. if (k2 === undefined) k2 = k;
  7. o[k2] = m[k];
  8. }));
  9. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11. }) : function(o, v) {
  12. o["default"] = v;
  13. });
  14. var __importStar = (this && this.__importStar) || function (mod) {
  15. if (mod && mod.__esModule) return mod;
  16. var result = {};
  17. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  18. __setModuleDefault(result, mod);
  19. return result;
  20. };
  21. var __importDefault = (this && this.__importDefault) || function (mod) {
  22. return (mod && mod.__esModule) ? mod : { "default": mod };
  23. };
  24. Object.defineProperty(exports, "__esModule", { value: true });
  25. const path_1 = __importDefault(require("path"));
  26. const http_1 = __importDefault(require("http"));
  27. const https_1 = __importDefault(require("https"));
  28. const events_1 = require("events");
  29. const got = __importStar(require("got"));
  30. const logger_1 = __importDefault(require("@wdio/logger"));
  31. const utils_1 = require("@wdio/utils");
  32. const utils_2 = require("./utils");
  33. const pkg = require('../package.json');
  34. const DEFAULT_HEADERS = {
  35. 'Content-Type': 'application/json; charset=utf-8',
  36. 'Connection': 'keep-alive',
  37. 'Accept': 'application/json',
  38. 'User-Agent': 'webdriver/' + pkg.version
  39. };
  40. const log = logger_1.default('webdriver');
  41. const agents = {
  42. http: new http_1.default.Agent({ keepAlive: true }),
  43. https: new https_1.default.Agent({ keepAlive: true })
  44. };
  45. class WebDriverRequest extends events_1.EventEmitter {
  46. constructor(method, endpoint, body, isHubCommand = false) {
  47. super();
  48. this.defaultOptions = {
  49. retry: 0,
  50. followRedirect: true,
  51. responseType: 'json',
  52. throwHttpErrors: false
  53. };
  54. this.body = body;
  55. this.method = method;
  56. this.endpoint = endpoint;
  57. this.isHubCommand = isHubCommand;
  58. this.requiresSessionId = Boolean(this.endpoint.match(/:sessionId/));
  59. }
  60. makeRequest(options, sessionId) {
  61. let fullRequestOptions = Object.assign({
  62. method: this.method
  63. }, this.defaultOptions, this._createOptions(options, sessionId));
  64. if (typeof options.transformRequest === 'function') {
  65. fullRequestOptions = options.transformRequest(fullRequestOptions);
  66. }
  67. this.emit('request', fullRequestOptions);
  68. return this._request(fullRequestOptions, options.transformResponse, options.connectionRetryCount, 0);
  69. }
  70. _createOptions(options, sessionId) {
  71. const requestOptions = {
  72. https: {},
  73. agent: options.agent || agents,
  74. headers: {
  75. ...DEFAULT_HEADERS,
  76. ...(typeof options.headers === 'object' ? options.headers : {})
  77. },
  78. searchParams: typeof options.queryParams === 'object' ? options.queryParams : {},
  79. timeout: options.connectionRetryTimeout
  80. };
  81. if (this.body && (Object.keys(this.body).length || this.method === 'POST')) {
  82. const contentLength = Buffer.byteLength(JSON.stringify(this.body), 'utf8');
  83. requestOptions.json = this.body;
  84. requestOptions.headers['Content-Length'] = `${contentLength}`;
  85. }
  86. let endpoint = this.endpoint;
  87. if (this.requiresSessionId) {
  88. if (!sessionId) {
  89. throw new Error('A sessionId is required for this command');
  90. }
  91. endpoint = endpoint.replace(':sessionId', sessionId);
  92. }
  93. requestOptions.url = new URL(`${options.protocol}://` +
  94. `${options.hostname}:${options.port}` +
  95. (this.isHubCommand ? this.endpoint : path_1.default.join(options.path || '', endpoint)));
  96. if (this.endpoint === '/session' && options.user && options.key) {
  97. requestOptions.username = options.user;
  98. requestOptions.password = options.key;
  99. }
  100. requestOptions.https.rejectUnauthorized = !(options.strictSSL === false ||
  101. process.env.STRICT_SSL === 'false' ||
  102. process.env.strict_ssl === 'false');
  103. return requestOptions;
  104. }
  105. async _request(fullRequestOptions, transformResponse, totalRetryCount = 0, retryCount = 0) {
  106. log.info(`[${fullRequestOptions.method}] ${fullRequestOptions.url.href}`);
  107. if (fullRequestOptions.json && Object.keys(fullRequestOptions.json).length) {
  108. log.info('DATA', utils_1.transformCommandLogResult(fullRequestOptions.json));
  109. }
  110. const { url, ...gotOptions } = fullRequestOptions;
  111. let response = await got.default(url, gotOptions)
  112. .catch((err) => err);
  113. const retry = (error, msg) => {
  114. if (retryCount >= totalRetryCount || error.message.includes('invalid session id')) {
  115. log.error(`Request failed with status ${response.statusCode} due to ${error}`);
  116. this.emit('response', { error });
  117. throw error;
  118. }
  119. ++retryCount;
  120. this.emit('retry', { error, retryCount });
  121. log.warn(msg);
  122. log.info(`Retrying ${retryCount}/${totalRetryCount}`);
  123. return this._request(fullRequestOptions, transformResponse, totalRetryCount, retryCount);
  124. };
  125. if (response instanceof Error) {
  126. if (response.code === 'ETIMEDOUT') {
  127. return retry(response, 'Request timed out! Consider increasing the "connectionRetryTimeout" option.');
  128. }
  129. throw response;
  130. }
  131. if (typeof transformResponse === 'function') {
  132. response = transformResponse(response, fullRequestOptions);
  133. }
  134. const error = utils_2.getErrorFromResponseBody(response.body);
  135. if (this.isHubCommand) {
  136. if (typeof response.body === 'string' && response.body.startsWith('<!DOCTYPE html>')) {
  137. return Promise.reject(new Error('Command can only be called to a Selenium Hub'));
  138. }
  139. return { value: response.body || null };
  140. }
  141. if (utils_2.isSuccessfulResponse(response.statusCode, response.body)) {
  142. this.emit('response', { result: response.body });
  143. return response.body;
  144. }
  145. if (error.name === 'stale element reference') {
  146. log.warn('Request encountered a stale element - terminating request');
  147. this.emit('response', { error });
  148. throw error;
  149. }
  150. return retry(error, `Request failed with status ${response.statusCode} due to ${error.message}`);
  151. }
  152. }
  153. exports.default = WebDriverRequest;