Sin descripción

XMLHttpRequest.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import RNFetchBlob from '../index.js'
  5. import XMLHttpRequestEventTarget from './XMLHttpRequestEventTarget.js'
  6. import Log from '../utils/log.js'
  7. import Blob from './Blob.js'
  8. import ProgressEvent from './ProgressEvent.js'
  9. const log = new Log('XMLHttpRequest')
  10. log.disable()
  11. // log.level(3)
  12. const UNSENT = 0
  13. const OPENED = 1
  14. const HEADERS_RECEIVED = 2
  15. const LOADING = 3
  16. const DONE = 4
  17. export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
  18. _onreadystatechange : () => void;
  19. upload : XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
  20. static binaryContentTypes : Array<string> = [
  21. 'image/', 'video/', 'audio/'
  22. ];
  23. // readonly
  24. _readyState : number = UNSENT;
  25. _uriType : 'net' | 'file' = 'net';
  26. _response : any = '';
  27. _responseText : any = '';
  28. _responseHeaders : any = {};
  29. _responseType : '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' = '';
  30. // TODO : not suppoted ATM
  31. _responseURL : null = '';
  32. _responseXML : null = '';
  33. _status : number = 0;
  34. _statusText : string = '';
  35. _timeout : number = 60000;
  36. _sendFlag : boolean = false;
  37. _uploadStarted : boolean = false;
  38. _increment : boolean = false;
  39. // RNFetchBlob compatible data structure
  40. _config : RNFetchBlobConfig = {};
  41. _url : any;
  42. _method : string;
  43. _headers: any = {
  44. 'Content-Type' : 'text/plain'
  45. };
  46. _body: any;
  47. // RNFetchBlob promise object, which has `progress`, `uploadProgress`, and
  48. // `cancel` methods.
  49. _task: any;
  50. // constants
  51. get UNSENT() { return UNSENT }
  52. get OPENED() { return OPENED }
  53. get HEADERS_RECEIVED() { return HEADERS_RECEIVED }
  54. get LOADING() { return LOADING }
  55. get DONE() { return DONE }
  56. static get UNSENT() {
  57. return UNSENT
  58. }
  59. static get OPENED() {
  60. return OPENED
  61. }
  62. static get HEADERS_RECEIVED() {
  63. return HEADERS_RECEIVED
  64. }
  65. static get LOADING() {
  66. return LOADING
  67. }
  68. static get DONE() {
  69. return DONE
  70. }
  71. static addBinaryContentType(substr:string) {
  72. for(let i in XMLHttpRequest.binaryContentTypes) {
  73. if(new RegExp(substr,'i').test(XMLHttpRequest.binaryContentTypes[i])) {
  74. return
  75. }
  76. }
  77. XMLHttpRequest.binaryContentTypes.push(substr)
  78. }
  79. static removeBinaryContentType(val) {
  80. for(let i in XMLHttpRequest.binaryContentTypes) {
  81. if(new RegExp(substr,'i').test(XMLHttpRequest.binaryContentTypes[i])) {
  82. XMLHttpRequest.binaryContentTypes.splice(i,1)
  83. return
  84. }
  85. }
  86. }
  87. constructor() {
  88. log.verbose('XMLHttpRequest constructor called')
  89. super()
  90. }
  91. /**
  92. * XMLHttpRequest.open, always async, user and password not supported. When
  93. * this method invoked, headers should becomes empty again.
  94. * @param {string} method Request method
  95. * @param {string} url Request URL
  96. * @param {true} async Always async
  97. * @param {any} user NOT SUPPORTED
  98. * @param {any} password NOT SUPPORTED
  99. */
  100. open(method:string, url:string, async:true, user:any, password:any) {
  101. log.verbose('XMLHttpRequest open ', method, url, async, user, password)
  102. this._method = method
  103. this._url = url
  104. this._headers = {}
  105. this._increment = /^JSONStream\:\/\//.test(this._url)
  106. this._url = this._url.replace(/^JSONStream\:\/\//, '')
  107. this._dispatchReadStateChange(XMLHttpRequest.OPENED)
  108. }
  109. /**
  110. * Invoke this function to send HTTP request, and set body.
  111. * @param {any} body Body in RNfetchblob flavor
  112. */
  113. send(body) {
  114. this._body = body
  115. if(this._readyState !== XMLHttpRequest.OPENED)
  116. throw 'InvalidStateError : XMLHttpRequest is not opened yet.'
  117. let promise = Promise.resolve()
  118. this._sendFlag = true
  119. log.verbose('XMLHttpRequest send ', body)
  120. let {_method, _url, _headers } = this
  121. log.verbose('sending request with args', _method, _url, _headers, body)
  122. log.verbose(typeof body, body instanceof FormData)
  123. if(body instanceof Blob) {
  124. log.debug('sending blob body', body._blobCreated)
  125. promise = new Promise((resolve, reject) => {
  126. body.onCreated((blob) => {
  127. log.debug('body created send request')
  128. body = RNFetchBlob.wrap(blob.getRNFetchBlobRef())
  129. resolve()
  130. })
  131. })
  132. }
  133. else if(typeof body === 'object') {
  134. body = JSON.stringify(body)
  135. promise = Promise.resolve()
  136. }
  137. else {
  138. body = body ? body.toString() : body
  139. promise = Promise.resolve()
  140. }
  141. promise.then(() => {
  142. log.debug('send request invoke', body)
  143. for(let h in _headers) {
  144. _headers[h] = _headers[h].toString()
  145. }
  146. this._task = RNFetchBlob
  147. .config({
  148. auto: true,
  149. timeout : this._timeout,
  150. increment : this._increment,
  151. binaryContentTypes : XMLHttpRequest.binaryContentTypes
  152. })
  153. .fetch(_method, _url, _headers, body)
  154. this._task
  155. .stateChange(this._headerReceived.bind(this))
  156. .uploadProgress(this._uploadProgressEvent.bind(this))
  157. .progress(this._progressEvent.bind(this))
  158. .catch(this._onError.bind(this))
  159. .then(this._onDone.bind(this))
  160. })
  161. }
  162. overrideMimeType(mime:string) {
  163. log.verbose('XMLHttpRequest overrideMimeType', mime)
  164. this._headers['Content-Type'] = mime
  165. }
  166. setRequestHeader(name, value) {
  167. log.verbose('XMLHttpRequest set header', name, value)
  168. if(this._readyState !== OPENED || this._sendFlag) {
  169. throw `InvalidStateError : Calling setRequestHeader in wrong state ${this._readyState}`
  170. }
  171. // UNICODE SHOULD NOT PASS
  172. if(typeof name !== 'string' || /[^\u0000-\u00ff]/.test(name)) {
  173. throw 'TypeError : header field name should be a string'
  174. }
  175. //
  176. let invalidPatterns = [
  177. /[\(\)\>\<\@\,\:\\\/\[\]\?\=\}\{\s\ \u007f\;\t\0\v\r]/,
  178. /tt/
  179. ]
  180. for(let i in invalidPatterns) {
  181. if(invalidPatterns[i].test(name) || typeof name !== 'string') {
  182. throw `SyntaxError : Invalid header field name ${name}`
  183. }
  184. }
  185. this._headers[name] = value
  186. }
  187. abort() {
  188. log.verbose('XMLHttpRequest abort ')
  189. if(!this._task)
  190. return
  191. this._task.cancel((err) => {
  192. let e = {
  193. timeStamp : Date.now(),
  194. }
  195. if(this.onabort)
  196. this.onabort()
  197. if(err) {
  198. e.detail = err
  199. e.type = 'error'
  200. this.dispatchEvent('error', e)
  201. }
  202. else {
  203. e.type = 'abort'
  204. this.dispatchEvent('abort', e)
  205. }
  206. })
  207. }
  208. getResponseHeader(field:string):string | null {
  209. log.verbose('XMLHttpRequest get header', field, this._responseHeaders)
  210. if(!this._responseHeaders)
  211. return null
  212. return (this._responseHeaders[field] || this._responseHeaders[field.toLowerCase()]) || null
  213. }
  214. getAllResponseHeaders():string | null {
  215. log.verbose('XMLHttpRequest get all headers', this._responseHeaders)
  216. if(!this._responseHeaders)
  217. return ''
  218. let result = ''
  219. let respHeaders = this.responseHeaders
  220. for(let i in respHeaders) {
  221. result += `${i}: ${respHeaders[i]}${String.fromCharCode(0x0D,0x0A)}`
  222. }
  223. return result.substr(0, result.length-2)
  224. }
  225. _headerReceived(e) {
  226. log.debug('header received ', this._task.taskId, e)
  227. this.responseURL = this._url
  228. if(e.state === "2") {
  229. this._responseHeaders = e.headers
  230. this._statusText = e.status
  231. this._responseType = e.respType || ''
  232. this._status = Math.floor(e.status)
  233. this._dispatchReadStateChange(XMLHttpRequest.HEADERS_RECEIVED)
  234. }
  235. }
  236. _uploadProgressEvent(send:number, total:number) {
  237. if(!this._uploadStarted) {
  238. this.upload.dispatchEvent('loadstart')
  239. this._uploadStarted = true
  240. }
  241. if(send >= total)
  242. this.upload.dispatchEvent('load')
  243. this.upload.dispatchEvent('progress', new ProgressEvent(true, send, total))
  244. }
  245. _progressEvent(send:number, total:number, chunk:string) {
  246. log.verbose(this.readyState)
  247. if(this._readyState === XMLHttpRequest.HEADERS_RECEIVED)
  248. this._dispatchReadStateChange(XMLHttpRequest.LOADING)
  249. let lengthComputable = false
  250. if(total && total >= 0)
  251. lengthComputable = true
  252. let e = new ProgressEvent(lengthComputable, send, total)
  253. if(this._increment) {
  254. this._responseText += chunk
  255. }
  256. this.dispatchEvent('progress', e)
  257. }
  258. _onError(err) {
  259. let statusCode = Math.floor(this.status)
  260. if(statusCode >= 100 && statusCode !== 408) {
  261. return
  262. }
  263. log.debug('XMLHttpRequest error', err)
  264. this._statusText = err
  265. this._status = String(err).match(/\d+/)
  266. this._status = this._status ? Math.floor(this.status) : 404
  267. this._dispatchReadStateChange(XMLHttpRequest.DONE)
  268. if(err && String(err.message).match(/(timed\sout|timedout)/) || this._status == 408) {
  269. this.dispatchEvent('timeout')
  270. }
  271. this.dispatchEvent('loadend')
  272. this.dispatchEvent('error', {
  273. type : 'error',
  274. detail : err
  275. })
  276. this.clearEventListeners()
  277. }
  278. _onDone(resp) {
  279. log.debug('XMLHttpRequest done', this._url, resp, this)
  280. this._statusText = this._status
  281. let responseDataReady = () => {
  282. this.dispatchEvent('load')
  283. this.dispatchEvent('loadend')
  284. this._dispatchReadStateChange(XMLHttpRequest.DONE)
  285. this.clearEventListeners()
  286. }
  287. if(resp) {
  288. let info = resp.respInfo || {}
  289. log.debug(this._url, info, info.respType)
  290. switch(info.respType) {
  291. case 'json' :
  292. try{
  293. this._responseText = resp.text()
  294. this._response = resp.json()
  295. responseDataReady()
  296. } catch(err) {
  297. }
  298. break;
  299. case 'blob' :
  300. resp.blob().then((b) => {
  301. this._responseText = resp.text()
  302. this._response = b
  303. responseDataReady()
  304. })
  305. break;
  306. default :
  307. this._responseText = resp.text()
  308. this._response = this.responseText
  309. responseDataReady()
  310. break;
  311. }
  312. }
  313. }
  314. _dispatchReadStateChange(state) {
  315. this._readyState = state
  316. if(typeof this._onreadystatechange === 'function')
  317. this._onreadystatechange()
  318. }
  319. set onreadystatechange(fn:() => void) {
  320. log.verbose('XMLHttpRequest set onreadystatechange', fn)
  321. this._onreadystatechange = fn
  322. }
  323. get onreadystatechange() {
  324. return this._onreadystatechange
  325. }
  326. get readyState() {
  327. log.verbose('get readyState', this._readyState)
  328. return this._readyState
  329. }
  330. get status() {
  331. log.verbose('get status', this._status)
  332. return this._status
  333. }
  334. get statusText() {
  335. log.verbose('get statusText', this._statusText)
  336. return this._statusText
  337. }
  338. get response() {
  339. log.verbose('get response', this._response)
  340. return this._response
  341. }
  342. get responseText() {
  343. log.verbose('get responseText', this._responseText)
  344. return this._responseText
  345. }
  346. get responseURL() {
  347. log.verbose('get responseURL', this._responseURL)
  348. return this._responseURL
  349. }
  350. get responseHeaders() {
  351. log.verbose('get responseHeaders', this._responseHeaders)
  352. return this._responseHeaders
  353. }
  354. set timeout(val) {
  355. this._timeout = val*1000
  356. log.verbose('set timeout', this._timeout)
  357. }
  358. get timeout() {
  359. log.verbose('get timeout', this._timeout)
  360. return this._timeout
  361. }
  362. set responseType(val) {
  363. log.verbose('set response type', this._responseType)
  364. this._responseType = val
  365. }
  366. get responseType() {
  367. log.verbose('get response type', this._responseType)
  368. return this._responseType
  369. }
  370. get isRNFBPolyfill() {
  371. return true
  372. }
  373. }