ParseFile.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  7. var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
  8. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  9. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  10. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  11. function ownKeys(object, enumerableOnly) {
  12. var keys = Object.keys(object);
  13. if (Object.getOwnPropertySymbols) {
  14. var symbols = Object.getOwnPropertySymbols(object);
  15. enumerableOnly && (symbols = symbols.filter(function (sym) {
  16. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  17. })), keys.push.apply(keys, symbols);
  18. }
  19. return keys;
  20. }
  21. function _objectSpread(target) {
  22. for (var i = 1; i < arguments.length; i++) {
  23. var source = null != arguments[i] ? arguments[i] : {};
  24. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  25. (0, _defineProperty2.default)(target, key, source[key]);
  26. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  27. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  28. });
  29. }
  30. return target;
  31. }
  32. function _regeneratorRuntime() {
  33. "use strict";
  34. _regeneratorRuntime = function () {
  35. return exports;
  36. };
  37. var exports = {},
  38. Op = Object.prototype,
  39. hasOwn = Op.hasOwnProperty,
  40. $Symbol = "function" == typeof Symbol ? Symbol : {},
  41. iteratorSymbol = $Symbol.iterator || "@@iterator",
  42. asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
  43. toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  44. function define(obj, key, value) {
  45. return Object.defineProperty(obj, key, {
  46. value: value,
  47. enumerable: !0,
  48. configurable: !0,
  49. writable: !0
  50. }), obj[key];
  51. }
  52. try {
  53. define({}, "");
  54. } catch (err) {
  55. define = function (obj, key, value) {
  56. return obj[key] = value;
  57. };
  58. }
  59. function wrap(innerFn, outerFn, self, tryLocsList) {
  60. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
  61. generator = Object.create(protoGenerator.prototype),
  62. context = new Context(tryLocsList || []);
  63. return generator._invoke = function (innerFn, self, context) {
  64. var state = "suspendedStart";
  65. return function (method, arg) {
  66. if ("executing" === state) throw new Error("Generator is already running");
  67. if ("completed" === state) {
  68. if ("throw" === method) throw arg;
  69. return doneResult();
  70. }
  71. for (context.method = method, context.arg = arg;;) {
  72. var delegate = context.delegate;
  73. if (delegate) {
  74. var delegateResult = maybeInvokeDelegate(delegate, context);
  75. if (delegateResult) {
  76. if (delegateResult === ContinueSentinel) continue;
  77. return delegateResult;
  78. }
  79. }
  80. if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
  81. if ("suspendedStart" === state) throw state = "completed", context.arg;
  82. context.dispatchException(context.arg);
  83. } else "return" === context.method && context.abrupt("return", context.arg);
  84. state = "executing";
  85. var record = tryCatch(innerFn, self, context);
  86. if ("normal" === record.type) {
  87. if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
  88. return {
  89. value: record.arg,
  90. done: context.done
  91. };
  92. }
  93. "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
  94. }
  95. };
  96. }(innerFn, self, context), generator;
  97. }
  98. function tryCatch(fn, obj, arg) {
  99. try {
  100. return {
  101. type: "normal",
  102. arg: fn.call(obj, arg)
  103. };
  104. } catch (err) {
  105. return {
  106. type: "throw",
  107. arg: err
  108. };
  109. }
  110. }
  111. exports.wrap = wrap;
  112. var ContinueSentinel = {};
  113. function Generator() {}
  114. function GeneratorFunction() {}
  115. function GeneratorFunctionPrototype() {}
  116. var IteratorPrototype = {};
  117. define(IteratorPrototype, iteratorSymbol, function () {
  118. return this;
  119. });
  120. var getProto = Object.getPrototypeOf,
  121. NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  122. NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
  123. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  124. function defineIteratorMethods(prototype) {
  125. ["next", "throw", "return"].forEach(function (method) {
  126. define(prototype, method, function (arg) {
  127. return this._invoke(method, arg);
  128. });
  129. });
  130. }
  131. function AsyncIterator(generator, PromiseImpl) {
  132. function invoke(method, arg, resolve, reject) {
  133. var record = tryCatch(generator[method], generator, arg);
  134. if ("throw" !== record.type) {
  135. var result = record.arg,
  136. value = result.value;
  137. return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
  138. invoke("next", value, resolve, reject);
  139. }, function (err) {
  140. invoke("throw", err, resolve, reject);
  141. }) : PromiseImpl.resolve(value).then(function (unwrapped) {
  142. result.value = unwrapped, resolve(result);
  143. }, function (error) {
  144. return invoke("throw", error, resolve, reject);
  145. });
  146. }
  147. reject(record.arg);
  148. }
  149. var previousPromise;
  150. this._invoke = function (method, arg) {
  151. function callInvokeWithMethodAndArg() {
  152. return new PromiseImpl(function (resolve, reject) {
  153. invoke(method, arg, resolve, reject);
  154. });
  155. }
  156. return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  157. };
  158. }
  159. function maybeInvokeDelegate(delegate, context) {
  160. var method = delegate.iterator[context.method];
  161. if (undefined === method) {
  162. if (context.delegate = null, "throw" === context.method) {
  163. if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
  164. context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
  165. }
  166. return ContinueSentinel;
  167. }
  168. var record = tryCatch(method, delegate.iterator, context.arg);
  169. if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
  170. var info = record.arg;
  171. return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
  172. }
  173. function pushTryEntry(locs) {
  174. var entry = {
  175. tryLoc: locs[0]
  176. };
  177. 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
  178. }
  179. function resetTryEntry(entry) {
  180. var record = entry.completion || {};
  181. record.type = "normal", delete record.arg, entry.completion = record;
  182. }
  183. function Context(tryLocsList) {
  184. this.tryEntries = [{
  185. tryLoc: "root"
  186. }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
  187. }
  188. function values(iterable) {
  189. if (iterable) {
  190. var iteratorMethod = iterable[iteratorSymbol];
  191. if (iteratorMethod) return iteratorMethod.call(iterable);
  192. if ("function" == typeof iterable.next) return iterable;
  193. if (!isNaN(iterable.length)) {
  194. var i = -1,
  195. next = function next() {
  196. for (; ++i < iterable.length;) {
  197. if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
  198. }
  199. return next.value = undefined, next.done = !0, next;
  200. };
  201. return next.next = next;
  202. }
  203. }
  204. return {
  205. next: doneResult
  206. };
  207. }
  208. function doneResult() {
  209. return {
  210. value: undefined,
  211. done: !0
  212. };
  213. }
  214. return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
  215. var ctor = "function" == typeof genFun && genFun.constructor;
  216. return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
  217. }, exports.mark = function (genFun) {
  218. return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
  219. }, exports.awrap = function (arg) {
  220. return {
  221. __await: arg
  222. };
  223. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
  224. return this;
  225. }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  226. void 0 === PromiseImpl && (PromiseImpl = Promise);
  227. var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
  228. return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
  229. return result.done ? result.value : iter.next();
  230. });
  231. }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
  232. return this;
  233. }), define(Gp, "toString", function () {
  234. return "[object Generator]";
  235. }), exports.keys = function (object) {
  236. var keys = [];
  237. for (var key in object) {
  238. keys.push(key);
  239. }
  240. return keys.reverse(), function next() {
  241. for (; keys.length;) {
  242. var key = keys.pop();
  243. if (key in object) return next.value = key, next.done = !1, next;
  244. }
  245. return next.done = !0, next;
  246. };
  247. }, exports.values = values, Context.prototype = {
  248. constructor: Context,
  249. reset: function (skipTempReset) {
  250. if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) {
  251. "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
  252. }
  253. },
  254. stop: function () {
  255. this.done = !0;
  256. var rootRecord = this.tryEntries[0].completion;
  257. if ("throw" === rootRecord.type) throw rootRecord.arg;
  258. return this.rval;
  259. },
  260. dispatchException: function (exception) {
  261. if (this.done) throw exception;
  262. var context = this;
  263. function handle(loc, caught) {
  264. return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
  265. }
  266. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  267. var entry = this.tryEntries[i],
  268. record = entry.completion;
  269. if ("root" === entry.tryLoc) return handle("end");
  270. if (entry.tryLoc <= this.prev) {
  271. var hasCatch = hasOwn.call(entry, "catchLoc"),
  272. hasFinally = hasOwn.call(entry, "finallyLoc");
  273. if (hasCatch && hasFinally) {
  274. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  275. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  276. } else if (hasCatch) {
  277. if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
  278. } else {
  279. if (!hasFinally) throw new Error("try statement without catch or finally");
  280. if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
  281. }
  282. }
  283. }
  284. },
  285. abrupt: function (type, arg) {
  286. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  287. var entry = this.tryEntries[i];
  288. if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
  289. var finallyEntry = entry;
  290. break;
  291. }
  292. }
  293. finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
  294. var record = finallyEntry ? finallyEntry.completion : {};
  295. return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
  296. },
  297. complete: function (record, afterLoc) {
  298. if ("throw" === record.type) throw record.arg;
  299. return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
  300. },
  301. finish: function (finallyLoc) {
  302. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  303. var entry = this.tryEntries[i];
  304. if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
  305. }
  306. },
  307. catch: function (tryLoc) {
  308. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  309. var entry = this.tryEntries[i];
  310. if (entry.tryLoc === tryLoc) {
  311. var record = entry.completion;
  312. if ("throw" === record.type) {
  313. var thrown = record.arg;
  314. resetTryEntry(entry);
  315. }
  316. return thrown;
  317. }
  318. }
  319. throw new Error("illegal catch attempt");
  320. },
  321. delegateYield: function (iterable, resultName, nextLoc) {
  322. return this.delegate = {
  323. iterator: values(iterable),
  324. resultName: resultName,
  325. nextLoc: nextLoc
  326. }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
  327. }
  328. }, exports;
  329. }
  330. var ParseError = require('./ParseError').default;
  331. var XHR = null;
  332. if (typeof XMLHttpRequest !== 'undefined') {
  333. XHR = XMLHttpRequest;
  334. }
  335. function b64Digit(number) {
  336. if (number < 26) {
  337. return String.fromCharCode(65 + number);
  338. }
  339. if (number < 52) {
  340. return String.fromCharCode(97 + (number - 26));
  341. }
  342. if (number < 62) {
  343. return String.fromCharCode(48 + (number - 52));
  344. }
  345. if (number === 62) {
  346. return '+';
  347. }
  348. if (number === 63) {
  349. return '/';
  350. }
  351. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  352. }
  353. var ParseFile = function () {
  354. function ParseFile(name, data, type, metadata, tags) {
  355. (0, _classCallCheck2.default)(this, ParseFile);
  356. var specifiedType = type || '';
  357. this._name = name;
  358. this._metadata = metadata || {};
  359. this._tags = tags || {};
  360. if (data !== undefined) {
  361. if (Array.isArray(data)) {
  362. this._data = ParseFile.encodeBase64(data);
  363. this._source = {
  364. format: 'base64',
  365. base64: this._data,
  366. type: specifiedType
  367. };
  368. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  369. this._source = {
  370. format: 'file',
  371. file: data,
  372. type: specifiedType
  373. };
  374. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  375. this._source = {
  376. format: 'uri',
  377. uri: data.uri,
  378. type: specifiedType
  379. };
  380. } else if (data && typeof data.base64 === 'string') {
  381. var base64 = data.base64.split(',').slice(-1)[0];
  382. var dataType = specifiedType || data.base64.split(';').slice(0, 1)[0].split(':').slice(1, 2)[0] || 'text/plain';
  383. this._data = base64;
  384. this._source = {
  385. format: 'base64',
  386. base64: base64,
  387. type: dataType
  388. };
  389. } else {
  390. throw new TypeError('Cannot create a Parse.File with that data.');
  391. }
  392. }
  393. }
  394. (0, _createClass2.default)(ParseFile, [{
  395. key: "getData",
  396. value: function () {
  397. var _this = this;
  398. var options, controller, result;
  399. return _regeneratorRuntime().async(function (_context) {
  400. while (1) {
  401. switch (_context.prev = _context.next) {
  402. case 0:
  403. if (!this._data) {
  404. _context.next = 2;
  405. break;
  406. }
  407. return _context.abrupt("return", this._data);
  408. case 2:
  409. if (this._url) {
  410. _context.next = 4;
  411. break;
  412. }
  413. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  414. case 4:
  415. options = {
  416. requestTask: function (task) {
  417. return _this._requestTask = task;
  418. }
  419. };
  420. controller = _CoreManager.default.getFileController();
  421. _context.next = 8;
  422. return _regeneratorRuntime().awrap(controller.download(this._url, options));
  423. case 8:
  424. result = _context.sent;
  425. this._data = result.base64;
  426. return _context.abrupt("return", this._data);
  427. case 11:
  428. case "end":
  429. return _context.stop();
  430. }
  431. }
  432. }, null, this, null, Promise);
  433. }
  434. }, {
  435. key: "name",
  436. value: function () {
  437. return this._name;
  438. }
  439. }, {
  440. key: "url",
  441. value: function (options) {
  442. options = options || {};
  443. if (!this._url) {
  444. return;
  445. }
  446. if (options.forceSecure) {
  447. return this._url.replace(/^http:\/\//i, 'https://');
  448. } else {
  449. return this._url;
  450. }
  451. }
  452. }, {
  453. key: "metadata",
  454. value: function () {
  455. return this._metadata;
  456. }
  457. }, {
  458. key: "tags",
  459. value: function () {
  460. return this._tags;
  461. }
  462. }, {
  463. key: "save",
  464. value: function (options) {
  465. var _this2 = this;
  466. options = options || {};
  467. options.requestTask = function (task) {
  468. return _this2._requestTask = task;
  469. };
  470. options.metadata = this._metadata;
  471. options.tags = this._tags;
  472. var controller = _CoreManager.default.getFileController();
  473. if (!this._previousSave) {
  474. if (this._source.format === 'file') {
  475. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  476. _this2._name = res.name;
  477. _this2._url = res.url;
  478. _this2._data = null;
  479. _this2._requestTask = null;
  480. return _this2;
  481. });
  482. } else if (this._source.format === 'uri') {
  483. this._previousSave = controller.download(this._source.uri, options).then(function (result) {
  484. if (!(result && result.base64)) {
  485. return {};
  486. }
  487. var newSource = {
  488. format: 'base64',
  489. base64: result.base64,
  490. type: result.contentType
  491. };
  492. _this2._data = result.base64;
  493. _this2._requestTask = null;
  494. return controller.saveBase64(_this2._name, newSource, options);
  495. }).then(function (res) {
  496. _this2._name = res.name;
  497. _this2._url = res.url;
  498. _this2._requestTask = null;
  499. return _this2;
  500. });
  501. } else {
  502. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  503. _this2._name = res.name;
  504. _this2._url = res.url;
  505. _this2._requestTask = null;
  506. return _this2;
  507. });
  508. }
  509. }
  510. if (this._previousSave) {
  511. return this._previousSave;
  512. }
  513. }
  514. }, {
  515. key: "cancel",
  516. value: function () {
  517. if (this._requestTask && typeof this._requestTask.abort === 'function') {
  518. this._requestTask.abort();
  519. }
  520. this._requestTask = null;
  521. }
  522. }, {
  523. key: "destroy",
  524. value: function () {
  525. var _this3 = this;
  526. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  527. if (!this._name) {
  528. throw new ParseError(ParseError.FILE_DELETE_UNNAMED_ERROR, 'Cannot delete an unnamed file.');
  529. }
  530. var destroyOptions = {
  531. useMasterKey: true
  532. };
  533. if (options.hasOwnProperty('useMasterKey')) {
  534. destroyOptions.useMasterKey = options.useMasterKey;
  535. }
  536. var controller = _CoreManager.default.getFileController();
  537. return controller.deleteFile(this._name, destroyOptions).then(function () {
  538. _this3._data = null;
  539. _this3._requestTask = null;
  540. return _this3;
  541. });
  542. }
  543. }, {
  544. key: "toJSON",
  545. value: function () {
  546. return {
  547. __type: 'File',
  548. name: this._name,
  549. url: this._url
  550. };
  551. }
  552. }, {
  553. key: "equals",
  554. value: function (other) {
  555. if (this === other) {
  556. return true;
  557. }
  558. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  559. }
  560. }, {
  561. key: "setMetadata",
  562. value: function (metadata) {
  563. var _this4 = this;
  564. if (metadata && typeof metadata === 'object') {
  565. Object.keys(metadata).forEach(function (key) {
  566. _this4.addMetadata(key, metadata[key]);
  567. });
  568. }
  569. }
  570. }, {
  571. key: "addMetadata",
  572. value: function (key, value) {
  573. if (typeof key === 'string') {
  574. this._metadata[key] = value;
  575. }
  576. }
  577. }, {
  578. key: "setTags",
  579. value: function (tags) {
  580. var _this5 = this;
  581. if (tags && typeof tags === 'object') {
  582. Object.keys(tags).forEach(function (key) {
  583. _this5.addTag(key, tags[key]);
  584. });
  585. }
  586. }
  587. }, {
  588. key: "addTag",
  589. value: function (key, value) {
  590. if (typeof key === 'string') {
  591. this._tags[key] = value;
  592. }
  593. }
  594. }], [{
  595. key: "fromJSON",
  596. value: function (obj) {
  597. if (obj.__type !== 'File') {
  598. throw new TypeError('JSON object does not represent a ParseFile');
  599. }
  600. var file = new ParseFile(obj.name);
  601. file._url = obj.url;
  602. return file;
  603. }
  604. }, {
  605. key: "encodeBase64",
  606. value: function (bytes) {
  607. var chunks = [];
  608. chunks.length = Math.ceil(bytes.length / 3);
  609. for (var i = 0; i < chunks.length; i++) {
  610. var b1 = bytes[i * 3];
  611. var b2 = bytes[i * 3 + 1] || 0;
  612. var b3 = bytes[i * 3 + 2] || 0;
  613. var has2 = i * 3 + 1 < bytes.length;
  614. var has3 = i * 3 + 2 < bytes.length;
  615. 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('');
  616. }
  617. return chunks.join('');
  618. }
  619. }]);
  620. return ParseFile;
  621. }();
  622. var DefaultController = {
  623. saveFile: function (name, source, options) {
  624. var base64Data, _base64Data$split, _base64Data$split2, first, second, data, newSource;
  625. return _regeneratorRuntime().async(function (_context2) {
  626. while (1) {
  627. switch (_context2.prev = _context2.next) {
  628. case 0:
  629. if (!(source.format !== 'file')) {
  630. _context2.next = 2;
  631. break;
  632. }
  633. throw new Error('saveFile can only be used with File-type sources.');
  634. case 2:
  635. _context2.next = 4;
  636. return _regeneratorRuntime().awrap(new Promise(function (res, rej) {
  637. var reader = new FileReader();
  638. reader.onload = function () {
  639. return res(reader.result);
  640. };
  641. reader.onerror = function (error) {
  642. return rej(error);
  643. };
  644. reader.readAsDataURL(source.file);
  645. }));
  646. case 4:
  647. base64Data = _context2.sent;
  648. _base64Data$split = base64Data.split(','), _base64Data$split2 = (0, _slicedToArray2.default)(_base64Data$split, 2), first = _base64Data$split2[0], second = _base64Data$split2[1];
  649. data = second ? second : first;
  650. newSource = {
  651. format: 'base64',
  652. base64: data,
  653. type: source.type || (source.file ? source.file.type : null)
  654. };
  655. _context2.next = 10;
  656. return _regeneratorRuntime().awrap(DefaultController.saveBase64(name, newSource, options));
  657. case 10:
  658. return _context2.abrupt("return", _context2.sent);
  659. case 11:
  660. case "end":
  661. return _context2.stop();
  662. }
  663. }
  664. }, null, null, null, Promise);
  665. },
  666. saveBase64: function (name, source, options) {
  667. if (source.format !== 'base64') {
  668. throw new Error('saveBase64 can only be used with Base64-type sources.');
  669. }
  670. var data = {
  671. base64: source.base64,
  672. fileData: {
  673. metadata: _objectSpread({}, options.metadata),
  674. tags: _objectSpread({}, options.tags)
  675. }
  676. };
  677. delete options.metadata;
  678. delete options.tags;
  679. if (source.type) {
  680. data._ContentType = source.type;
  681. }
  682. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  683. },
  684. download: function (uri, options) {
  685. if (XHR) {
  686. return this.downloadAjax(uri, options);
  687. } else {
  688. return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  689. }
  690. },
  691. downloadAjax: function (uri, options) {
  692. return new Promise(function (resolve, reject) {
  693. var xhr = new XHR();
  694. xhr.open('GET', uri, true);
  695. xhr.responseType = 'arraybuffer';
  696. xhr.onerror = function (e) {
  697. reject(e);
  698. };
  699. xhr.onreadystatechange = function () {
  700. if (xhr.readyState !== xhr.DONE) {
  701. return;
  702. }
  703. if (!this.response) {
  704. return resolve({});
  705. }
  706. var bytes = new Uint8Array(this.response);
  707. resolve({
  708. base64: ParseFile.encodeBase64(bytes),
  709. contentType: xhr.getResponseHeader('content-type')
  710. });
  711. };
  712. options.requestTask(xhr);
  713. xhr.send();
  714. });
  715. },
  716. deleteFile: function (name, options) {
  717. var headers = {
  718. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID')
  719. };
  720. if (options.useMasterKey) {
  721. headers['X-Parse-Master-Key'] = _CoreManager.default.get('MASTER_KEY');
  722. }
  723. var url = _CoreManager.default.get('SERVER_URL');
  724. if (url[url.length - 1] !== '/') {
  725. url += '/';
  726. }
  727. url += 'files/' + name;
  728. return _CoreManager.default.getRESTController().ajax('DELETE', url, '', headers).catch(function (response) {
  729. if (!response || response === 'SyntaxError: Unexpected end of JSON input') {
  730. return Promise.resolve();
  731. } else {
  732. return _CoreManager.default.getRESTController().handleError(response);
  733. }
  734. });
  735. },
  736. _setXHR: function (xhr) {
  737. XHR = xhr;
  738. },
  739. _getXHR: function () {
  740. return XHR;
  741. }
  742. };
  743. _CoreManager.default.setFileController(DefaultController);
  744. var _default = ParseFile;
  745. exports.default = _default;
  746. exports.b64Digit = b64Digit;