ParseFile.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. "use strict";
  2. var _Object$keys2 = require("@babel/runtime-corejs3/core-js-stable/object/keys");
  3. var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols");
  4. var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter");
  5. var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
  6. var _forEachInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/for-each");
  7. var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors");
  8. var _Object$defineProperties = require("@babel/runtime-corejs3/core-js-stable/object/define-properties");
  9. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  10. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  11. _Object$defineProperty(exports, "__esModule", {
  12. value: true
  13. });
  14. exports.default = void 0;
  15. var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs3/regenerator"));
  16. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  17. var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
  18. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  19. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  20. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  21. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  22. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
  23. var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));
  24. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));
  25. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck"));
  26. var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass"));
  27. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  28. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  29. function ownKeys(object, enumerableOnly) {
  30. var keys = _Object$keys2(object);
  31. if (_Object$getOwnPropertySymbols) {
  32. var symbols = _Object$getOwnPropertySymbols(object);
  33. enumerableOnly && (symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) {
  34. return _Object$getOwnPropertyDescriptor(object, sym).enumerable;
  35. })), keys.push.apply(keys, symbols);
  36. }
  37. return keys;
  38. }
  39. function _objectSpread(target) {
  40. for (var i = 1; i < arguments.length; i++) {
  41. var _context8, _context9;
  42. var source = null != arguments[i] ? arguments[i] : {};
  43. i % 2 ? _forEachInstanceProperty2(_context8 = ownKeys(Object(source), !0)).call(_context8, function (key) {
  44. (0, _defineProperty2.default)(target, key, source[key]);
  45. }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : _forEachInstanceProperty2(_context9 = ownKeys(Object(source))).call(_context9, function (key) {
  46. _Object$defineProperty(target, key, _Object$getOwnPropertyDescriptor(source, key));
  47. });
  48. }
  49. return target;
  50. } /**
  51. * @flow
  52. */ /* global XMLHttpRequest, Blob */
  53. /*:: import type { FullOptions } from './RESTController';*/
  54. var ParseError = require('./ParseError').default;
  55. var XHR = null;
  56. if (typeof XMLHttpRequest !== 'undefined') {
  57. XHR = XMLHttpRequest;
  58. }
  59. /*:: type Base64 = { base64: string };*/
  60. /*:: type Uri = { uri: string };*/
  61. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  62. /*:: export type FileSource =
  63. | {
  64. format: 'file',
  65. file: Blob,
  66. type: string,
  67. }
  68. | {
  69. format: 'base64',
  70. base64: string,
  71. type: string,
  72. }
  73. | {
  74. format: 'uri',
  75. uri: string,
  76. type: string,
  77. };*/
  78. function b64Digit(number /*: number*/) /*: string*/{
  79. if (number < 26) {
  80. return String.fromCharCode(65 + number);
  81. }
  82. if (number < 52) {
  83. return String.fromCharCode(97 + (number - 26));
  84. }
  85. if (number < 62) {
  86. return String.fromCharCode(48 + (number - 52));
  87. }
  88. if (number === 62) {
  89. return '+';
  90. }
  91. if (number === 63) {
  92. return '/';
  93. }
  94. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  95. }
  96. /**
  97. * A Parse.File is a local representation of a file that is saved to the Parse
  98. * cloud.
  99. *
  100. * @alias Parse.File
  101. */
  102. var ParseFile = /*#__PURE__*/function () {
  103. /**
  104. * @param name {String} The file's name. This will be prefixed by a unique
  105. * value once the file has finished saving. The file name must begin with
  106. * an alphanumeric character, and consist of alphanumeric characters,
  107. * periods, spaces, underscores, or dashes.
  108. * @param data {Array} The data for the file, as either:
  109. * 1. an Array of byte value Numbers, or
  110. * 2. an Object like { base64: "..." } with a base64-encoded String.
  111. * 3. an Object like { uri: "..." } with a uri String.
  112. * 4. a File object selected with a file upload control. (3) only works
  113. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  114. * For example:
  115. * <pre>
  116. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  117. * if (fileUploadControl.files.length > 0) {
  118. * var file = fileUploadControl.files[0];
  119. * var name = "photo.jpg";
  120. * var parseFile = new Parse.File(name, file);
  121. * parseFile.save().then(function() {
  122. * // The file has been saved to Parse.
  123. * }, function(error) {
  124. * // The file either could not be read, or could not be saved to Parse.
  125. * });
  126. * }</pre>
  127. * @param type {String} Optional Content-Type header to use for the file. If
  128. * this is omitted, the content type will be inferred from the name's
  129. * extension.
  130. * @param metadata {Object} Optional key value pairs to be stored with file object
  131. * @param tags {Object} Optional key value pairs to be stored with file object
  132. */
  133. function ParseFile(name /*: string*/, data /*:: ?: FileData*/, type /*:: ?: string*/, metadata /*:: ?: Object*/, tags /*:: ?: Object*/) {
  134. (0, _classCallCheck2.default)(this, ParseFile);
  135. (0, _defineProperty2.default)(this, "_name", void 0);
  136. (0, _defineProperty2.default)(this, "_url", void 0);
  137. (0, _defineProperty2.default)(this, "_source", void 0);
  138. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  139. (0, _defineProperty2.default)(this, "_data", void 0);
  140. (0, _defineProperty2.default)(this, "_requestTask", void 0);
  141. (0, _defineProperty2.default)(this, "_metadata", void 0);
  142. (0, _defineProperty2.default)(this, "_tags", void 0);
  143. var specifiedType = type || '';
  144. this._name = name;
  145. this._metadata = metadata || {};
  146. this._tags = tags || {};
  147. if (data !== undefined) {
  148. if ((0, _isArray.default)(data)) {
  149. this._data = ParseFile.encodeBase64(data);
  150. this._source = {
  151. format: 'base64',
  152. base64: this._data,
  153. type: specifiedType
  154. };
  155. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  156. this._source = {
  157. format: 'file',
  158. file: data,
  159. type: specifiedType
  160. };
  161. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  162. this._source = {
  163. format: 'uri',
  164. uri: data.uri,
  165. type: specifiedType
  166. };
  167. } else if (data && typeof data.base64 === 'string') {
  168. var _context, _context2, _context3;
  169. var base64 = (0, _slice.default)(_context = data.base64.split(',')).call(_context, -1)[0];
  170. var dataType = specifiedType || (0, _slice.default)(_context2 = (0, _slice.default)(_context3 = data.base64.split(';')).call(_context3, 0, 1)[0].split(':')).call(_context2, 1, 2)[0] || 'text/plain';
  171. this._data = base64;
  172. this._source = {
  173. format: 'base64',
  174. base64: base64,
  175. type: dataType
  176. };
  177. } else {
  178. throw new TypeError('Cannot create a Parse.File with that data.');
  179. }
  180. }
  181. }
  182. /**
  183. * Return the data for the file, downloading it if not already present.
  184. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  185. * Data is cleared if saved with File object selected with a file upload control
  186. *
  187. * @returns {Promise} Promise that is resolve with base64 data
  188. */
  189. (0, _createClass2.default)(ParseFile, [{
  190. key: "getData",
  191. value: function () {
  192. var _getData = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
  193. var _this = this;
  194. var options, controller, result;
  195. return _regenerator.default.wrap(function (_context4) {
  196. while (1) switch (_context4.prev = _context4.next) {
  197. case 0:
  198. if (!this._data) {
  199. _context4.next = 2;
  200. break;
  201. }
  202. return _context4.abrupt("return", this._data);
  203. case 2:
  204. if (this._url) {
  205. _context4.next = 4;
  206. break;
  207. }
  208. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  209. case 4:
  210. options = {
  211. requestTask: function (task) {
  212. return _this._requestTask = task;
  213. }
  214. };
  215. controller = _CoreManager.default.getFileController();
  216. _context4.next = 8;
  217. return controller.download(this._url, options);
  218. case 8:
  219. result = _context4.sent;
  220. this._data = result.base64;
  221. return _context4.abrupt("return", this._data);
  222. case 11:
  223. case "end":
  224. return _context4.stop();
  225. }
  226. }, _callee, this);
  227. }));
  228. function getData() {
  229. return _getData.apply(this, arguments);
  230. }
  231. return getData;
  232. }()
  233. /**
  234. * Gets the name of the file. Before save is called, this is the filename
  235. * given by the user. After save is called, that name gets prefixed with a
  236. * unique identifier.
  237. *
  238. * @returns {string}
  239. */
  240. }, {
  241. key: "name",
  242. value: function () /*: string*/{
  243. return this._name;
  244. }
  245. /**
  246. * Gets the url of the file. It is only available after you save the file or
  247. * after you get the file from a Parse.Object.
  248. *
  249. * @param {object} options An object to specify url options
  250. * @returns {string | undefined}
  251. */
  252. }, {
  253. key: "url",
  254. value: function (options /*:: ?: { forceSecure?: boolean }*/) /*: ?string*/{
  255. options = options || {};
  256. if (!this._url) {
  257. return;
  258. }
  259. if (options.forceSecure) {
  260. return this._url.replace(/^http:\/\//i, 'https://');
  261. } else {
  262. return this._url;
  263. }
  264. }
  265. /**
  266. * Gets the metadata of the file.
  267. *
  268. * @returns {object}
  269. */
  270. }, {
  271. key: "metadata",
  272. value: function () /*: Object*/{
  273. return this._metadata;
  274. }
  275. /**
  276. * Gets the tags of the file.
  277. *
  278. * @returns {object}
  279. */
  280. }, {
  281. key: "tags",
  282. value: function () /*: Object*/{
  283. return this._tags;
  284. }
  285. /**
  286. * Saves the file to the Parse cloud.
  287. *
  288. * @param {object} options
  289. * Valid options are:<ul>
  290. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  291. * be used for this request.
  292. * <li>sessionToken: A valid session token, used for making a request on
  293. * behalf of a specific user.
  294. * <li>progress: In Browser only, callback for upload progress. For example:
  295. * <pre>
  296. * let parseFile = new Parse.File(name, file);
  297. * parseFile.save({
  298. * progress: (progressValue, loaded, total, { type }) => {
  299. * if (type === "upload" && progressValue !== null) {
  300. * // Update the UI using progressValue
  301. * }
  302. * }
  303. * });
  304. * </pre>
  305. * </ul>
  306. * @returns {Promise | undefined} Promise that is resolved when the save finishes.
  307. */
  308. }, {
  309. key: "save",
  310. value: function (options /*:: ?: FullOptions*/) /*: ?Promise*/{
  311. var _this2 = this;
  312. options = options || {};
  313. options.requestTask = function (task) {
  314. return _this2._requestTask = task;
  315. };
  316. options.metadata = this._metadata;
  317. options.tags = this._tags;
  318. var controller = _CoreManager.default.getFileController();
  319. if (!this._previousSave) {
  320. if (this._source.format === 'file') {
  321. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  322. _this2._name = res.name;
  323. _this2._url = res.url;
  324. _this2._data = null;
  325. _this2._requestTask = null;
  326. return _this2;
  327. });
  328. } else if (this._source.format === 'uri') {
  329. this._previousSave = controller.download(this._source.uri, options).then(function (result) {
  330. if (!(result && result.base64)) {
  331. return {};
  332. }
  333. var newSource = {
  334. format: 'base64',
  335. base64: result.base64,
  336. type: result.contentType
  337. };
  338. _this2._data = result.base64;
  339. _this2._requestTask = null;
  340. return controller.saveBase64(_this2._name, newSource, options);
  341. }).then(function (res) {
  342. _this2._name = res.name;
  343. _this2._url = res.url;
  344. _this2._requestTask = null;
  345. return _this2;
  346. });
  347. } else {
  348. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  349. _this2._name = res.name;
  350. _this2._url = res.url;
  351. _this2._requestTask = null;
  352. return _this2;
  353. });
  354. }
  355. }
  356. if (this._previousSave) {
  357. return this._previousSave;
  358. }
  359. }
  360. /**
  361. * Aborts the request if it has already been sent.
  362. */
  363. }, {
  364. key: "cancel",
  365. value: function () {
  366. if (this._requestTask && typeof this._requestTask.abort === 'function') {
  367. this._requestTask._aborted = true;
  368. this._requestTask.abort();
  369. }
  370. this._requestTask = null;
  371. }
  372. /**
  373. * Deletes the file from the Parse cloud.
  374. * In Cloud Code and Node only with Master Key.
  375. *
  376. * @param {object} options
  377. * Valid options are:<ul>
  378. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  379. * be used for this request.
  380. * <pre>
  381. * @returns {Promise} Promise that is resolved when the delete finishes.
  382. */
  383. }, {
  384. key: "destroy",
  385. value: function () {
  386. var _this3 = this;
  387. var options /*:: ?: FullOptions*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  388. if (!this._name) {
  389. throw new ParseError(ParseError.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
  390. }
  391. var destroyOptions = {
  392. useMasterKey: true
  393. };
  394. if (options.hasOwnProperty('useMasterKey')) {
  395. destroyOptions.useMasterKey = options.useMasterKey;
  396. }
  397. var controller = _CoreManager.default.getFileController();
  398. return controller.deleteFile(this._name, destroyOptions).then(function () {
  399. _this3._data = null;
  400. _this3._requestTask = null;
  401. return _this3;
  402. });
  403. }
  404. }, {
  405. key: "toJSON",
  406. value: function () /*: { name: ?string, url: ?string }*/{
  407. return {
  408. __type: 'File',
  409. name: this._name,
  410. url: this._url
  411. };
  412. }
  413. }, {
  414. key: "equals",
  415. value: function (other /*: mixed*/) /*: boolean*/{
  416. if (this === other) {
  417. return true;
  418. }
  419. // Unsaved Files are never equal, since they will be saved to different URLs
  420. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  421. }
  422. /**
  423. * Sets metadata to be saved with file object. Overwrites existing metadata
  424. *
  425. * @param {object} metadata Key value pairs to be stored with file object
  426. */
  427. }, {
  428. key: "setMetadata",
  429. value: function (metadata /*: any*/) {
  430. var _this4 = this;
  431. if (metadata && (0, _typeof2.default)(metadata) === 'object') {
  432. var _context5;
  433. (0, _forEach.default)(_context5 = (0, _keys.default)(metadata)).call(_context5, function (key) {
  434. _this4.addMetadata(key, metadata[key]);
  435. });
  436. }
  437. }
  438. /**
  439. * Sets metadata to be saved with file object. Adds to existing metadata.
  440. *
  441. * @param {string} key key to store the metadata
  442. * @param {*} value metadata
  443. */
  444. }, {
  445. key: "addMetadata",
  446. value: function (key /*: string*/, value /*: any*/) {
  447. if (typeof key === 'string') {
  448. this._metadata[key] = value;
  449. }
  450. }
  451. /**
  452. * Sets tags to be saved with file object. Overwrites existing tags
  453. *
  454. * @param {object} tags Key value pairs to be stored with file object
  455. */
  456. }, {
  457. key: "setTags",
  458. value: function (tags /*: any*/) {
  459. var _this5 = this;
  460. if (tags && (0, _typeof2.default)(tags) === 'object') {
  461. var _context6;
  462. (0, _forEach.default)(_context6 = (0, _keys.default)(tags)).call(_context6, function (key) {
  463. _this5.addTag(key, tags[key]);
  464. });
  465. }
  466. }
  467. /**
  468. * Sets tags to be saved with file object. Adds to existing tags.
  469. *
  470. * @param {string} key key to store tags
  471. * @param {*} value tag
  472. */
  473. }, {
  474. key: "addTag",
  475. value: function (key /*: string*/, value /*: string*/) {
  476. if (typeof key === 'string') {
  477. this._tags[key] = value;
  478. }
  479. }
  480. }], [{
  481. key: "fromJSON",
  482. value: function (obj) /*: ParseFile*/{
  483. if (obj.__type !== 'File') {
  484. throw new TypeError('JSON object does not represent a ParseFile');
  485. }
  486. var file = new ParseFile(obj.name);
  487. file._url = obj.url;
  488. return file;
  489. }
  490. }, {
  491. key: "encodeBase64",
  492. value: function (bytes /*: Array<number>*/) /*: string*/{
  493. var chunks = [];
  494. chunks.length = Math.ceil(bytes.length / 3);
  495. for (var i = 0; i < chunks.length; i++) {
  496. var b1 = bytes[i * 3];
  497. var b2 = bytes[i * 3 + 1] || 0;
  498. var b3 = bytes[i * 3 + 2] || 0;
  499. var has2 = i * 3 + 1 < bytes.length;
  500. var has3 = i * 3 + 2 < bytes.length;
  501. chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
  502. }
  503. return chunks.join('');
  504. }
  505. }]);
  506. return ParseFile;
  507. }();
  508. var DefaultController = {
  509. saveFile: function () {
  510. var _saveFile = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(name /*: string*/, source /*: FileSource*/, options /*:: ?: FullOptions*/) {
  511. var base64Data, _base64Data$split, _base64Data$split2, first, second, data, newSource;
  512. return _regenerator.default.wrap(function (_context7) {
  513. while (1) switch (_context7.prev = _context7.next) {
  514. case 0:
  515. if (!(source.format !== 'file')) {
  516. _context7.next = 2;
  517. break;
  518. }
  519. throw new Error('saveFile can only be used with File-type sources.');
  520. case 2:
  521. _context7.next = 4;
  522. return new _promise.default(function (res, rej) {
  523. // eslint-disable-next-line no-undef
  524. var reader = new FileReader();
  525. reader.onload = function () {
  526. return res(reader.result);
  527. };
  528. reader.onerror = function (error) {
  529. return rej(error);
  530. };
  531. reader.readAsDataURL(source.file);
  532. });
  533. case 4:
  534. base64Data = _context7.sent;
  535. // we only want the data after the comma
  536. // For example: "data:application/pdf;base64,JVBERi0xLjQKJ..." we would only want "JVBERi0xLjQKJ..."
  537. _base64Data$split = base64Data.split(','), _base64Data$split2 = (0, _slicedToArray2.default)(_base64Data$split, 2), first = _base64Data$split2[0], second = _base64Data$split2[1]; // in the event there is no 'data:application/pdf;base64,' at the beginning of the base64 string
  538. // use the entire string instead
  539. data = second ? second : first;
  540. newSource = {
  541. format: 'base64',
  542. base64: data,
  543. type: source.type || (source.file ? source.file.type : null)
  544. };
  545. _context7.next = 10;
  546. return DefaultController.saveBase64(name, newSource, options);
  547. case 10:
  548. return _context7.abrupt("return", _context7.sent);
  549. case 11:
  550. case "end":
  551. return _context7.stop();
  552. }
  553. }, _callee2);
  554. }));
  555. function saveFile() {
  556. return _saveFile.apply(this, arguments);
  557. }
  558. return saveFile;
  559. }(),
  560. saveBase64: function (name /*: string*/, source /*: FileSource*/, options /*:: ?: FullOptions*/) {
  561. if (source.format !== 'base64') {
  562. throw new Error('saveBase64 can only be used with Base64-type sources.');
  563. }
  564. var data /*: { base64: any, _ContentType?: any, fileData: Object }*/ = {
  565. base64: source.base64,
  566. fileData: {
  567. metadata: _objectSpread({}, options.metadata),
  568. tags: _objectSpread({}, options.tags)
  569. }
  570. };
  571. delete options.metadata;
  572. delete options.tags;
  573. if (source.type) {
  574. data._ContentType = source.type;
  575. }
  576. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  577. },
  578. download: function (uri, options) {
  579. if (XHR) {
  580. return this.downloadAjax(uri, options);
  581. } else {
  582. return _promise.default.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  583. }
  584. },
  585. downloadAjax: function (uri, options) {
  586. return new _promise.default(function (resolve, reject) {
  587. var xhr = new XHR();
  588. xhr.open('GET', uri, true);
  589. xhr.responseType = 'arraybuffer';
  590. xhr.onerror = function (e) {
  591. reject(e);
  592. };
  593. xhr.onreadystatechange = function () {
  594. if (xhr.readyState !== xhr.DONE) {
  595. return;
  596. }
  597. if (!this.response) {
  598. return resolve({});
  599. }
  600. var bytes = new Uint8Array(this.response);
  601. resolve({
  602. base64: ParseFile.encodeBase64(bytes),
  603. contentType: xhr.getResponseHeader('content-type')
  604. });
  605. };
  606. options.requestTask(xhr);
  607. xhr.send();
  608. });
  609. },
  610. deleteFile: function (name /*: string*/, options /*:: ?: FullOptions*/) {
  611. var headers = {
  612. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
  613. };
  614. if (options.useMasterKey) {
  615. headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
  616. }
  617. var url = _CoreManager.default.get('SERVER_URL');
  618. if (url[url.length - 1] !== '/') {
  619. url += '/';
  620. }
  621. url += 'files/' + name;
  622. return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(function (response) {
  623. // TODO: return JSON object in server
  624. if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
  625. return _promise.default.resolve();
  626. } else {
  627. return _CoreManager.default.getRESTController().handleError(response);
  628. }
  629. });
  630. },
  631. _setXHR: function (xhr /*: any*/) {
  632. XHR = xhr;
  633. },
  634. _getXHR: function () {
  635. return XHR;
  636. }
  637. };
  638. _CoreManager.default.setFileController(DefaultController);
  639. var _default = ParseFile;
  640. exports.default = _default;
  641. exports.b64Digit = b64Digit;