ParseFile.js 24 KB

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