ParseFile.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. "use strict";
  2. var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
  3. var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
  4. _Object$defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.default = void 0;
  8. var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));
  9. var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
  10. var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each"));
  11. var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
  12. var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));
  13. var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of"));
  14. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
  15. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  16. var _ParseError = _interopRequireDefault(require("./ParseError"));
  17. var _Xhr = _interopRequireDefault(require("./Xhr.weapp"));
  18. /* global XMLHttpRequest, Blob */
  19. let XHR = null;
  20. if (typeof XMLHttpRequest !== 'undefined') {
  21. XHR = XMLHttpRequest;
  22. }
  23. XHR = _Xhr.default;
  24. function b64Digit(number) {
  25. if (number < 26) {
  26. return String.fromCharCode(65 + number);
  27. }
  28. if (number < 52) {
  29. return String.fromCharCode(97 + (number - 26));
  30. }
  31. if (number < 62) {
  32. return String.fromCharCode(48 + (number - 52));
  33. }
  34. if (number === 62) {
  35. return '+';
  36. }
  37. if (number === 63) {
  38. return '/';
  39. }
  40. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  41. }
  42. /**
  43. * A Parse.File is a local representation of a file that is saved to the Parse
  44. * cloud.
  45. *
  46. * @alias Parse.File
  47. */
  48. class ParseFile {
  49. /**
  50. * @param name {String} The file's name. This will be prefixed by a unique
  51. * value once the file has finished saving. The file name must begin with
  52. * an alphanumeric character, and consist of alphanumeric characters,
  53. * periods, spaces, underscores, or dashes.
  54. * @param data {Array} The data for the file, as either:
  55. * 1. an Array of byte value Numbers, or
  56. * 2. an Object like { base64: "..." } with a base64-encoded String.
  57. * 3. an Object like { uri: "..." } with a uri String.
  58. * 4. a File object selected with a file upload control. (3) only works
  59. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  60. * For example:
  61. * <pre>
  62. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  63. * if (fileUploadControl.files.length > 0) {
  64. * var file = fileUploadControl.files[0];
  65. * var name = "photo.jpg";
  66. * var parseFile = new Parse.File(name, file);
  67. * parseFile.save().then(function() {
  68. * // The file has been saved to Parse.
  69. * }, function(error) {
  70. * // The file either could not be read, or could not be saved to Parse.
  71. * });
  72. * }</pre>
  73. * @param type {String} Optional Content-Type header to use for the file. If
  74. * this is omitted, the content type will be inferred from the name's
  75. * extension.
  76. * @param metadata {object} Optional key value pairs to be stored with file object
  77. * @param tags {object} Optional key value pairs to be stored with file object
  78. */
  79. constructor(name, data, type, metadata, tags) {
  80. (0, _defineProperty2.default)(this, "_name", void 0);
  81. (0, _defineProperty2.default)(this, "_url", void 0);
  82. (0, _defineProperty2.default)(this, "_source", void 0);
  83. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  84. (0, _defineProperty2.default)(this, "_data", void 0);
  85. (0, _defineProperty2.default)(this, "_requestTask", void 0);
  86. (0, _defineProperty2.default)(this, "_metadata", void 0);
  87. (0, _defineProperty2.default)(this, "_tags", void 0);
  88. const specifiedType = type || '';
  89. this._name = name;
  90. this._metadata = metadata || {};
  91. this._tags = tags || {};
  92. if (data !== undefined) {
  93. if ((0, _isArray.default)(data)) {
  94. this._data = ParseFile.encodeBase64(data);
  95. this._source = {
  96. format: 'base64',
  97. base64: this._data,
  98. type: specifiedType
  99. };
  100. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  101. this._source = {
  102. format: 'file',
  103. file: data,
  104. type: specifiedType
  105. };
  106. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  107. this._source = {
  108. format: 'uri',
  109. uri: data.uri,
  110. type: specifiedType
  111. };
  112. } else if (data && typeof data.base64 === 'string') {
  113. var _context, _context2, _context3;
  114. const base64 = (0, _slice.default)(_context = data.base64.split(',')).call(_context, -1)[0];
  115. const 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';
  116. this._data = base64;
  117. this._source = {
  118. format: 'base64',
  119. base64,
  120. type: dataType
  121. };
  122. } else {
  123. throw new TypeError('Cannot create a Parse.File with that data.');
  124. }
  125. }
  126. }
  127. /**
  128. * Return the data for the file, downloading it if not already present.
  129. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  130. * Data is cleared if saved with File object selected with a file upload control
  131. *
  132. * @returns {Promise} Promise that is resolve with base64 data
  133. */
  134. async getData() {
  135. if (this._data) {
  136. return this._data;
  137. }
  138. if (!this._url) {
  139. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  140. }
  141. const controller = _CoreManager.default.getFileController();
  142. const result = await controller.download(this._url, {
  143. requestTask: task => this._requestTask = task
  144. });
  145. this._data = result.base64;
  146. return this._data;
  147. }
  148. /**
  149. * Gets the name of the file. Before save is called, this is the filename
  150. * given by the user. After save is called, that name gets prefixed with a
  151. * unique identifier.
  152. *
  153. * @returns {string}
  154. */
  155. name() {
  156. return this._name;
  157. }
  158. /**
  159. * Gets the url of the file. It is only available after you save the file or
  160. * after you get the file from a Parse.Object.
  161. *
  162. * @param {object} options An object to specify url options
  163. * @param {boolean} [options.forceSecure] force the url to be secure
  164. * @returns {string | undefined}
  165. */
  166. url(options) {
  167. options = options || {};
  168. if (!this._url) {
  169. return;
  170. }
  171. if (options.forceSecure) {
  172. return this._url.replace(/^http:\/\//i, 'https://');
  173. } else {
  174. return this._url;
  175. }
  176. }
  177. /**
  178. * Gets the metadata of the file.
  179. *
  180. * @returns {object}
  181. */
  182. metadata() {
  183. return this._metadata;
  184. }
  185. /**
  186. * Gets the tags of the file.
  187. *
  188. * @returns {object}
  189. */
  190. tags() {
  191. return this._tags;
  192. }
  193. /**
  194. * Saves the file to the Parse cloud.
  195. *
  196. * @param {object} options
  197. * Valid options are:<ul>
  198. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  199. * be used for this request.
  200. * <li>sessionToken: A valid session token, used for making a request on
  201. * behalf of a specific user.
  202. * <li>progress: In Browser only, callback for upload progress. For example:
  203. * <pre>
  204. * let parseFile = new Parse.File(name, file);
  205. * parseFile.save({
  206. * progress: (progressValue, loaded, total, { type }) => {
  207. * if (type === "upload" && progressValue !== null) {
  208. * // Update the UI using progressValue
  209. * }
  210. * }
  211. * });
  212. * </pre>
  213. * </ul>
  214. * @returns {Promise | undefined} Promise that is resolved when the save finishes.
  215. */
  216. save(options) {
  217. options = options || {};
  218. options.requestTask = task => this._requestTask = task;
  219. options.metadata = this._metadata;
  220. options.tags = this._tags;
  221. const controller = _CoreManager.default.getFileController();
  222. if (!this._previousSave) {
  223. if (this._source.format === 'file') {
  224. this._previousSave = controller.saveFile(this._name, this._source, options).then(res => {
  225. this._name = res.name;
  226. this._url = res.url;
  227. this._data = null;
  228. this._requestTask = null;
  229. return this;
  230. });
  231. } else if (this._source.format === 'uri') {
  232. this._previousSave = controller.download(this._source.uri, options).then(result => {
  233. if (!(result && result.base64)) {
  234. return {};
  235. }
  236. const newSource = {
  237. format: 'base64',
  238. base64: result.base64,
  239. type: result.contentType
  240. };
  241. this._data = result.base64;
  242. this._requestTask = null;
  243. return controller.saveBase64(this._name, newSource, options);
  244. }).then(res => {
  245. this._name = res.name;
  246. this._url = res.url;
  247. this._requestTask = null;
  248. return this;
  249. });
  250. } else {
  251. this._previousSave = controller.saveBase64(this._name, this._source, options).then(res => {
  252. this._name = res.name;
  253. this._url = res.url;
  254. this._requestTask = null;
  255. return this;
  256. });
  257. }
  258. }
  259. if (this._previousSave) {
  260. return this._previousSave;
  261. }
  262. }
  263. /**
  264. * Aborts the request if it has already been sent.
  265. */
  266. cancel() {
  267. if (this._requestTask && typeof this._requestTask.abort === 'function') {
  268. this._requestTask._aborted = true;
  269. this._requestTask.abort();
  270. }
  271. this._requestTask = null;
  272. }
  273. /**
  274. * Deletes the file from the Parse cloud.
  275. * In Cloud Code and Node only with Master Key.
  276. *
  277. * @param {object} options
  278. * Valid options are:<ul>
  279. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  280. * be used for this request.
  281. * <pre>
  282. * @returns {Promise} Promise that is resolved when the delete finishes.
  283. */
  284. destroy() {
  285. let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  286. if (!this._name) {
  287. throw new _ParseError.default(_ParseError.default.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
  288. }
  289. const destroyOptions = {
  290. useMasterKey: true
  291. };
  292. if (options.hasOwnProperty('useMasterKey')) {
  293. destroyOptions.useMasterKey = !!options.useMasterKey;
  294. }
  295. const controller = _CoreManager.default.getFileController();
  296. return controller.deleteFile(this._name, destroyOptions).then(() => {
  297. this._data = undefined;
  298. this._requestTask = null;
  299. return this;
  300. });
  301. }
  302. toJSON() {
  303. return {
  304. __type: 'File',
  305. name: this._name,
  306. url: this._url
  307. };
  308. }
  309. equals(other) {
  310. if (this === other) {
  311. return true;
  312. }
  313. // Unsaved Files are never equal, since they will be saved to different URLs
  314. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  315. }
  316. /**
  317. * Sets metadata to be saved with file object. Overwrites existing metadata
  318. *
  319. * @param {object} metadata Key value pairs to be stored with file object
  320. */
  321. setMetadata(metadata) {
  322. if (metadata && typeof metadata === 'object') {
  323. var _context4;
  324. (0, _forEach.default)(_context4 = (0, _keys.default)(metadata)).call(_context4, key => {
  325. this.addMetadata(key, metadata[key]);
  326. });
  327. }
  328. }
  329. /**
  330. * Sets metadata to be saved with file object. Adds to existing metadata.
  331. *
  332. * @param {string} key key to store the metadata
  333. * @param {*} value metadata
  334. */
  335. addMetadata(key, value) {
  336. if (typeof key === 'string') {
  337. this._metadata[key] = value;
  338. }
  339. }
  340. /**
  341. * Sets tags to be saved with file object. Overwrites existing tags
  342. *
  343. * @param {object} tags Key value pairs to be stored with file object
  344. */
  345. setTags(tags) {
  346. if (tags && typeof tags === 'object') {
  347. var _context5;
  348. (0, _forEach.default)(_context5 = (0, _keys.default)(tags)).call(_context5, key => {
  349. this.addTag(key, tags[key]);
  350. });
  351. }
  352. }
  353. /**
  354. * Sets tags to be saved with file object. Adds to existing tags.
  355. *
  356. * @param {string} key key to store tags
  357. * @param {*} value tag
  358. */
  359. addTag(key, value) {
  360. if (typeof key === 'string') {
  361. this._tags[key] = value;
  362. }
  363. }
  364. static fromJSON(obj) {
  365. if (obj.__type !== 'File') {
  366. throw new TypeError('JSON object does not represent a ParseFile');
  367. }
  368. const file = new ParseFile(obj.name);
  369. file._url = obj.url;
  370. return file;
  371. }
  372. static encodeBase64(bytes) {
  373. const chunks = [];
  374. chunks.length = Math.ceil(bytes.length / 3);
  375. for (let i = 0; i < chunks.length; i++) {
  376. const b1 = bytes[i * 3];
  377. const b2 = bytes[i * 3 + 1] || 0;
  378. const b3 = bytes[i * 3 + 2] || 0;
  379. const has2 = i * 3 + 1 < bytes.length;
  380. const has3 = i * 3 + 2 < bytes.length;
  381. 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('');
  382. }
  383. return chunks.join('');
  384. }
  385. }
  386. const DefaultController = {
  387. saveFile: async function (name, source, options) {
  388. if (source.format !== 'file') {
  389. throw new Error('saveFile can only be used with File-type sources.');
  390. }
  391. const base64Data = await new _promise.default((res, rej) => {
  392. // eslint-disable-next-line no-undef
  393. const reader = new FileReader();
  394. reader.onload = () => res(reader.result);
  395. reader.onerror = error => rej(error);
  396. reader.readAsDataURL(source.file);
  397. });
  398. // we only want the data after the comma
  399. // For example: "data:application/pdf;base64,JVBERi0xLjQKJ..." we would only want "JVBERi0xLjQKJ..."
  400. const [first, second] = base64Data.split(',');
  401. // in the event there is no 'data:application/pdf;base64,' at the beginning of the base64 string
  402. // use the entire string instead
  403. const data = second ? second : first;
  404. const newSource = {
  405. format: 'base64',
  406. base64: data,
  407. type: source.type || (source.file ? source.file.type : undefined)
  408. };
  409. return await DefaultController.saveBase64(name, newSource, options);
  410. },
  411. saveBase64: function (name, source) {
  412. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  413. if (source.format !== 'base64') {
  414. throw new Error('saveBase64 can only be used with Base64-type sources.');
  415. }
  416. const data = {
  417. base64: source.base64,
  418. fileData: {
  419. metadata: {
  420. ...options.metadata
  421. },
  422. tags: {
  423. ...options.tags
  424. }
  425. }
  426. };
  427. delete options.metadata;
  428. delete options.tags;
  429. if (source.type) {
  430. data._ContentType = source.type;
  431. }
  432. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  433. },
  434. download: function (uri, options) {
  435. if (XHR) {
  436. return this.downloadAjax(uri, options);
  437. } else {
  438. return _promise.default.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  439. }
  440. },
  441. downloadAjax: function (uri, options) {
  442. return new _promise.default((resolve, reject) => {
  443. const xhr = new XHR();
  444. xhr.open('GET', uri, true);
  445. xhr.responseType = 'arraybuffer';
  446. xhr.onerror = function (e) {
  447. reject(e);
  448. };
  449. xhr.onreadystatechange = function () {
  450. if (xhr.readyState !== xhr.DONE) {
  451. return;
  452. }
  453. if (!this.response) {
  454. return resolve({});
  455. }
  456. const bytes = new Uint8Array(this.response);
  457. resolve({
  458. base64: ParseFile.encodeBase64(bytes),
  459. contentType: xhr.getResponseHeader('content-type')
  460. });
  461. };
  462. options.requestTask(xhr);
  463. xhr.send();
  464. });
  465. },
  466. deleteFile: function (name, options) {
  467. const headers = {
  468. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
  469. };
  470. if (options.useMasterKey) {
  471. headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
  472. }
  473. let url = _CoreManager.default.get('SERVER_URL');
  474. if (url[url.length - 1] !== '/') {
  475. url += '/';
  476. }
  477. url += 'files/' + name;
  478. return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(response => {
  479. // TODO: return JSON object in server
  480. if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
  481. return _promise.default.resolve();
  482. } else {
  483. return _CoreManager.default.getRESTController().handleError(response);
  484. }
  485. });
  486. },
  487. _setXHR(xhr) {
  488. XHR = xhr;
  489. },
  490. _getXHR() {
  491. return XHR;
  492. }
  493. };
  494. _CoreManager.default.setFileController(DefaultController);
  495. var _default = exports.default = ParseFile;
  496. exports.b64Digit = b64Digit;