ParseFile.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = void 0;
  7. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  8. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
  9. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  10. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  11. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  12. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  13. /**
  14. * Copyright (c) 2015-present, Parse, LLC.
  15. * All rights reserved.
  16. *
  17. * This source code is licensed under the BSD-style license found in the
  18. * LICENSE file in the root directory of this source tree. An additional grant
  19. * of patent rights can be found in the PATENTS file in the same directory.
  20. *
  21. * @flow
  22. */
  23. /* global XMLHttpRequest, Blob */
  24. var XHR = null;
  25. if (typeof XMLHttpRequest !== 'undefined') {
  26. XHR = XMLHttpRequest;
  27. }
  28. /*:: type Base64 = { base64: string };*/
  29. /*:: type Uri = { uri: string };*/
  30. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  31. /*:: export type FileSource = {
  32. format: 'file';
  33. file: Blob;
  34. type: string
  35. } | {
  36. format: 'base64';
  37. base64: string;
  38. type: string
  39. } | {
  40. format: 'uri';
  41. uri: string;
  42. type: string
  43. };*/
  44. var dataUriRegexp = /^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;
  45. function b64Digit(number
  46. /*: number*/
  47. )
  48. /*: string*/
  49. {
  50. if (number < 26) {
  51. return String.fromCharCode(65 + number);
  52. }
  53. if (number < 52) {
  54. return String.fromCharCode(97 + (number - 26));
  55. }
  56. if (number < 62) {
  57. return String.fromCharCode(48 + (number - 52));
  58. }
  59. if (number === 62) {
  60. return '+';
  61. }
  62. if (number === 63) {
  63. return '/';
  64. }
  65. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  66. }
  67. /**
  68. * A Parse.File is a local representation of a file that is saved to the Parse
  69. * cloud.
  70. * @alias Parse.File
  71. */
  72. var ParseFile =
  73. /*#__PURE__*/
  74. function () {
  75. /**
  76. * @param name {String} The file's name. This will be prefixed by a unique
  77. * value once the file has finished saving. The file name must begin with
  78. * an alphanumeric character, and consist of alphanumeric characters,
  79. * periods, spaces, underscores, or dashes.
  80. * @param data {Array} The data for the file, as either:
  81. * 1. an Array of byte value Numbers, or
  82. * 2. an Object like { base64: "..." } with a base64-encoded String.
  83. * 3. an Object like { uri: "..." } with a uri String.
  84. * 4. a File object selected with a file upload control. (3) only works
  85. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  86. * For example:
  87. * <pre>
  88. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  89. * if (fileUploadControl.files.length > 0) {
  90. * var file = fileUploadControl.files[0];
  91. * var name = "photo.jpg";
  92. * var parseFile = new Parse.File(name, file);
  93. * parseFile.save().then(function() {
  94. * // The file has been saved to Parse.
  95. * }, function(error) {
  96. * // The file either could not be read, or could not be saved to Parse.
  97. * });
  98. * }</pre>
  99. * @param type {String} Optional Content-Type header to use for the file. If
  100. * this is omitted, the content type will be inferred from the name's
  101. * extension.
  102. */
  103. function ParseFile(name
  104. /*: string*/
  105. , data
  106. /*:: ?: FileData*/
  107. , type
  108. /*:: ?: string*/
  109. ) {
  110. (0, _classCallCheck2.default)(this, ParseFile);
  111. (0, _defineProperty2.default)(this, "_name", void 0);
  112. (0, _defineProperty2.default)(this, "_url", void 0);
  113. (0, _defineProperty2.default)(this, "_source", void 0);
  114. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  115. (0, _defineProperty2.default)(this, "_data", void 0);
  116. var specifiedType = type || '';
  117. this._name = name;
  118. if (data !== undefined) {
  119. if (Array.isArray(data)) {
  120. this._data = ParseFile.encodeBase64(data);
  121. this._source = {
  122. format: 'base64',
  123. base64: this._data,
  124. type: specifiedType
  125. };
  126. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  127. this._source = {
  128. format: 'file',
  129. file: data,
  130. type: specifiedType
  131. };
  132. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  133. this._source = {
  134. format: 'uri',
  135. uri: data.uri,
  136. type: specifiedType
  137. };
  138. } else if (data && typeof data.base64 === 'string') {
  139. var base64 = data.base64;
  140. var commaIndex = base64.indexOf(',');
  141. if (commaIndex !== -1) {
  142. var matches = dataUriRegexp.exec(base64.slice(0, commaIndex + 1)); // if data URI with type and charset, there will be 4 matches.
  143. this._data = base64.slice(commaIndex + 1);
  144. this._source = {
  145. format: 'base64',
  146. base64: this._data,
  147. type: matches[1]
  148. };
  149. } else {
  150. this._data = base64;
  151. this._source = {
  152. format: 'base64',
  153. base64: base64,
  154. type: specifiedType
  155. };
  156. }
  157. } else {
  158. throw new TypeError('Cannot create a Parse.File with that data.');
  159. }
  160. }
  161. }
  162. /**
  163. * Return the data for the file, downloading it if not already present.
  164. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  165. * Data is cleared if saved with File object selected with a file upload control
  166. *
  167. * @return {Promise} Promise that is resolve with base64 data
  168. */
  169. (0, _createClass2.default)(ParseFile, [{
  170. key: "getData",
  171. value: function () {
  172. var _getData = (0, _asyncToGenerator2.default)(
  173. /*#__PURE__*/
  174. _regenerator.default.mark(function _callee() {
  175. var controller, result;
  176. return _regenerator.default.wrap(function (_context) {
  177. while (1) {
  178. switch (_context.prev = _context.next) {
  179. case 0:
  180. if (!this._data) {
  181. _context.next = 2;
  182. break;
  183. }
  184. return _context.abrupt("return", this._data);
  185. case 2:
  186. if (this._url) {
  187. _context.next = 4;
  188. break;
  189. }
  190. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  191. case 4:
  192. controller = _CoreManager.default.getFileController();
  193. _context.next = 7;
  194. return controller.download(this._url);
  195. case 7:
  196. result = _context.sent;
  197. this._data = result.base64;
  198. return _context.abrupt("return", this._data);
  199. case 10:
  200. case "end":
  201. return _context.stop();
  202. }
  203. }
  204. }, _callee, this);
  205. }));
  206. return function () {
  207. return _getData.apply(this, arguments);
  208. };
  209. }()
  210. /**
  211. * Gets the name of the file. Before save is called, this is the filename
  212. * given by the user. After save is called, that name gets prefixed with a
  213. * unique identifier.
  214. * @return {String}
  215. */
  216. }, {
  217. key: "name",
  218. value: function ()
  219. /*: string*/
  220. {
  221. return this._name;
  222. }
  223. /**
  224. * Gets the url of the file. It is only available after you save the file or
  225. * after you get the file from a Parse.Object.
  226. * @param {Object} options An object to specify url options
  227. * @return {String}
  228. */
  229. }, {
  230. key: "url",
  231. value: function (options
  232. /*:: ?: { forceSecure?: boolean }*/
  233. )
  234. /*: ?string*/
  235. {
  236. options = options || {};
  237. if (!this._url) {
  238. return;
  239. }
  240. if (options.forceSecure) {
  241. return this._url.replace(/^http:\/\//i, 'https://');
  242. } else {
  243. return this._url;
  244. }
  245. }
  246. /**
  247. * Saves the file to the Parse cloud.
  248. * @param {Object} options
  249. * * Valid options are:<ul>
  250. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  251. * be used for this request.
  252. * <li>progress: In Browser only, callback for upload progress
  253. * </ul>
  254. * @return {Promise} Promise that is resolved when the save finishes.
  255. */
  256. }, {
  257. key: "save",
  258. value: function (options
  259. /*:: ?: FullOptions*/
  260. ) {
  261. var _this = this;
  262. options = options || {};
  263. var controller = _CoreManager.default.getFileController();
  264. if (!this._previousSave) {
  265. if (this._source.format === 'file') {
  266. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  267. _this._name = res.name;
  268. _this._url = res.url;
  269. _this._data = null;
  270. return _this;
  271. });
  272. } else if (this._source.format === 'uri') {
  273. this._previousSave = controller.download(this._source.uri).then(function (result) {
  274. var newSource = {
  275. format: 'base64',
  276. base64: result.base64,
  277. type: result.contentType
  278. };
  279. _this._data = result.base64;
  280. return controller.saveBase64(_this._name, newSource, options);
  281. }).then(function (res) {
  282. _this._name = res.name;
  283. _this._url = res.url;
  284. return _this;
  285. });
  286. } else {
  287. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  288. _this._name = res.name;
  289. _this._url = res.url;
  290. return _this;
  291. });
  292. }
  293. }
  294. if (this._previousSave) {
  295. return this._previousSave;
  296. }
  297. }
  298. }, {
  299. key: "toJSON",
  300. value: function ()
  301. /*: { name: ?string, url: ?string }*/
  302. {
  303. return {
  304. __type: 'File',
  305. name: this._name,
  306. url: this._url
  307. };
  308. }
  309. }, {
  310. key: "equals",
  311. value: function (other
  312. /*: mixed*/
  313. )
  314. /*: boolean*/
  315. {
  316. if (this === other) {
  317. return true;
  318. } // Unsaved Files are never equal, since they will be saved to different URLs
  319. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  320. }
  321. }], [{
  322. key: "fromJSON",
  323. value: function (obj)
  324. /*: ParseFile*/
  325. {
  326. if (obj.__type !== 'File') {
  327. throw new TypeError('JSON object does not represent a ParseFile');
  328. }
  329. var file = new ParseFile(obj.name);
  330. file._url = obj.url;
  331. return file;
  332. }
  333. }, {
  334. key: "encodeBase64",
  335. value: function (bytes
  336. /*: Array<number>*/
  337. )
  338. /*: string*/
  339. {
  340. var chunks = [];
  341. chunks.length = Math.ceil(bytes.length / 3);
  342. for (var i = 0; i < chunks.length; i++) {
  343. var b1 = bytes[i * 3];
  344. var b2 = bytes[i * 3 + 1] || 0;
  345. var b3 = bytes[i * 3 + 2] || 0;
  346. var has2 = i * 3 + 1 < bytes.length;
  347. var has3 = i * 3 + 2 < bytes.length;
  348. 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('');
  349. }
  350. return chunks.join('');
  351. }
  352. }]);
  353. return ParseFile;
  354. }();
  355. var DefaultController = {
  356. saveFile: function (name
  357. /*: string*/
  358. , source
  359. /*: FileSource*/
  360. , options
  361. /*:: ?: FullOptions*/
  362. ) {
  363. if (source.format !== 'file') {
  364. throw new Error('saveFile can only be used with File-type sources.');
  365. } // To directly upload a File, we use a REST-style AJAX request
  366. var headers = {
  367. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID'),
  368. 'Content-Type': source.type || (source.file ? source.file.type : null)
  369. };
  370. var jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  371. if (jsKey) {
  372. headers['X-Parse-JavaScript-Key'] = jsKey;
  373. }
  374. var url = _CoreManager.default.get('SERVER_URL');
  375. if (url[url.length - 1] !== '/') {
  376. url += '/';
  377. }
  378. url += 'files/' + name;
  379. return _CoreManager.default.getRESTController().ajax('POST', url, source.file, headers, options).then(function (res) {
  380. return res.response;
  381. });
  382. },
  383. saveBase64: function (name
  384. /*: string*/
  385. , source
  386. /*: FileSource*/
  387. , options
  388. /*:: ?: FullOptions*/
  389. ) {
  390. if (source.format !== 'base64') {
  391. throw new Error('saveBase64 can only be used with Base64-type sources.');
  392. }
  393. var data
  394. /*: { base64: any; _ContentType?: any }*/
  395. = {
  396. base64: source.base64
  397. };
  398. if (source.type) {
  399. data._ContentType = source.type;
  400. }
  401. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  402. },
  403. download: function (uri) {
  404. if (XHR) {
  405. return this.downloadAjax(uri);
  406. } else {
  407. return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  408. }
  409. },
  410. downloadAjax: function (uri) {
  411. return new Promise(function (resolve, reject) {
  412. var xhr = new XHR();
  413. xhr.open('GET', uri, true);
  414. xhr.responseType = 'arraybuffer';
  415. xhr.onerror = function (e) {
  416. reject(e);
  417. };
  418. xhr.onreadystatechange = function () {
  419. if (xhr.readyState !== 4) {
  420. return;
  421. }
  422. var bytes = new Uint8Array(this.response);
  423. resolve({
  424. base64: ParseFile.encodeBase64(bytes),
  425. contentType: xhr.getResponseHeader('content-type')
  426. });
  427. };
  428. xhr.send();
  429. });
  430. },
  431. _setXHR: function (xhr
  432. /*: any*/
  433. ) {
  434. XHR = xhr;
  435. }
  436. };
  437. _CoreManager.default.setFileController(DefaultController);
  438. var _default = ParseFile;
  439. exports.default = _default;