ParseFile.js 15 KB

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