cordova-http-plugin.js 8.49 KB
Newer Older
Chok's avatar
Chok committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
var pluginId = module.id.slice(0, module.id.lastIndexOf('.'));

var cordovaProxy = require('cordova/exec/proxy');
var jsUtil = require(pluginId + '.js-util');

var reqMap = {};

function serializeJsonData(data) {
  try {
    return JSON.stringify(data);
  } catch (err) {
    return null;
  }
}

function serializePrimitive(key, value) {
  if (value === null || value === undefined) {
    return encodeURIComponent(key) + '=';
  }

  return encodeURIComponent(key) + '=' + encodeURIComponent(value);
}

function serializeArray(key, values) {
  return values.map(function (value) {
    return encodeURIComponent(key) + '[]=' + encodeURIComponent(value);
  }).join('&');
}

function serializeParams(params) {
  if (params === null) return '';

  return Object.keys(params).map(function (key) {
    if (jsUtil.getTypeOf(params[key]) === 'Array') {
      return serializeArray(key, params[key]);
    }

    return serializePrimitive(key, params[key]);
  }).join('&');
}

function decodeB64(dataString) {
  var binaryString = atob(dataString);
  var bytes = new Uint8Array(binaryString.length);

  for (var i = 0; i < binaryString.length; ++i) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  return bytes.buffer;
}

function processMultipartData(data) {
  if (!data) return null;

  var fd = new FormData();

  for (var i = 0; i < data.buffers.length; ++i) {
    var buffer = data.buffers[i];
    var name = data.names[i];
    var fileName = data.fileNames[i];
    var type = data.types[i];

    if (fileName) {
      fd.append(name, new Blob([decodeB64(buffer)], { type: type }), fileName);
    } else {
      // we assume it's plain text if no filename was given
      fd.append(name, atob(buffer));
    }
  }

  return fd;
}

function deserializeResponseHeaders(headers) {
  var headerMap = {};
  var arr = headers.trim().split(/[\r\n]+/);

  arr.forEach(function (line) {
    var parts = line.split(': ');
    var header = parts.shift().toLowerCase();
    var value = parts.join(': ');

    headerMap[header] = value;
  });

  return headerMap;
}

function getResponseData(xhr) {
  if (xhr.responseType !== 'text' || jsUtil.getTypeOf(xhr.responseText) !== 'String') {
    return xhr.response;
  }

  return xhr.responseText;
}

function createXhrSuccessObject(xhr) {
  return {
    url: xhr.responseURL,
    status: xhr.status,
    data: getResponseData(xhr),
    headers: deserializeResponseHeaders(xhr.getAllResponseHeaders())
  };
}

function createXhrFailureObject(xhr) {
  var obj = {};

  obj.headers = xhr.getAllResponseHeaders();
  obj.error = getResponseData(xhr);
  obj.error = obj.error || 'advanced-http: please check browser console for error messages';

  if (xhr.responseURL) obj.url = xhr.responseURL;
  if (xhr.status) obj.status = xhr.status;

  return obj;
}

function injectRequestIdHandler(reqId, cb) {
  return function (response) {
    delete reqMap[reqId];
    cb(response);
  }
}

function getHeaderValue(headers, headerName) {
  let result = null;

  Object.keys(headers).forEach(function (key) {
    if (key.toLowerCase() === headerName.toLowerCase()) {
      result = headers[key];
    }
  });

  return result;
}

function setDefaultContentType(headers, contentType) {
  if (getHeaderValue(headers, 'Content-Type') === null) {
    headers['Content-Type'] = contentType;
  }
}

function setHeaders(xhr, headers) {
  Object.keys(headers).forEach(function (key) {
    if (key.toLowerCase() === 'cookie') return;

    xhr.setRequestHeader(key, headers[key]);
  });
}

