DropboxClient.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /**
  2. * Copyright (c) 2006-2016, JGraph Ltd
  3. * Copyright (c) 2006-2016, Gaudenz Alder
  4. */
  5. /**
  6. * Constructs a new point for the optional x and y coordinates. If no
  7. * coordinates are given, then the default values for <x> and <y> are used.
  8. * @constructor
  9. * @class Implements a basic 2D point. Known subclassers = {@link mxRectangle}.
  10. * @param {number} x X-coordinate of the point.
  11. * @param {number} y Y-coordinate of the point.
  12. */
  13. DropboxClient = function(editorUi)
  14. {
  15. mxEventSource.call(this);
  16. /**
  17. * Holds the x-coordinate of the point.
  18. * @type number
  19. * @default 0
  20. */
  21. this.ui = editorUi;
  22. /**
  23. * Holds the x-coordinate of the point.
  24. * @type number
  25. * @default 0
  26. */
  27. this.client = new Dropbox.Client(
  28. {
  29. key: App.DROPBOX_APPKEY,
  30. sandbox: true
  31. });
  32. /**
  33. * Holds the x-coordinate of the point.
  34. * @type number
  35. * @default 0
  36. */
  37. this.client.authDriver(new Dropbox.AuthDriver.Popup(
  38. {
  39. rememberUser: true,
  40. receiverUrl: 'https://' + window.location.host + '/dropbox.html'
  41. }));
  42. };
  43. // Extends mxEventSource
  44. mxUtils.extend(DropboxClient, mxEventSource);
  45. /**
  46. * FIXME: How to find name of app folder for current user. The Apps part of the
  47. * name is internationalized so this hardcoded check does not work everywhere.
  48. */
  49. DropboxClient.prototype.appPath = '/drawio/';
  50. /**
  51. * Executes the first step for connecting to Google Drive.
  52. */
  53. DropboxClient.prototype.extension = '.html';
  54. /**
  55. * Executes the first step for connecting to Google Drive.
  56. */
  57. DriveClient.prototype.maxRetries = 4;
  58. /**
  59. * Executes the first step for connecting to Google Drive.
  60. */
  61. DropboxClient.prototype.user = null;
  62. /**
  63. * Executes the first step for connecting to Google Drive.
  64. */
  65. DropboxClient.prototype.writingFile = false;
  66. /**
  67. * Authorizes the client, gets the userId and calls <open>.
  68. */
  69. DropboxClient.prototype.logout = function()
  70. {
  71. this.client.signOut(mxUtils.bind(this, function()
  72. {
  73. this.setUser(null);
  74. }));
  75. };
  76. /**
  77. * Authorizes the client, gets the userId and calls <open>.
  78. */
  79. DropboxClient.prototype.setUser = function(user)
  80. {
  81. this.user = user;
  82. this.fireEvent(new mxEventObject('userChanged'));
  83. };
  84. /**
  85. * Authorizes the client, gets the userId and calls <open>.
  86. */
  87. DropboxClient.prototype.getUser = function()
  88. {
  89. return this.user;
  90. };
  91. /**
  92. * Checks if the client is authorized and calls the next step.
  93. */
  94. DropboxClient.prototype.updateUser = function(success, error, remember)
  95. {
  96. this.client.getUserInfo(null, mxUtils.bind(this, function(error, info)
  97. {
  98. if (error == null)
  99. {
  100. this.setUser(new DrawioUser(info.uid, info.email, info.name));
  101. }
  102. else
  103. {
  104. this.setUser(null);
  105. }
  106. }));
  107. };
  108. /**
  109. * Authorizes the client, gets the userId and calls <open>.
  110. */
  111. DropboxClient.prototype.execute = function(fn)
  112. {
  113. if (this.client.isAuthenticated())
  114. {
  115. fn();
  116. }
  117. else
  118. {
  119. this.authorize(false, mxUtils.bind(this, function(error, client)
  120. {
  121. if (error != null)
  122. {
  123. this.ui.handleError(error);
  124. }
  125. else
  126. {
  127. if (this.client.isAuthenticated())
  128. {
  129. this.updateUser();
  130. fn();
  131. }
  132. else
  133. {
  134. this.ui.showAuthDialog(this, false, mxUtils.bind(this, function(remember, success)
  135. {
  136. this.authorize(true, mxUtils.bind(this, function(error2, client)
  137. {
  138. if (error2 != null)
  139. {
  140. this.ui.handleError(error2);
  141. }
  142. else if (this.client.isAuthenticated())
  143. {
  144. this.updateUser();
  145. if (success != null)
  146. {
  147. success();
  148. }
  149. fn();
  150. }
  151. }));
  152. }));
  153. }
  154. }
  155. }));
  156. }
  157. };
  158. /**
  159. * Authorizes the client, gets the userId and calls <open>.
  160. */
  161. DropboxClient.prototype.authorize = function(interactive, fn)
  162. {
  163. this.client.authenticate({interactive: interactive}, mxUtils.bind(this, function(error, client)
  164. {
  165. if (error != null)
  166. {
  167. if (window.console != null)
  168. {
  169. console.log(error);
  170. }
  171. }
  172. else
  173. {
  174. fn();
  175. }
  176. }));
  177. };
  178. /**
  179. * Checks if the client is authorized and calls the next step.
  180. */
  181. DropboxClient.prototype.getLibrary = function(path, success, error)
  182. {
  183. this.getFile(path, success, error, false, true);
  184. };
  185. /**
  186. * DenyConvert is ignored in this client, just added for API compatibility.
  187. */
  188. DropboxClient.prototype.getFile = function(path, success, error, denyConvert, asLibrary)
  189. {
  190. asLibrary = (asLibrary != null) ? asLibrary : false;
  191. var fn = mxUtils.bind(this, function()
  192. {
  193. this.execute(mxUtils.bind(this, function()
  194. {
  195. var acceptResponse = true;
  196. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  197. {
  198. acceptResponse = false;
  199. error({code: App.ERROR_TIMEOUT, retry: fn});
  200. }), this.ui.timeout);
  201. var options = null;
  202. if (urlParams['rev'] != null)
  203. {
  204. options = {versionTag: urlParams['rev']};
  205. }
  206. this.client.readFile('/' + path, options, mxUtils.bind(this, function(err, data, stat)
  207. {
  208. try
  209. {
  210. window.clearTimeout(timeoutThread);
  211. if (acceptResponse)
  212. {
  213. if (err != null)
  214. {
  215. error(err)
  216. }
  217. else
  218. {
  219. if (asLibrary)
  220. {
  221. success(new DropboxLibrary(this.ui, data, stat));
  222. }
  223. else
  224. {
  225. success(new DropboxFile(this.ui, data, stat));
  226. }
  227. }
  228. }
  229. }
  230. catch (e)
  231. {
  232. error(e);
  233. }
  234. }));
  235. }));
  236. });
  237. fn();
  238. };
  239. /**
  240. * Translates this point by the given vector.
  241. *
  242. * @param {number} dx X-coordinate of the translation.
  243. * @param {number} dy Y-coordinate of the translation.
  244. */
  245. DropboxClient.prototype.checkExists = function(filename, fn)
  246. {
  247. this.client.stat(filename, mxUtils.bind(this, function(err, stat)
  248. {
  249. if ((err != null && err.status == 404) || (stat != null && stat.isRemoved))
  250. {
  251. fn(true);
  252. }
  253. else
  254. {
  255. this.ui.confirm(mxResources.get('replaceIt', [filename]), function()
  256. {
  257. fn(true);
  258. }, function()
  259. {
  260. fn(false);
  261. });
  262. }
  263. }));
  264. };
  265. /**
  266. * Translates this point by the given vector.
  267. *
  268. * @param {number} dx X-coordinate of the translation.
  269. * @param {number} dy Y-coordinate of the translation.
  270. */
  271. DropboxClient.prototype.renameFile = function(file, filename, success, error)
  272. {
  273. if (file != null && filename != null)
  274. {
  275. // Checks if file exists
  276. this.execute(mxUtils.bind(this, function()
  277. {
  278. this.checkExists(filename, mxUtils.bind(this, function(checked)
  279. {
  280. if (checked)
  281. {
  282. // Uses write and remove because move does not allow overwriting an existing target
  283. this.writeFile(filename, file.getData(), mxUtils.bind(this, function(stat)
  284. {
  285. this.client.remove(file.getTitle(), function(err2, stat2)
  286. {
  287. if (err2 != null)
  288. {
  289. error(err2)
  290. }
  291. else
  292. {
  293. success(stat);
  294. }
  295. });
  296. }), error);
  297. }
  298. else
  299. {
  300. error();
  301. }
  302. }));
  303. }));
  304. }
  305. };
  306. /**
  307. * Translates this point by the given vector.
  308. *
  309. * @param {number} dx X-coordinate of the translation.
  310. * @param {number} dy Y-coordinate of the translation.
  311. */
  312. DropboxClient.prototype.insertLibrary = function(filename, data, success, error)
  313. {
  314. this.insertFile(filename, data, success, error, true);
  315. };
  316. /**
  317. * Translates this point by the given vector.
  318. *
  319. * @param {number} dx X-coordinate of the translation.
  320. * @param {number} dy Y-coordinate of the translation.
  321. */
  322. DropboxClient.prototype.insertFile = function(filename, data, success, error, asLibrary)
  323. {
  324. asLibrary = (asLibrary != null) ? asLibrary : false;
  325. this.execute(mxUtils.bind(this, function()
  326. {
  327. this.checkExists(filename, mxUtils.bind(this, function(checked)
  328. {
  329. if (checked)
  330. {
  331. this.writeFile(filename, data, mxUtils.bind(this, function(stat)
  332. {
  333. if (asLibrary)
  334. {
  335. success(new DropboxLibrary(this.ui, data, stat));
  336. }
  337. else
  338. {
  339. success(new DropboxFile(this.ui, data, stat));
  340. }
  341. }), error);
  342. }
  343. else
  344. {
  345. error();
  346. }
  347. }));
  348. }));
  349. };
  350. /**
  351. * Translates this point by the given vector.
  352. *
  353. * @param {number} dx X-coordinate of the translation.
  354. * @param {number} dy Y-coordinate of the translation.
  355. */
  356. DropboxClient.prototype.saveFile = function(filename, data, success, error)
  357. {
  358. this.execute(mxUtils.bind(this, function()
  359. {
  360. this.writeFile(filename, data, success, error);
  361. }));
  362. };
  363. /**
  364. * Translates this point by the given vector.
  365. *
  366. * @param {number} dx X-coordinate of the translation.
  367. * @param {number} dy Y-coordinate of the translation.
  368. */
  369. DropboxClient.prototype.writeFile = function(filename, data, success, error)
  370. {
  371. if (/[\\\/:\?\*"\|]/.test(filename))
  372. {
  373. if (error != null)
  374. {
  375. error({message: mxResources.get('dropboxCharsNotAllowed')});
  376. }
  377. }
  378. else if (!this.writingFile)
  379. {
  380. var acceptResponse = true;
  381. var timeoutThread = null;
  382. this.writingFile = true;
  383. var retryCount = 0;
  384. // Cancels any pending requests
  385. if (this.requestThread != null)
  386. {
  387. window.clearTimeout(this.requestThread);
  388. }
  389. var fn = mxUtils.bind(this, function()
  390. {
  391. if (timeoutThread != null)
  392. {
  393. window.clearTimeout(timeoutThread);
  394. }
  395. timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  396. {
  397. this.writingFile = false;
  398. acceptResponse = false;
  399. if (error != null)
  400. {
  401. error({code: App.ERROR_TIMEOUT, retry: fn});
  402. }
  403. }), this.ui.timeout);
  404. this.client.writeFile(filename, data, mxUtils.bind(this, function(err, stat)
  405. {
  406. window.clearTimeout(timeoutThread);
  407. if (acceptResponse)
  408. {
  409. if (err != null)
  410. {
  411. if (retryCount < this.maxRetries)
  412. {
  413. retryCount++;
  414. var jitter = 1 + 0.1 * (Math.random() - 0.5);
  415. this.requestThread = window.setTimeout(fn, Math.round(Math.pow(2, retryCount) * jitter * 1000));
  416. }
  417. else if (error != null)
  418. {
  419. this.writingFile = false;
  420. error(err);
  421. }
  422. }
  423. else
  424. {
  425. this.writingFile = false;
  426. if (success != null)
  427. {
  428. success(stat);
  429. }
  430. }
  431. }
  432. }));
  433. });
  434. fn();
  435. }
  436. else if (error != null)
  437. {
  438. error({code: App.ERROR_BUSY});
  439. }
  440. };
  441. /**
  442. * Translates this point by the given vector.
  443. *
  444. * @param {number} dx X-coordinate of the translation.
  445. * @param {number} dy Y-coordinate of the translation.
  446. */
  447. DropboxClient.prototype.pickLibrary = function(fn)
  448. {
  449. // Authentication will be carried out on open to make sure the
  450. // autosave does not show an auth dialog. Showing it here will
  451. // block the second dialog (the file picker) so it's too early.
  452. Dropbox.choose(
  453. {
  454. linkType : 'direct',
  455. cancel: mxUtils.bind(this, function()
  456. {
  457. // do nothing
  458. }),
  459. success : mxUtils.bind(this, function(files)
  460. {
  461. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  462. {
  463. var error = mxUtils.bind(this, function(e)
  464. {
  465. this.ui.spinner.stop();
  466. this.ui.handleError(e);
  467. });
  468. var tmp = files[0].link.indexOf(this.appPath);
  469. if (tmp > 0)
  470. {
  471. // Checks if file is in app folder by loading file from there and comparing relative path and size
  472. // KNOWN: This check fails if a file is inside a drawio directory with same relative path and size
  473. this.execute(mxUtils.bind(this, function()
  474. {
  475. var rel = decodeURIComponent(files[0].link.substring(tmp + this.appPath.length - 1));
  476. this.client.readFile(rel, null, mxUtils.bind(this, function(err, data, stat)
  477. {
  478. if (stat != null && parseInt(files[0].bytes) === parseInt(stat.size) && rel === stat.path)
  479. {
  480. // No need to load file a second time
  481. try
  482. {
  483. this.ui.spinner.stop();
  484. fn(rel.substring(1), new DropboxLibrary(this.ui, data, stat));
  485. }
  486. catch (e)
  487. {
  488. this.ui.handleError(e);
  489. }
  490. }
  491. else
  492. {
  493. this.createLibrary(files[0], fn, error);
  494. }
  495. }));
  496. }));
  497. }
  498. else
  499. {
  500. this.execute(mxUtils.bind(this, function()
  501. {
  502. this.createLibrary(files[0], fn, error);
  503. }));
  504. }
  505. }
  506. })
  507. });
  508. };
  509. /**
  510. * Translates this point by the given vector.
  511. *
  512. * @param {number} dx X-coordinate of the translation.
  513. * @param {number} dy Y-coordinate of the translation.
  514. */
  515. DropboxClient.prototype.createLibrary = function(file, success, error)
  516. {
  517. this.ui.confirm(mxResources.get('note') + ': ' + mxResources.get('fileWillBeSavedInAppFolder', [file.name]), mxUtils.bind(this, function()
  518. {
  519. this.ui.loadUrl(file.link, mxUtils.bind(this, function(data)
  520. {
  521. this.insertFile(file.name, data, mxUtils.bind(this, function(newFile)
  522. {
  523. try
  524. {
  525. this.ui.spinner.stop();
  526. success(newFile.getHash().substring(1), newFile);
  527. }
  528. catch (e)
  529. {
  530. error(e);
  531. }
  532. }), error, true);
  533. }), error);
  534. }), mxUtils.bind(this, function()
  535. {
  536. this.ui.spinner.stop();
  537. }));
  538. };
  539. /**
  540. * Translates this point by the given vector.
  541. *
  542. * @param {number} dx X-coordinate of the translation.
  543. * @param {number} dy Y-coordinate of the translation.
  544. */
  545. DropboxClient.prototype.pickFile = function(fn, readOnly)
  546. {
  547. if (Dropbox.choose != null)
  548. {
  549. fn = (fn != null) ? fn : mxUtils.bind(this, function(path, file)
  550. {
  551. this.ui.loadFile('D' + encodeURIComponent(path), null, file);
  552. });
  553. // Authentication will be carried out on open to make sure the
  554. // autosave does not show an auth dialog. Showing it here will
  555. // block the second dialog (the file picker) so it's too early.
  556. Dropbox.choose(
  557. {
  558. linkType : 'direct',
  559. cancel: mxUtils.bind(this, function()
  560. {
  561. // do nothing
  562. }),
  563. success : mxUtils.bind(this, function(files)
  564. {
  565. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  566. {
  567. // File used for read-only
  568. if (readOnly)
  569. {
  570. this.ui.spinner.stop();
  571. fn(files[0].link);
  572. }
  573. else
  574. {
  575. var error = mxUtils.bind(this, function(e)
  576. {
  577. this.ui.spinner.stop();
  578. this.ui.handleError(e);
  579. });
  580. var success = mxUtils.bind(this, function(path, file)
  581. {
  582. this.ui.spinner.stop();
  583. fn(path, file);
  584. });
  585. var tmp = files[0].link.indexOf(this.appPath);
  586. if (tmp > 0 && !/(\.png)$/i.test(files[0].name) && !/(\.vs?dx)$/i.test(files[0].name) && !/(\.gliffy)$/i.test(files[0].name))
  587. {
  588. // Checks if file is in app folder by loading file from there and comparing relative path and size
  589. // KNOWN: This check fails if a file is inside a drawio directory with same relative path and size
  590. this.execute(mxUtils.bind(this, function()
  591. {
  592. var rel = decodeURIComponent(files[0].link.substring(tmp + this.appPath.length - 1));
  593. this.client.readFile(rel, null, mxUtils.bind(this, function(err, data, stat)
  594. {
  595. if (stat != null && parseInt(files[0].bytes) === parseInt(stat.size) && rel === stat.path)
  596. {
  597. this.ui.spinner.stop();
  598. // No need to load file a second time
  599. fn(rel.substring(1), new DropboxFile(this.ui, data, stat));
  600. }
  601. else
  602. {
  603. this.createFile(files[0], success, error);
  604. }
  605. }));
  606. }));
  607. }
  608. else
  609. {
  610. this.execute(mxUtils.bind(this, function()
  611. {
  612. this.createFile(files[0], success, error);
  613. }));
  614. }
  615. }
  616. }
  617. })
  618. });
  619. }
  620. else
  621. {
  622. this.ui.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
  623. }
  624. };
  625. /**
  626. * Translates this point by the given vector.
  627. *
  628. * @param {number} dx X-coordinate of the translation.
  629. * @param {number} dy Y-coordinate of the translation.
  630. */
  631. DropboxClient.prototype.createFile = function(file, success, error)
  632. {
  633. var name = file.name;
  634. if (/(\.png)$/i.test(name) || /(\.vs?dx)$/i.test(name) || /(\.gliffy)$/i.test(name))
  635. {
  636. name = name.substring(0, name.lastIndexOf('.')) + this.extension;
  637. }
  638. var doInsert = mxUtils.bind(this, function(filename, data)
  639. {
  640. this.ui.confirm(mxResources.get('note') + ': ' + mxResources.get('fileWillBeSavedInAppFolder', [filename]), mxUtils.bind(this, function()
  641. {
  642. this.insertFile(filename, data, mxUtils.bind(this, function(newFile)
  643. {
  644. success(filename, newFile);
  645. }), error);
  646. }), mxUtils.bind(this, function()
  647. {
  648. this.ui.spinner.stop();
  649. }));
  650. });
  651. this.ui.loadUrl(file.link, mxUtils.bind(this, function(data)
  652. {
  653. if (/(\.vs?dx)$/i.test(file.name) || /(\.gliffy)$/i.test(file.name))
  654. {
  655. this.ui.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  656. {
  657. if (xhr.readyState == 4)
  658. {
  659. if (xhr.status == 200 && xhr.responseText.substring(0, 13) == '<mxGraphModel')
  660. {
  661. doInsert(name, xhr.responseText);
  662. }
  663. else
  664. {
  665. this.ui.spinner.stop();
  666. if (error != null)
  667. {
  668. error({message: mxResources.get('errorLoadingFile')});
  669. }
  670. }
  671. }
  672. }), file.name);
  673. }
  674. else
  675. {
  676. if (/(\.png)$/i.test(file.name))
  677. {
  678. data = this.ui.extractGraphModelFromPng(data);
  679. }
  680. if (data != null && data.length > 0)
  681. {
  682. doInsert(name, data);
  683. }
  684. else
  685. {
  686. this.ui.spinner.stop();
  687. if (error != null)
  688. {
  689. error({message: mxResources.get('errorLoadingFile')});
  690. }
  691. }
  692. }
  693. }), error, /(\.png)$/i.test(file.name));
  694. };