Simple email application for Android. Original source code: https://framagit.org/dystopia-project/simple-email
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.

296 lines
8.4 KiB

  1. 'use strict';
  2. const {URL} = require('url'); // TODO: Use the `URL` global when targeting Node.js 10
  3. const util = require('util');
  4. const EventEmitter = require('events');
  5. const http = require('http');
  6. const https = require('https');
  7. const urlLib = require('url');
  8. const CacheableRequest = require('cacheable-request');
  9. const toReadableStream = require('to-readable-stream');
  10. const is = require('@sindresorhus/is');
  11. const timer = require('@szmarczak/http-timer');
  12. const timedOut = require('./utils/timed-out');
  13. const getBodySize = require('./utils/get-body-size');
  14. const getResponse = require('./get-response');
  15. const progress = require('./progress');
  16. const {CacheError, UnsupportedProtocolError, MaxRedirectsError, RequestError, TimeoutError} = require('./errors');
  17. const urlToOptions = require('./utils/url-to-options');
  18. const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
  19. const allMethodRedirectCodes = new Set([300, 303, 307, 308]);
  20. module.exports = (options, input) => {
  21. const emitter = new EventEmitter();
  22. const redirects = [];
  23. let currentRequest;
  24. let requestUrl;
  25. let redirectString;
  26. let uploadBodySize;
  27. let retryCount = 0;
  28. let shouldAbort = false;
  29. const setCookie = options.cookieJar ? util.promisify(options.cookieJar.setCookie.bind(options.cookieJar)) : null;
  30. const getCookieString = options.cookieJar ? util.promisify(options.cookieJar.getCookieString.bind(options.cookieJar)) : null;
  31. const agents = is.object(options.agent) ? options.agent : null;
  32. const get = async options => {
  33. const currentUrl = redirectString || requestUrl;
  34. if (options.protocol !== 'http:' && options.protocol !== 'https:') {
  35. throw new UnsupportedProtocolError(options);
  36. }
  37. decodeURI(currentUrl);
  38. let fn;
  39. if (is.function(options.request)) {
  40. fn = {request: options.request};
  41. } else {
  42. fn = options.protocol === 'https:' ? https : http;
  43. }
  44. if (agents) {
  45. const protocolName = options.protocol === 'https:' ? 'https' : 'http';
  46. options.agent = agents[protocolName] || options.agent;
  47. }
  48. /* istanbul ignore next: electron.net is broken */
  49. if (options.useElectronNet && process.versions.electron) {
  50. const r = ({x: require})['yx'.slice(1)]; // Trick webpack
  51. const electron = r('electron');
  52. fn = electron.net || electron.remote.net;
  53. }
  54. if (options.cookieJar) {
  55. const cookieString = await getCookieString(currentUrl, {});
  56. if (is.nonEmptyString(cookieString)) {
  57. options.headers.cookie = cookieString;
  58. }
  59. }
  60. let timings;
  61. const handleResponse = async response => {
  62. try {
  63. /* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */
  64. if (options.useElectronNet) {
  65. response = new Proxy(response, {
  66. get: (target, name) => {
  67. if (name === 'trailers' || name === 'rawTrailers') {
  68. return [];
  69. }
  70. const value = target[name];
  71. return is.function(value) ? value.bind(target) : value;
  72. }
  73. });
  74. }
  75. const {statusCode} = response;
  76. response.url = currentUrl;
  77. response.requestUrl = requestUrl;
  78. response.retryCount = retryCount;
  79. response.timings = timings;
  80. response.redirectUrls = redirects;
  81. const rawCookies = response.headers['set-cookie'];
  82. if (options.cookieJar && rawCookies) {
  83. await Promise.all(rawCookies.map(rawCookie => setCookie(rawCookie, response.url)));
  84. }
  85. if (options.followRedirect && 'location' in response.headers) {
  86. if (allMethodRedirectCodes.has(statusCode) || (getMethodRedirectCodes.has(statusCode) && (options.method === 'GET' || options.method === 'HEAD'))) {
  87. response.resume(); // We're being redirected, we don't care about the response.
  88. if (statusCode === 303) {
  89. // Server responded with "see other", indicating that the resource exists at another location,
  90. // and the client should request it from that location via GET or HEAD.
  91. options.method = 'GET';
  92. }
  93. if (redirects.length >= 10) {
  94. throw new MaxRedirectsError(statusCode, redirects, options);
  95. }
  96. // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604
  97. const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
  98. const redirectURL = new URL(redirectBuffer, currentUrl);
  99. redirectString = redirectURL.toString();
  100. redirects.push(redirectString);
  101. const redirectOpts = {
  102. ...options,
  103. ...urlToOptions(redirectURL)
  104. };
  105. for (const hook of options.hooks.beforeRedirect) {
  106. // eslint-disable-next-line no-await-in-loop
  107. await hook(redirectOpts);
  108. }
  109. emitter.emit('redirect', response, redirectOpts);
  110. await get(redirectOpts);
  111. return;
  112. }
  113. }
  114. getResponse(response, options, emitter);
  115. } catch (error) {
  116. emitter.emit('error', error);
  117. }
  118. };
  119. const handleRequest = request => {
  120. if (shouldAbort) {
  121. request.once('error', () => {});
  122. request.abort();
  123. return;
  124. }
  125. currentRequest = request;
  126. request.once('error', error => {
  127. if (request.aborted) {
  128. return;
  129. }
  130. if (error instanceof timedOut.TimeoutError) {
  131. error = new TimeoutError(error, options);
  132. } else {
  133. error = new RequestError(error, options);
  134. }
  135. if (emitter.retry(error) === false) {
  136. emitter.emit('error', error);
  137. }
  138. });
  139. timings = timer(request);
  140. progress.upload(request, emitter, uploadBodySize);
  141. if (options.gotTimeout) {
  142. timedOut(request, options.gotTimeout, options);
  143. }
  144. emitter.emit('request', request);
  145. const uploadComplete = () => {
  146. request.emit('upload-complete');
  147. };
  148. try {
  149. if (is.nodeStream(options.body)) {
  150. options.body.once('end', uploadComplete);
  151. options.body.pipe(request);
  152. options.body = undefined;
  153. } else if (options.body) {
  154. request.end(options.body, uploadComplete);
  155. } else if (input && (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH')) {
  156. input.once('end', uploadComplete);
  157. input.pipe(request);
  158. } else {
  159. request.end(uploadComplete);
  160. }
  161. } catch (error) {
  162. emitter.emit('error', new RequestError(error, options));
  163. }
  164. };
  165. if (options.cache) {
  166. const cacheableRequest = new CacheableRequest(fn.request, options.cache);
  167. const cacheReq = cacheableRequest(options, handleResponse);
  168. cacheReq.once('error', error => {
  169. if (error instanceof CacheableRequest.RequestError) {
  170. emitter.emit('error', new RequestError(error, options));
  171. } else {
  172. emitter.emit('error', new CacheError(error, options));
  173. }
  174. });
  175. cacheReq.once('request', handleRequest);
  176. } else {
  177. // Catches errors thrown by calling fn.request(...)
  178. try {
  179. handleRequest(fn.request(options, handleResponse));
  180. } catch (error) {
  181. emitter.emit('error', new RequestError(error, options));
  182. }
  183. }
  184. };
  185. emitter.retry = error => {
  186. let backoff;
  187. try {
  188. backoff = options.retry.retries(++retryCount, error);
  189. } catch (error2) {
  190. emitter.emit('error', error2);
  191. return;
  192. }
  193. if (backoff) {
  194. const retry = async options => {
  195. try {
  196. for (const hook of options.hooks.beforeRetry) {
  197. // eslint-disable-next-line no-await-in-loop
  198. await hook(options, error, retryCount);
  199. }
  200. await get(options);
  201. } catch (error) {
  202. emitter.emit('error', error);
  203. }
  204. };
  205. setTimeout(retry, backoff, {...options, forceRefresh: true});
  206. return true;
  207. }
  208. return false;
  209. };
  210. emitter.abort = () => {
  211. if (currentRequest) {
  212. currentRequest.once('error', () => {});
  213. currentRequest.abort();
  214. } else {
  215. shouldAbort = true;
  216. }
  217. };
  218. setImmediate(async () => {
  219. try {
  220. // Convert buffer to stream to receive upload progress events (#322)
  221. const {body} = options;
  222. if (is.buffer(body)) {
  223. options.body = toReadableStream(body);
  224. uploadBodySize = body.length;
  225. } else {
  226. uploadBodySize = await getBodySize(options);
  227. }
  228. if (is.undefined(options.headers['content-length']) && is.undefined(options.headers['transfer-encoding'])) {
  229. if ((uploadBodySize > 0 || options.method === 'PUT') && !is.null(uploadBodySize)) {
  230. options.headers['content-length'] = uploadBodySize;
  231. }
  232. }
  233. for (const hook of options.hooks.beforeRequest) {
  234. // eslint-disable-next-line no-await-in-loop
  235. await hook(options);
  236. }
  237. requestUrl = options.href || (new URL(options.path, urlLib.format(options))).toString();
  238. await get(options);
  239. } catch (error) {
  240. emitter.emit('error', error);
  241. }
  242. });
  243. return emitter;
  244. };