function sendRequest(method, withData, opts, success, failure) {
  var data, serializer, headers, readTimeout, followRedirect, responseType, reqId;
  var url = opts[0];

  if (withData) {
    data = opts[1];
    serializer = opts[2];
    headers = opts[3];
    // connect timeout not applied
    // connectTimeout = opts[4];
    readTimeout = opts[5];
    followRedirect = opts[6];
    responseType = opts[7];
    reqId = opts[8];
  } else {
    headers = opts[1];
    // connect timeout not applied
    // connectTimeout = opts[2];
    readTimeout = opts[3];
    followRedirect = opts[4];
    responseType = opts[5];
    reqId = opts[6];
  }

  var onSuccess = injectRequestIdHandler(reqId, success);
  var onFail = injectRequestIdHandler(reqId, failure);

  var processedData = null;
  var xhr = new XMLHttpRequest();

  reqMap[reqId] = xhr;

  xhr.open(method, url);

  if (headers.Cookie && headers.Cookie.length > 0) {
    return onFail('advanced-http: custom cookies not supported on browser platform');
  }

  if (!followRedirect) {
    return onFail('advanced-http: disabling follow redirect not supported on browser platform');
  }

  switch (serializer) {
    case 'json':
      setDefaultContentType(headers, 'application/json; charset=utf8');
      processedData = serializeJsonData(data);

      if (processedData === null) {
        return onFail('advanced-http: failed serializing data');
      }

      break;

    case 'utf8':
      setDefaultContentType(headers, 'text/plain; charset=utf8');
      processedData = data.text;
      break;

    case 'urlencoded':
      setDefaultContentType(headers, 'application/x-www-form-urlencoded');
      processedData = serializeParams(data);
      break;

    case 'multipart':
      const contentType = getHeaderValue(headers, 'Content-Type');

      // intentionally don't set a default content type
      // it's set by the browser together with the content disposition string
      if (contentType) {
        headers['Content-Type'] = contentType;
      }

      processedData = processMultipartData(data);
      break;

    case 'raw':
      setDefaultContentType(headers, 'application/octet-stream');
      processedData = data;
      break;
  }

  // requesting text instead of JSON because it's parsed in the response handler
  xhr.responseType = responseType === 'json' ? 'text' : responseType;

  // we can't set connect timeout and read timeout separately on browser platform
  xhr.timeout = readTimeout * 1000;

  try {
    setHeaders(xhr, headers);
  } catch(error) {
    return onFail({
      status: -1,
      error: error,
      url: url,
      headers: headers
    });
  }

  xhr.onerror = function () {
    return onFail(createXhrFailureObject(xhr));
  };

  xhr.onabort = function () {
    return onFail({
      status: -8,
      error: 'Request was aborted',
      url: url,
      headers: {}
    });
  };

  xhr.ontimeout = function () {
    return onFail({
      status: -4,
      error: 'Request timed out',
      url: url,
      headers: {}
    });
  };

  xhr.onload = function () {
    if (xhr.readyState !== xhr.DONE) return;

    if (xhr.status < 200 || xhr.status > 299) {
      return onFail(createXhrFailureObject(xhr));
    }

    return onSuccess(createXhrSuccessObject(xhr));
  };

  xhr.send(processedData);
}

function abort(opts, success, failure) {
  var reqId = opts[0];
  var result = false;

  var xhr = reqMap[reqId];
  if(xhr && xhr.readyState !== xhr.DONE){
    xhr.abort();
    result = true;
  }

  success({aborted: result});
}

var browserInterface = {
  get: function (success, failure, opts) {
    return sendRequest('get', false, opts, success, failure);
  },
  head: function (success, failure, opts) {
    return sendRequest('head', false, opts, success, failure);
  },
  delete: function (success, failure, opts) {
    return sendRequest('delete', false, opts, success, failure);
  },
  post: function (success, failure, opts) {
    return sendRequest('post', true, opts, success, failure);
  },
  put: function (success, failure, opts) {
    return sendRequest('put', true, opts, success, failure);
  },
  patch: function (success, failure, opts) {
    return sendRequest('patch', true, opts, success, failure);
  },
  abort: function (success, failure, opts) {
    return abort(opts, success, failure);
  },
  uploadFile: function (success, failure, opts) {
    return failure('advanced-http: function "uploadFile" not supported on browser platform');
  },
  uploadFiles: function (success, failure, opts) {
    return failure('advanced-http: function "uploadFiles" not supported on browser platform');
  },
  downloadFile: function (success, failure, opts) {
    return failure('advanced-http: function "downloadFile" not supported on browser platform');
  },
  setServerTrustMode: function (success, failure, opts) {
    return failure('advanced-http: function "setServerTrustMode" not supported on browser platform');
  },
  setClientAuthMode: function (success, failure, opts) {
    return failure('advanced-http: function "setClientAuthMode" not supported on browser platform');
  }
};

module.exports = browserInterface;
cordovaProxy.add('CordovaHttpPlugin', browserInterface);