DropboxClient.js 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /**
  2. * Copyright (c) 2006-2024, JGraph Ltd
  3. * Copyright (c) 2006-2024, draw.io AG
  4. */
  5. //Add a closure to hide the class private variables without changing the code a lot
  6. (function()
  7. {
  8. var _token = null;
  9. window.DropboxClient = function(editorUi)
  10. {
  11. DrawioClient.call(this, editorUi, 'dbauth');
  12. this.client = new Dropbox({clientId: this.clientId});
  13. };
  14. // Extends DrawioClient
  15. mxUtils.extend(DropboxClient, DrawioClient);
  16. /**
  17. * FIXME: How to find name of app folder for current user. The Apps part of the
  18. * name is internationalized so this hardcoded check does not work everywhere.
  19. */
  20. DropboxClient.prototype.appPath = '/drawio-diagrams/';
  21. /**
  22. * Executes the first step for connecting to Google Drive.
  23. */
  24. DropboxClient.prototype.extension = '.drawio';
  25. /**
  26. * Executes the first step for connecting to Google Drive.
  27. */
  28. DropboxClient.prototype.writingFile = false;
  29. /**
  30. * Executes the first step for connecting to Google Drive.
  31. */
  32. DropboxClient.prototype.maxRetries = 4;
  33. DropboxClient.prototype.clientId = window.DRAWIO_DROPBOX_ID;
  34. DropboxClient.prototype.redirectUri = window.DRAWIO_SERVER_URL + 'dropbox';
  35. /**
  36. * Authorizes the client, gets the userId and calls <open>.
  37. */
  38. DropboxClient.prototype.logout = function()
  39. {
  40. //Send to server to clear refresh token cookie
  41. this.ui.editor.loadUrl(this.redirectUri + '?doLogout=1&state=' + encodeURIComponent('cId=' + this.clientId + '&domain=' + window.location.host));
  42. this.clearPersistentToken();
  43. this.setUser(null);
  44. _token = null;
  45. this.client.authTokenRevoke().then(mxUtils.bind(this, function()
  46. {
  47. this.client.setAccessToken(null);
  48. }));
  49. };
  50. /**
  51. * Checks if the client is authorized and calls the next step.
  52. */
  53. DropboxClient.prototype.updateUser = function(success, error, failOnAuth)
  54. {
  55. var acceptResponse = true;
  56. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  57. {
  58. acceptResponse = false;
  59. error({code: App.ERROR_TIMEOUT});
  60. }), this.ui.timeout);
  61. var promise = this.client.usersGetCurrentAccount();
  62. promise.then(mxUtils.bind(this, function(response)
  63. {
  64. window.clearTimeout(timeoutThread);
  65. if (acceptResponse)
  66. {
  67. this.setUser(new DrawioUser(response.account_id,
  68. response.email, response.name.display_name));
  69. success();
  70. }
  71. }));
  72. // Workaround for IE8/9 support with catch function
  73. promise['catch'](mxUtils.bind(this, function(err)
  74. {
  75. window.clearTimeout(timeoutThread);
  76. if (acceptResponse)
  77. {
  78. if (err != null && err.status === 401 && !failOnAuth)
  79. {
  80. this.setUser(null);
  81. this.client.setAccessToken(null);
  82. _token = null;
  83. this.authenticate(mxUtils.bind(this, function()
  84. {
  85. this.updateUser(success, error, true);
  86. }), error);
  87. }
  88. else
  89. {
  90. error({message: mxResources.get('accessDenied')});
  91. }
  92. }
  93. }));
  94. };
  95. /**
  96. * Authorizes the client, gets the userId and calls <open>.
  97. */
  98. DropboxClient.prototype.authenticate = function(success, error)
  99. {
  100. var req = new mxXmlRequest(this.redirectUri + '?getState=1', null, 'GET');
  101. req.send(mxUtils.bind(this, function(req)
  102. {
  103. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  104. {
  105. this.authenticateStep2(req.getText(), success, error);
  106. }
  107. else if (error != null)
  108. {
  109. error(req);
  110. }
  111. }), error);
  112. };
  113. DropboxClient.prototype.authenticateStep2 = function(state, success, error)
  114. {
  115. if (window.onDropboxCallback == null)
  116. {
  117. var auth = mxUtils.bind(this, function()
  118. {
  119. var acceptAuthResponse = true;
  120. var authRemembered = this.getPersistentToken(true);
  121. if (authRemembered != null)
  122. {
  123. var req = new mxXmlRequest(this.redirectUri + '?state=' + encodeURIComponent('cId=' + this.clientId + '&domain=' + window.location.host + '&token=' + state), null, 'GET'); //To identify which app/domain is used
  124. req.send(mxUtils.bind(this, function(req)
  125. {
  126. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  127. {
  128. try
  129. {
  130. _token = JSON.parse(req.getText()).access_token;
  131. this.client.setAccessToken(_token);
  132. this.setUser(null);
  133. success();
  134. }
  135. catch (e)
  136. {
  137. error({message: mxResources.get('authFailed'), retry: auth});
  138. }
  139. }
  140. else
  141. {
  142. this.clearPersistentToken();
  143. this.setUser(null);
  144. _token = null;
  145. this.client.setAccessToken(null);
  146. if (req.getStatus() == 401) // (Unauthorized) [e.g, invalid refresh token]
  147. {
  148. auth();
  149. }
  150. else
  151. {
  152. error({message: mxResources.get('accessDenied'), retry: auth});
  153. }
  154. }
  155. }), error);
  156. }
  157. else
  158. {
  159. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
  160. {
  161. var win = window.open('https://www.dropbox.com/oauth2/authorize?client_id=' +
  162. this.clientId + (remember? '&token_access_type=offline' : '') +
  163. '&redirect_uri=' + encodeURIComponent(this.redirectUri) +
  164. '&response_type=code&state=' + encodeURIComponent('cId=' + this.clientId + //To identify which app/domain is used
  165. '&domain=' + window.location.host + '&token=' + state), 'dbauth');
  166. if (win != null)
  167. {
  168. window.onDropboxCallback = mxUtils.bind(this, function(newAuthInfo, authWindow)
  169. {
  170. if (acceptAuthResponse)
  171. {
  172. window.onDropboxCallback = null;
  173. acceptAuthResponse = false;
  174. try
  175. {
  176. if (newAuthInfo == null)
  177. {
  178. error({message: mxResources.get('accessDenied'), retry: auth});
  179. }
  180. else
  181. {
  182. if (authSuccess != null)
  183. {
  184. authSuccess();
  185. }
  186. _token = newAuthInfo.access_token;
  187. this.client.setAccessToken(_token);
  188. this.setUser(null);
  189. if (remember)
  190. {
  191. this.setPersistentToken('remembered');
  192. }
  193. success();
  194. }
  195. }
  196. catch (e)
  197. {
  198. error(e);
  199. }
  200. finally
  201. {
  202. if (authWindow != null)
  203. {
  204. authWindow.close();
  205. }
  206. }
  207. }
  208. else if (authWindow != null)
  209. {
  210. authWindow.close();
  211. }
  212. });
  213. }
  214. else
  215. {
  216. error({message: mxResources.get('serviceUnavailableOrBlocked'), retry: auth});
  217. }
  218. }), mxUtils.bind(this, function()
  219. {
  220. if (acceptAuthResponse)
  221. {
  222. window.onDropboxCallback = null;
  223. acceptAuthResponse = false;
  224. error({message: mxResources.get('accessDenied'), retry: auth});
  225. }
  226. }));
  227. }
  228. });
  229. auth();
  230. }
  231. else
  232. {
  233. error({code: App.ERROR_BUSY});
  234. }
  235. };
  236. /**
  237. * Authorizes the client, gets the userId and calls <open>.
  238. */
  239. DropboxClient.prototype.executePromise = function(promiseFn, success, error)
  240. {
  241. var doExecute = mxUtils.bind(this, function(failOnAuth)
  242. {
  243. var acceptResponse = true;
  244. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  245. {
  246. acceptResponse = false;
  247. error({code: App.ERROR_TIMEOUT, retry: fn});
  248. }), this.ui.timeout);
  249. //Dropbox client start executing the promise once created so auth fails, so we send a function instead to delay promise creation
  250. var promise = promiseFn();
  251. promise.then(mxUtils.bind(this, function(response)
  252. {
  253. window.clearTimeout(timeoutThread);
  254. if (acceptResponse && success != null)
  255. {
  256. success(response);
  257. }
  258. }));
  259. // Workaround for IE8/9 support with catch function
  260. promise['catch'](mxUtils.bind(this, function(err)
  261. {
  262. window.clearTimeout(timeoutThread);
  263. if (acceptResponse)
  264. {
  265. if (err != null && (err.status == 500 || err.status == 400 ||
  266. err.status == 401))
  267. {
  268. this.setUser(null);
  269. this.client.setAccessToken(null);
  270. _token = null;
  271. if (!failOnAuth)
  272. {
  273. this.authenticate(function()
  274. {
  275. doExecute(true);
  276. }, error);
  277. }
  278. else
  279. {
  280. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  281. {
  282. this.authenticate(function()
  283. {
  284. fn(true);
  285. }, error);
  286. })});
  287. }
  288. }
  289. else
  290. {
  291. error({message: mxResources.get('error') + ' ' + err.status});
  292. }
  293. }
  294. }));
  295. });
  296. var fn = mxUtils.bind(this, function(failOnAuth)
  297. {
  298. if (this.user == null)
  299. {
  300. this.updateUser(function()
  301. {
  302. fn(true);
  303. }, error, failOnAuth);
  304. }
  305. else
  306. {
  307. doExecute(failOnAuth);
  308. }
  309. });
  310. if (_token == null)
  311. {
  312. this.authenticate(function()
  313. {
  314. fn(true);
  315. }, error);
  316. }
  317. else
  318. {
  319. fn(false);
  320. }
  321. };
  322. /**
  323. * Checks if the client is authorized and calls the next step.
  324. */
  325. DropboxClient.prototype.getLibrary = function(path, success, error)
  326. {
  327. this.getFile(path, success, error, true);
  328. };
  329. /**
  330. * DenyConvert is ignored in this client, just added for API compatibility.
  331. */
  332. DropboxClient.prototype.getFile = function(path, success, error, asLibrary)
  333. {
  334. asLibrary = (asLibrary != null) ? asLibrary : false;
  335. var binary = /\.png$/i.test(path);
  336. if (/^https:\/\//i.test(path) || /\.v(dx|sdx?)$/i.test(path) || /\.gliffy$/i.test(path) ||
  337. /\.pdf$/i.test(path) || (!this.ui.useCanvasForExport && binary))
  338. {
  339. var fn = mxUtils.bind(this, function()
  340. {
  341. var tokens = path.split('/');
  342. var name = (tokens.length > 0) ? tokens[tokens.length - 1] : path;
  343. this.ui.convertFile(path, name, null, this.extension, success, error);
  344. });
  345. if (_token != null)
  346. {
  347. fn();
  348. }
  349. else
  350. {
  351. this.authenticate(fn, error);
  352. }
  353. }
  354. else
  355. {
  356. var arg = {path: '/' + path};
  357. if (urlParams['rev'] != null)
  358. {
  359. arg.rev = urlParams['rev'];
  360. }
  361. this.readFile(arg, mxUtils.bind(this, function(data, response)
  362. {
  363. var index = (binary) ? data.lastIndexOf(',') : -1;
  364. var file = null;
  365. if (index > 0)
  366. {
  367. var xml = this.ui.extractGraphModelFromPng(data);
  368. if (xml != null && xml.length > 0)
  369. {
  370. data = xml;
  371. }
  372. else
  373. {
  374. // Imports as PNG image
  375. file = new LocalFile(this, data, path, true);
  376. }
  377. }
  378. success((file != null) ? file :
  379. ((asLibrary) ? new DropboxLibrary(this.ui, data, response) :
  380. new DropboxFile(this.ui, data, response)));
  381. }), error, binary);
  382. }
  383. };
  384. /**
  385. * Translates this point by the given vector.
  386. *
  387. * @param {number} dx X-coordinate of the translation.
  388. * @param {number} dy Y-coordinate of the translation.
  389. */
  390. DropboxClient.prototype.readFile = function(arg, success, error, binary)
  391. {
  392. var doExecute = mxUtils.bind(this, function(failOnAuth)
  393. {
  394. var acceptResponse = true;
  395. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  396. {
  397. acceptResponse = false;
  398. error({code: App.ERROR_TIMEOUT});
  399. }), this.ui.timeout);
  400. // Workaround for Uncaught DOMException in filesDownload is to
  401. // get the metadata to handle the file not found case
  402. var checkPromise = this.client.filesGetMetadata({path: '/' + arg.path.substring(1), include_deleted: false});
  403. checkPromise.then(mxUtils.bind(this, function(response)
  404. {
  405. // ignore
  406. }));
  407. // Workaround for IE8/9 support with catch function
  408. checkPromise['catch'](function(err)
  409. {
  410. window.clearTimeout(timeoutThread);
  411. if (acceptResponse && err != null && err.status == 409)
  412. {
  413. acceptResponse = false;
  414. error({message: mxResources.get('fileNotFound')});
  415. }
  416. });
  417. // Download file in parallel
  418. // LATER: Report Uncaught DOMException with path/not_found in filesDownload
  419. var promise = this.client.filesDownload(arg);
  420. promise.then(mxUtils.bind(this, function(response)
  421. {
  422. window.clearTimeout(timeoutThread);
  423. if (acceptResponse)
  424. {
  425. acceptResponse = false;
  426. try
  427. {
  428. var reader = new FileReader();
  429. reader.onload = mxUtils.bind(this, function(event)
  430. {
  431. success(reader.result, response);
  432. });
  433. if (binary)
  434. {
  435. reader.readAsDataURL(response.fileBlob);
  436. }
  437. else
  438. {
  439. reader.readAsText(response.fileBlob);
  440. }
  441. }
  442. catch (e)
  443. {
  444. error(e);
  445. }
  446. }
  447. }));
  448. // Workaround for IE8/9 support with catch function
  449. promise['catch'](mxUtils.bind(this, function(err)
  450. {
  451. window.clearTimeout(timeoutThread);
  452. if (acceptResponse)
  453. {
  454. acceptResponse = false;
  455. if (err != null && (err.status == 500 || err.status == 400 ||
  456. err.status == 401))
  457. {
  458. this.client.setAccessToken(null);
  459. this.setUser(null);
  460. _token = null;
  461. if (!failOnAuth)
  462. {
  463. this.authenticate(function()
  464. {
  465. doExecute(true);
  466. }, error);
  467. }
  468. else
  469. {
  470. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  471. {
  472. this.authenticate(function()
  473. {
  474. fn(true);
  475. }, error);
  476. })});
  477. }
  478. }
  479. else
  480. {
  481. error({message: mxResources.get('error') + ' ' + err.status});
  482. }
  483. }
  484. }));
  485. });
  486. var fn = mxUtils.bind(this, function(failOnAuth)
  487. {
  488. if (this.user == null)
  489. {
  490. this.updateUser(function()
  491. {
  492. fn(true);
  493. }, error, failOnAuth);
  494. }
  495. else
  496. {
  497. doExecute(failOnAuth);
  498. }
  499. });
  500. if (_token == null)
  501. {
  502. this.authenticate(function()
  503. {
  504. fn(true);
  505. }, error);
  506. }
  507. else
  508. {
  509. fn(false);
  510. }
  511. };
  512. /**
  513. * Translates this point by the given vector.
  514. *
  515. * @param {number} dx X-coordinate of the translation.
  516. * @param {number} dy Y-coordinate of the translation.
  517. */
  518. DropboxClient.prototype.checkExists = function(filename, fn, noConfirm)
  519. {
  520. var promiseFn = mxUtils.bind(this, function()
  521. {
  522. return this.client.filesGetMetadata({path: '/' + filename.toLowerCase(), include_deleted: false});
  523. });
  524. this.executePromise(promiseFn, mxUtils.bind(this, function(response)
  525. {
  526. if (noConfirm)
  527. {
  528. fn(false, true, response);
  529. }
  530. else
  531. {
  532. this.ui.confirm(mxResources.get('replaceIt', [filename]), function()
  533. {
  534. fn(true, true, response);
  535. }, function()
  536. {
  537. fn(false, true, response);
  538. });
  539. }
  540. }), function(err)
  541. {
  542. fn(true, false);
  543. });
  544. };
  545. /**
  546. * Translates this point by the given vector.
  547. *
  548. * @param {number} dx X-coordinate of the translation.
  549. * @param {number} dy Y-coordinate of the translation.
  550. */
  551. DropboxClient.prototype.renameFile = function(file, filename, success, error)
  552. {
  553. if (/[\\\/:\?\*"\|]/.test(filename))
  554. {
  555. error({message: mxResources.get('dropboxCharsNotAllowed')});
  556. }
  557. else
  558. {
  559. // Appends working directory of source file
  560. if (file != null && filename != null)
  561. {
  562. var path = file.stat.path_display.substring(1);
  563. var idx = path.lastIndexOf('/');
  564. if (idx > 0)
  565. {
  566. filename = path.substring(0, idx + 1) + filename;
  567. }
  568. }
  569. if (file != null && filename != null && file.stat.path_lower.substring(1) !== filename.toLowerCase())
  570. {
  571. // Checks if file exists
  572. this.checkExists(filename, mxUtils.bind(this, function(checked, exists, response)
  573. {
  574. if (checked)
  575. {
  576. var thenHandler = mxUtils.bind(this, function(deleteResponse)
  577. {
  578. var move = mxUtils.bind(this, function()
  579. {
  580. return this.client.filesMove({from_path: file.stat.path_display, to_path: '/' +
  581. filename, autorename: false});
  582. });
  583. this.executePromise(move, success, error);
  584. });
  585. // API fails on same name with different upper-/lowercase
  586. if (!exists || response.path_lower.substring(1) === filename.toLowerCase())
  587. {
  588. thenHandler();
  589. }
  590. else
  591. {
  592. // Deletes file first to avoid conflict in filesMove (non-atomic)
  593. var promiseFn = mxUtils.bind(this, function()
  594. {
  595. return this.client.filesDelete({path: '/' + filename.toLowerCase()});
  596. });
  597. this.executePromise(promiseFn, thenHandler, error);
  598. }
  599. }
  600. else
  601. {
  602. error();
  603. }
  604. }));
  605. }
  606. else
  607. {
  608. // Same name with different upper-/lowercase not supported by Dropbox API
  609. error({message: mxResources.get('invalidName')});
  610. }
  611. }
  612. };
  613. /**
  614. * Translates this point by the given vector.
  615. *
  616. * @param {number} dx X-coordinate of the translation.
  617. * @param {number} dy Y-coordinate of the translation.
  618. */
  619. DropboxClient.prototype.insertLibrary = function(filename, data, success, error)
  620. {
  621. this.insertFile(filename, data, success, error, true);
  622. };
  623. /**
  624. * Translates this point by the given vector.
  625. *
  626. * @param {number} dx X-coordinate of the translation.
  627. * @param {number} dy Y-coordinate of the translation.
  628. */
  629. DropboxClient.prototype.insertFile = function(filename, data, success, error, asLibrary)
  630. {
  631. asLibrary = (asLibrary != null) ? asLibrary : false;
  632. this.checkExists(filename, mxUtils.bind(this, function(checked)
  633. {
  634. if (checked)
  635. {
  636. this.saveFile(filename, data, mxUtils.bind(this, function(stat)
  637. {
  638. if (asLibrary)
  639. {
  640. success(new DropboxLibrary(this.ui, data, stat));
  641. }
  642. else
  643. {
  644. success(new DropboxFile(this.ui, data, stat));
  645. }
  646. }), error);
  647. }
  648. else
  649. {
  650. error();
  651. }
  652. }));
  653. };
  654. /**
  655. * Translates this point by the given vector.
  656. *
  657. * @param {number} dx X-coordinate of the translation.
  658. * @param {number} dy Y-coordinate of the translation.
  659. */
  660. DropboxClient.prototype.saveFile = function(filename, data, success, error, folder)
  661. {
  662. if (/[\\\/:\?\*"\|]/.test(filename))
  663. {
  664. error({message: mxResources.get('dropboxCharsNotAllowed')});
  665. }
  666. else if (data.length >= 150000000 /*150MB*/)
  667. {
  668. error({message: mxResources.get('drawingTooLarge') + ' (' +
  669. this.ui.formatFileSize(data.length) + ' / 150 MB)'});
  670. }
  671. else
  672. {
  673. folder = (folder != null) ? folder : '';
  674. // Mute switch is ignored
  675. var promiseFn = mxUtils.bind(this, function()
  676. {
  677. return this.client.filesUpload({path: '/' + folder + filename,
  678. mode: {'.tag': 'overwrite'}, mute: true,
  679. contents: new Blob([data], {type: 'text/plain'})});
  680. });
  681. this.executePromise(promiseFn, success, error);
  682. }
  683. };
  684. /**
  685. * Translates this point by the given vector.
  686. *
  687. * @param {number} dx X-coordinate of the translation.
  688. * @param {number} dy Y-coordinate of the translation.
  689. */
  690. DropboxClient.prototype.pickLibrary = function(fn)
  691. {
  692. // Authentication will be carried out on open to make sure the
  693. // autosave does not show an auth dialog. Showing it here will
  694. // block the second dialog (the file picker) so it's too early.
  695. Dropbox.choose(
  696. {
  697. linkType : 'direct',
  698. cancel: mxUtils.bind(this, function()
  699. {
  700. // do nothing
  701. }),
  702. success : mxUtils.bind(this, function(files)
  703. {
  704. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  705. {
  706. var error = mxUtils.bind(this, function(e)
  707. {
  708. this.ui.spinner.stop();
  709. this.ui.handleError(e);
  710. });
  711. var tmp = (files[0].link != null) ? files[0].link.indexOf(this.appPath) : -1;
  712. if (tmp > 0)
  713. {
  714. // Checks if file is in app folder by loading file from there and comparing the ID
  715. var rel = decodeURIComponent(files[0].link.substring(tmp + this.appPath.length - 1));
  716. this.readFile({path: rel}, mxUtils.bind(this, function(data, stat)
  717. {
  718. if (stat != null && stat.id == files[0].id)
  719. {
  720. // No need to load file a second time
  721. try
  722. {
  723. this.ui.spinner.stop();
  724. fn(rel.substring(1), new DropboxLibrary(this.ui, data, stat));
  725. }
  726. catch (e)
  727. {
  728. this.ui.handleError(e);
  729. }
  730. }
  731. else
  732. {
  733. this.createLibrary(files[0], fn, error);
  734. }
  735. }), error);
  736. }
  737. else
  738. {
  739. this.createLibrary(files[0], fn, error);
  740. }
  741. }
  742. })
  743. });
  744. };
  745. /**
  746. * Translates this point by the given vector.
  747. *
  748. * @param {number} dx X-coordinate of the translation.
  749. * @param {number} dy Y-coordinate of the translation.
  750. */
  751. DropboxClient.prototype.createLibrary = function(file, success, error)
  752. {
  753. this.ui.confirm(mxResources.get('note') + ': ' + mxResources.get('fileWillBeSavedInAppFolder',
  754. [file.name]), mxUtils.bind(this, function()
  755. {
  756. this.ui.editor.loadUrl(file.link, mxUtils.bind(this, function(data)
  757. {
  758. this.insertFile(file.name, data, mxUtils.bind(this, function(newFile)
  759. {
  760. try
  761. {
  762. this.ui.spinner.stop();
  763. success(newFile.getHash().substring(1), newFile);
  764. }
  765. catch (e)
  766. {
  767. error(e);
  768. }
  769. }), error, true);
  770. }), error);
  771. }), mxUtils.bind(this, function()
  772. {
  773. this.ui.spinner.stop();
  774. }));
  775. };
  776. /**
  777. * Translates this point by the given vector.
  778. *
  779. * @param {number} dx X-coordinate of the translation.
  780. * @param {number} dy Y-coordinate of the translation.
  781. */
  782. DropboxClient.prototype.pickFile = function(fn, readOnly)
  783. {
  784. if (Dropbox.choose != null)
  785. {
  786. fn = (fn != null) ? fn : mxUtils.bind(this, function(path, file)
  787. {
  788. this.ui.loadFile((path != null) ? 'D' + encodeURIComponent(path) : file.getHash(), null, file);
  789. });
  790. // Authentication will be carried out on open to make sure the
  791. // autosave does not show an auth dialog. Showing it here will
  792. // block the second dialog (the file picker) so it's too early.
  793. Dropbox.choose(
  794. {
  795. linkType : 'direct',
  796. cancel: mxUtils.bind(this, function()
  797. {
  798. // do nothing
  799. }),
  800. success : mxUtils.bind(this, function(files)
  801. {
  802. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  803. {
  804. // File used for read-only
  805. if (readOnly)
  806. {
  807. this.ui.spinner.stop();
  808. fn(files[0].link);
  809. }
  810. else
  811. {
  812. var error = mxUtils.bind(this, function(e)
  813. {
  814. this.ui.spinner.stop();
  815. this.ui.handleError(e);
  816. });
  817. var success = mxUtils.bind(this, function(path, file)
  818. {
  819. this.ui.spinner.stop();
  820. fn(path, file);
  821. });
  822. var binary = /\.png$/i.test(files[0].name);
  823. if (/\.vsdx$/i.test(files[0].name) || /\.gliffy$/i.test(files[0].name) ||
  824. (!this.ui.useCanvasForExport && binary))
  825. {
  826. success(files[0].link);
  827. }
  828. else
  829. {
  830. var tmp = (files[0].link != null) ? files[0].link.indexOf(this.appPath) : -1;
  831. if (tmp > 0)
  832. {
  833. // Checks if file is in app folder by loading file from there and comparing the ID
  834. var rel = decodeURIComponent(files[0].link.substring(tmp + this.appPath.length - 1));
  835. this.readFile({path: rel}, mxUtils.bind(this, function(data, stat)
  836. {
  837. if (stat != null && stat.id == files[0].id)
  838. {
  839. var index = (binary) ? data.lastIndexOf(',') : -1;
  840. this.ui.spinner.stop();
  841. var file = null;
  842. if (index > 0)
  843. {
  844. var xml = this.ui.extractGraphModelFromPng(data);
  845. if (xml != null && xml.length > 0)
  846. {
  847. data = xml;
  848. }
  849. else
  850. {
  851. // Imports as PNG image
  852. file = new LocalFile(this, data, rel, true);
  853. }
  854. }
  855. // No need to load file a second time
  856. fn(rel.substring(1), (file != null) ? file : new DropboxFile(this.ui, data, stat));
  857. }
  858. else
  859. {
  860. this.createFile(files[0], success, error);
  861. }
  862. }), error, binary);
  863. }
  864. else
  865. {
  866. this.createFile(files[0], success, error);
  867. }
  868. }
  869. }
  870. }
  871. })
  872. });
  873. }
  874. else
  875. {
  876. this.ui.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
  877. }
  878. };
  879. /**
  880. * Translates this point by the given vector.
  881. *
  882. * @param {number} dx X-coordinate of the translation.
  883. * @param {number} dy Y-coordinate of the translation.
  884. */
  885. DropboxClient.prototype.createFile = function(file, success, error)
  886. {
  887. var binary = /(\.png)$/i.test(file.name);
  888. this.ui.editor.loadUrl(file.link, mxUtils.bind(this, function(data)
  889. {
  890. if (data != null && data.length > 0)
  891. {
  892. this.ui.confirm(mxResources.get('note') + ': ' + mxResources.get('fileWillBeSavedInAppFolder', [file.name]), mxUtils.bind(this, function()
  893. {
  894. var index = (binary) ? data.lastIndexOf(',') : -1;
  895. if (index > 0)
  896. {
  897. var xml = this.ui.extractGraphModelFromPng(data.substring(index + 1));
  898. if (xml != null && xml.length > 0)
  899. {
  900. data = xml;
  901. }
  902. }
  903. this.insertFile(file.name, data, mxUtils.bind(this, function(newFile)
  904. {
  905. success(file.name, newFile);
  906. }), error);
  907. }), mxUtils.bind(this, function()
  908. {
  909. this.ui.spinner.stop();
  910. }));
  911. }
  912. else
  913. {
  914. this.ui.spinner.stop();
  915. error({message: mxResources.get('errorLoadingFile')});
  916. }
  917. }), error, binary);
  918. };
  919. })();