ParseFile.js 12 KB

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