ParseFile.js 17 KB

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