OneDriveClient.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. OneDriveClient = function(editorUi)
  6. {
  7. DrawioClient.call(this, editorUi, 'odauth');
  8. this.token = this.token;
  9. };
  10. // Extends DrawioClient
  11. mxUtils.extend(OneDriveClient, DrawioClient);
  12. /**
  13. * Specifies if thumbnails should be enabled. Default is true.
  14. * LATER: If thumbnails are disabled, make sure to replace the
  15. * existing thumbnail with the placeholder only once.
  16. */
  17. OneDriveClient.prototype.clientId = (window.location.hostname == 'test.draw.io') ?
  18. '2e598409-107f-4b59-89ca-d7723c8e00a4' : '45c10911-200f-4e27-a666-9e9fca147395';
  19. /**
  20. * OAuth 2.0 scopes for installing Drive Apps.
  21. */
  22. OneDriveClient.prototype.scopes = 'user.read';
  23. /**
  24. * OAuth 2.0 scopes for installing Drive Apps.
  25. */
  26. OneDriveClient.prototype.redirectUri = 'https://' + window.location.hostname + '/onedrive3.html';
  27. /**
  28. * Executes the first step for connecting to Google Drive.
  29. */
  30. OneDriveClient.prototype.extension = '.html';
  31. /**
  32. * Executes the first step for connecting to Google Drive.
  33. */
  34. OneDriveClient.prototype.baseUrl = 'https://graph.microsoft.com/v1.0';
  35. /**
  36. * Checks if the client is authorized and calls the next step.
  37. */
  38. OneDriveClient.prototype.get = function(url, onload, onerror)
  39. {
  40. var req = new mxXmlRequest(url, null, 'GET');
  41. req.setRequestHeaders = mxUtils.bind(this, function(request, params)
  42. {
  43. request.setRequestHeader('Authorization', 'Bearer ' + this.token);
  44. });
  45. req.send(onload, onerror);
  46. return req;
  47. };
  48. /**
  49. * Checks if the client is authorized and calls the next step.
  50. */
  51. OneDriveClient.prototype.updateUser = function(success, error, failOnAuth)
  52. {
  53. var acceptResponse = true;
  54. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  55. {
  56. acceptResponse = false;
  57. error({code: App.ERROR_TIMEOUT});
  58. }), this.ui.timeout);
  59. this.get(this.baseUrl + '/me', mxUtils.bind(this, function(req)
  60. {
  61. window.clearTimeout(timeoutThread);
  62. if (acceptResponse)
  63. {
  64. if (req.getStatus() < 200 || req.getStatus() >= 300)
  65. {
  66. if (!failOnAuth)
  67. {
  68. this.logout();
  69. this.authenticate(mxUtils.bind(this, function()
  70. {
  71. this.updateUser(success, error, true);
  72. }), error);
  73. }
  74. else
  75. {
  76. error({message: mxResources.get('accessDenied')});
  77. }
  78. }
  79. else
  80. {
  81. var data = JSON.parse(req.getText());
  82. this.setUser(new DrawioUser(data.id, null, data.displayName));
  83. success();
  84. }
  85. }
  86. }), error);
  87. };
  88. /**
  89. * Authorizes the client, gets the userId and calls <open>.
  90. */
  91. OneDriveClient.prototype.authenticate = function(success, error)
  92. {
  93. if (window.onOneDriveCallback == null)
  94. {
  95. var auth = mxUtils.bind(this, function()
  96. {
  97. var acceptAuthResponse = true;
  98. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
  99. {
  100. var url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' +
  101. '?client_id=' + this.clientId + '&response_type=token' +
  102. '&redirect_uri=' + encodeURIComponent(this.redirectUri) +
  103. '&scope=' + encodeURIComponent(this.scopes) +
  104. '&response_mode=fragment';
  105. var width = 525,
  106. height = 525,
  107. screenX = window.screenX,
  108. screenY = window.screenY,
  109. outerWidth = window.outerWidth,
  110. outerHeight = window.outerHeight;
  111. var left = screenX + Math.max(outerWidth - width, 0) / 2;
  112. var top = screenY + Math.max(outerHeight - height, 0) / 2;
  113. var features = ['width=' + width, 'height=' + height,
  114. 'top=' + top, 'left=' + left,
  115. 'status=no', 'resizable=yes',
  116. 'toolbar=no', 'menubar=no',
  117. 'scrollbars=yes'];
  118. var popup = window.open(url, 'odauth', features.join(','));
  119. if (popup != null)
  120. {
  121. window.onOneDriveCallback = mxUtils.bind(this, function(token, authWindow)
  122. {
  123. if (acceptAuthResponse)
  124. {
  125. window.onOneDriveCallback = null;
  126. acceptAuthResponse = false;
  127. try
  128. {
  129. if (token == null)
  130. {
  131. error({message: mxResources.get('accessDenied'), retry: auth});
  132. }
  133. else
  134. {
  135. if (authSuccess != null)
  136. {
  137. authSuccess();
  138. }
  139. this.setUser(null);
  140. this.token = token;
  141. if (remember)
  142. {
  143. this.setPersistentToken(token);
  144. }
  145. success();
  146. }
  147. }
  148. catch (e)
  149. {
  150. error(e);
  151. }
  152. finally
  153. {
  154. if (authWindow != null)
  155. {
  156. authWindow.close();
  157. }
  158. }
  159. }
  160. else if (authWindow != null)
  161. {
  162. authWindow.close();
  163. }
  164. });
  165. popup.focus();
  166. }
  167. }), mxUtils.bind(this, function()
  168. {
  169. if (acceptAuthResponse)
  170. {
  171. window.onOneDriveCallback = null;
  172. acceptAuthResponse = false;
  173. error({message: mxResources.get('accessDenied'), retry: auth});
  174. }
  175. }));
  176. });
  177. auth();
  178. }
  179. else
  180. {
  181. error({code: App.ERROR_BUSY});
  182. }
  183. };
  184. /**
  185. * Checks if the client is authorized and calls the next step.
  186. */
  187. OneDriveClient.prototype.executeRequest = function(url, success, error)
  188. {
  189. var doExecute = mxUtils.bind(this, function(failOnAuth)
  190. {
  191. var acceptResponse = true;
  192. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  193. {
  194. acceptResponse = false;
  195. error({code: App.ERROR_TIMEOUT, retry: fn});
  196. }), this.ui.timeout);
  197. this.get(url, mxUtils.bind(this, function(req)
  198. {
  199. window.clearTimeout(timeoutThread);
  200. if (acceptResponse)
  201. {
  202. // 404 (file not found) is a valid response for checkExists
  203. if ((req.getStatus() >= 200 && req.getStatus() <= 299) || req.getStatus() == 404)
  204. {
  205. success(req);
  206. }
  207. // 400 is returns if wrong user for this file
  208. else if (req.getStatus() === 401 || req.getStatus() === 400)
  209. {
  210. this.clearPersistentToken();
  211. this.setUser(null);
  212. this.token = null;
  213. if (!failOnAuth)
  214. {
  215. this.authenticate(function()
  216. {
  217. doExecute(true);
  218. }, error);
  219. }
  220. else
  221. {
  222. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  223. {
  224. this.authenticate(function()
  225. {
  226. fn(true);
  227. }, error);
  228. })});
  229. }
  230. }
  231. else
  232. {
  233. error(this.parseRequestText(req));
  234. }
  235. }
  236. }), error);
  237. });
  238. var fn = mxUtils.bind(this, function(failOnAuth)
  239. {
  240. if (this.user == null)
  241. {
  242. this.updateUser(function()
  243. {
  244. fn(true);
  245. }, error, failOnAuth);
  246. }
  247. else
  248. {
  249. doExecute(failOnAuth);
  250. }
  251. });
  252. if (this.token == null)
  253. {
  254. this.authenticate(function()
  255. {
  256. fn(true);
  257. }, error);
  258. }
  259. else
  260. {
  261. fn(false);
  262. }
  263. };
  264. /**
  265. * Checks if the client is authorized and calls the next step.
  266. */
  267. OneDriveClient.prototype.getLibrary = function(id, success, error)
  268. {
  269. this.getFile(id, success, error, false, true);
  270. };
  271. /**
  272. * Checks if the client is authorized and calls the next step.
  273. */
  274. OneDriveClient.prototype.getFile = function(id, success, error, denyConvert, asLibrary)
  275. {
  276. asLibrary = (asLibrary != null) ? asLibrary : false;
  277. this.executeRequest(this.baseUrl + '/me/drive/items/' + id, mxUtils.bind(this, function(req)
  278. {
  279. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  280. {
  281. var meta = JSON.parse(req.getText());
  282. var binary = /\.png$/i.test(meta.name);
  283. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  284. if (/\.vsdx$/i.test(meta.name) || /\.gliffy$/i.test(meta.name) ||
  285. (!this.ui.useCanvasForExport && binary))
  286. {
  287. var mimeType = (meta.file != null) ? meta.file.mimeType : null;
  288. this.ui.convertFile(meta['@microsoft.graph.downloadUrl'], meta.name, mimeType,
  289. this.extension, success, error);
  290. }
  291. else
  292. {
  293. var acceptResponse = true;
  294. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  295. {
  296. acceptResponse = false;
  297. error({code: App.ERROR_TIMEOUT})
  298. }), this.ui.timeout);
  299. this.ui.loadUrl(meta['@microsoft.graph.downloadUrl'], mxUtils.bind(this, function(data)
  300. {
  301. window.clearTimeout(timeoutThread);
  302. if (acceptResponse)
  303. {
  304. var index = (binary) ? data.lastIndexOf(',') : -1;
  305. var file = null;
  306. if (index > 0)
  307. {
  308. var xml = this.ui.extractGraphModelFromPng(data.substring(index + 1));
  309. if (xml != null && xml.length > 0)
  310. {
  311. data = xml;
  312. }
  313. else
  314. {
  315. // Imports as PNG image
  316. file = new LocalFile(this.ui, data, meta.name, true);
  317. }
  318. }
  319. if (file != null)
  320. {
  321. success(file);
  322. }
  323. else if (asLibrary)
  324. {
  325. success(new OneDriveLibrary(this.ui, data, meta));
  326. }
  327. else
  328. {
  329. success(new OneDriveFile(this.ui, data, meta));
  330. }
  331. }
  332. }), mxUtils.bind(this, function(req)
  333. {
  334. window.clearTimeout(timeoutThread);
  335. if (acceptResponse)
  336. {
  337. error(this.parseRequestText(req));
  338. }
  339. }), binary || (meta.file != null && meta.file.mimeType != null &&
  340. meta.file.mimeType.substring(0, 6) == 'image/'));
  341. }
  342. }
  343. else
  344. {
  345. error(this.parseRequestText(req));
  346. }
  347. }), error);
  348. };
  349. /**
  350. * Translates this point by the given vector.
  351. *
  352. * @param {number} dx X-coordinate of the translation.
  353. * @param {number} dy Y-coordinate of the translation.
  354. */
  355. OneDriveClient.prototype.renameFile = function(file, filename, success, error)
  356. {
  357. if (file != null && filename != null)
  358. {
  359. // TODO: How to force overwrite file with same name?
  360. this.checkExists(file.meta.parentReference.id, filename, false, mxUtils.bind(this, function(checked)
  361. {
  362. if (checked)
  363. {
  364. var url = this.baseUrl + '/me/drive/items/' + file.meta.id;
  365. this.writeFile(url, JSON.stringify({name: filename}), 'PATCH', 'application/json', success, error);
  366. }
  367. else
  368. {
  369. error();
  370. }
  371. }));
  372. }
  373. };
  374. /**
  375. * Translates this point by the given vector.
  376. *
  377. * @param {number} dx X-coordinate of the translation.
  378. * @param {number} dy Y-coordinate of the translation.
  379. */
  380. OneDriveClient.prototype.moveFile = function(id, folderId, success, error)
  381. {
  382. var url = this.baseUrl + '/me/drive/items/' + id;
  383. this.writeFile(url, JSON.stringify({parentReference: {id: folderId}}), 'PATCH', 'application/json', success, error);
  384. };
  385. /**
  386. * Translates this point by the given vector.
  387. *
  388. * @param {number} dx X-coordinate of the translation.
  389. * @param {number} dy Y-coordinate of the translation.
  390. */
  391. OneDriveClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  392. {
  393. this.insertFile(filename, data, success, error, true, folderId);
  394. };
  395. /**
  396. * Translates this point by the given vector.
  397. *
  398. * @param {number} dx X-coordinate of the translation.
  399. * @param {number} dy Y-coordinate of the translation.
  400. */
  401. OneDriveClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId)
  402. {
  403. asLibrary = (asLibrary != null) ? asLibrary : false;
  404. this.checkExists(folderId, filename, true, mxUtils.bind(this, function(checked)
  405. {
  406. if (checked)
  407. {
  408. var folder = (folderId != null) ? '/me/drive/items/' + folderId : '/me/drive/root';
  409. var url = this.baseUrl + folder + '/children/' + filename + '/content';
  410. this.writeFile(url, data, 'PUT', null, mxUtils.bind(this, function(meta)
  411. {
  412. if (asLibrary)
  413. {
  414. success(new OneDriveLibrary(this.ui, data, meta));
  415. }
  416. else
  417. {
  418. success(new OneDriveFile(this.ui, data, meta));
  419. }
  420. }), error);
  421. }
  422. else
  423. {
  424. error();
  425. }
  426. }))
  427. };
  428. /**
  429. * Translates this point by the given vector.
  430. *
  431. * @param {number} dx X-coordinate of the translation.
  432. * @param {number} dy Y-coordinate of the translation.
  433. */
  434. OneDriveClient.prototype.checkExists = function(parentId, filename, askReplace, fn)
  435. {
  436. var folder = (parentId != null) ? '/me/drive/items/' + parentId : '/me/drive/root';
  437. this.executeRequest(this.baseUrl + folder + '/children/' + filename, mxUtils.bind(this, function(req)
  438. {
  439. if (req.getStatus() == 404)
  440. {
  441. fn(true);
  442. }
  443. else
  444. {
  445. if (askReplace)
  446. {
  447. this.ui.spinner.stop();
  448. this.ui.confirm(mxResources.get('replaceIt', [filename]), function()
  449. {
  450. fn(true);
  451. }, function()
  452. {
  453. fn(false);
  454. });
  455. }
  456. else
  457. {
  458. this.ui.spinner.stop();
  459. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  460. {
  461. fn(false);
  462. });
  463. }
  464. }
  465. }), function(req)
  466. {
  467. fn(false);
  468. }, true);
  469. };
  470. /**
  471. * Translates this point by the given vector.
  472. *
  473. * @param {number} dx X-coordinate of the translation.
  474. * @param {number} dy Y-coordinate of the translation.
  475. */
  476. OneDriveClient.prototype.saveFile = function(file, success, error)
  477. {
  478. var fn = mxUtils.bind(this, function(data)
  479. {
  480. var url = this.baseUrl + '/me/drive/items/' + file.meta.id + '/content/';
  481. this.writeFile(url, data, 'PUT', null, success, error);
  482. });
  483. if (this.ui.useCanvasForExport && /(\.png)$/i.test(file.meta.name))
  484. {
  485. this.ui.getEmbeddedPng(mxUtils.bind(this, function(data)
  486. {
  487. fn(this.ui.base64ToBlob(data, 'image/png'));
  488. }), error, (this.ui.getCurrentFile() != file) ? file.getData() : null);
  489. }
  490. else
  491. {
  492. fn(file.getData());
  493. }
  494. };
  495. /**
  496. * Translates this point by the given vector.
  497. *
  498. * @param {number} dx X-coordinate of the translation.
  499. * @param {number} dy Y-coordinate of the translation.
  500. */
  501. OneDriveClient.prototype.writeFile = function(url, data, method, contentType, success, error)
  502. {
  503. if (url != null && data != null)
  504. {
  505. var doExecute = mxUtils.bind(this, function(failOnAuth)
  506. {
  507. var acceptResponse = true;
  508. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  509. {
  510. acceptResponse = false;
  511. error({code: App.ERROR_TIMEOUT, retry: fn});
  512. }), this.ui.timeout);
  513. var req = new mxXmlRequest(url, data, method);
  514. req.setRequestHeaders = mxUtils.bind(this, function(request, params)
  515. {
  516. // Space deletes content type header. Specification says "text/plain"
  517. // should work but returns an 415 Unsupported Media Type error
  518. request.setRequestHeader('Content-Type', contentType || ' ');
  519. request.setRequestHeader('Authorization', 'Bearer ' + this.token);
  520. });
  521. req.send(mxUtils.bind(this, function(req)
  522. {
  523. window.clearTimeout(timeoutThread);
  524. if (acceptResponse)
  525. {
  526. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  527. {
  528. success(JSON.parse(req.getText()));
  529. }
  530. else if (req.getStatus() === 401)
  531. {
  532. this.clearPersistentToken();
  533. this.setUser(null);
  534. this.token = null;
  535. if (!failOnAuth)
  536. {
  537. this.authenticate(function()
  538. {
  539. doExecute(true);
  540. }, error);
  541. }
  542. else
  543. {
  544. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  545. {
  546. this.authenticate(function()
  547. {
  548. fn(true);
  549. }, error);
  550. })});
  551. }
  552. }
  553. else
  554. {
  555. error(this.parseRequestText(req));
  556. }
  557. }
  558. }), mxUtils.bind(this, function(req)
  559. {
  560. window.clearTimeout(timeoutThread);
  561. if (acceptResponse)
  562. {
  563. error(this.parseRequestText(req));
  564. }
  565. }));
  566. });
  567. var fn = mxUtils.bind(this, function(failOnAuth)
  568. {
  569. if (this.user == null)
  570. {
  571. this.updateUser(function()
  572. {
  573. fn(true);
  574. }, error, failOnAuth);
  575. }
  576. else
  577. {
  578. doExecute(failOnAuth);
  579. }
  580. });
  581. if (this.token == null)
  582. {
  583. this.authenticate(function()
  584. {
  585. fn(true);
  586. }, error);
  587. }
  588. else
  589. {
  590. fn(false);
  591. }
  592. }
  593. else
  594. {
  595. error({message: mxResources.get('unknownError')});
  596. }
  597. };
  598. /**
  599. * Checks if the client is authorized and calls the next step.
  600. */
  601. OneDriveClient.prototype.parseRequestText = function(req)
  602. {
  603. var result = {message: mxResources.get('unknownError')};
  604. try
  605. {
  606. result = JSON.parse(req.getText());
  607. }
  608. catch (e)
  609. {
  610. // ignore
  611. }
  612. return result;
  613. };
  614. /**
  615. * Checks if the client is authorized and calls the next step.
  616. */
  617. OneDriveClient.prototype.pickLibrary = function(fn)
  618. {
  619. this.pickFile(fn);
  620. };
  621. /**
  622. * Checks if the client is authorized and calls the next step.
  623. */
  624. OneDriveClient.prototype.pickFolder = function(fn)
  625. {
  626. OneDrive.save(
  627. {
  628. clientId: this.clientId,
  629. action: 'query',
  630. openInNewWindow: true,
  631. advanced:
  632. {
  633. 'redirectUri': this.redirectUri
  634. },
  635. success: mxUtils.bind(this, function(files)
  636. {
  637. // KNOWN: Token should be per I/O operation
  638. this.token = files.accessToken;
  639. fn(files);
  640. }),
  641. cancel: function()
  642. {
  643. // do nothing
  644. },
  645. error: mxUtils.bind(this, function(e)
  646. {
  647. this.ui.showError(mxResources.get('error'), e);
  648. })
  649. });
  650. };
  651. /**
  652. * Checks if the client is authorized and calls the next step.
  653. */
  654. OneDriveClient.prototype.pickFile = function(fn)
  655. {
  656. fn = (fn != null) ? fn : mxUtils.bind(this, function(id)
  657. {
  658. this.ui.loadFile('W' + encodeURIComponent(id));
  659. });
  660. OneDrive.open(
  661. {
  662. clientId: this.clientId,
  663. action: 'query',
  664. multiSelect: false,
  665. advanced:
  666. {
  667. 'redirectUri': this.redirectUri
  668. },
  669. success: mxUtils.bind(this, function(files)
  670. {
  671. if (files != null && files.value != null && files.value.length > 0)
  672. {
  673. // KNOWN: Token should be per I/O operation
  674. this.token = files.accessToken;
  675. fn(files.value[0].id, files);
  676. }
  677. }),
  678. cancel: function()
  679. {
  680. // do nothing
  681. },
  682. error: mxUtils.bind(this, function(e)
  683. {
  684. this.ui.showError(mxResources.get('error'), e);
  685. })
  686. });
  687. };
  688. /**
  689. * Checks if the client is authorized and calls the next step.
  690. */
  691. OneDriveClient.prototype.logout = function()
  692. {
  693. if (isLocalStorage)
  694. {
  695. var check = localStorage.getItem('odpickerv7cache');
  696. if (check != null && check.substring(0, 19) == '{"odsdkLoginHint":{')
  697. {
  698. localStorage.removeItem('odpickerv7cache');
  699. }
  700. }
  701. this.clearPersistentToken();
  702. this.setUser(null);
  703. this.token = null;
  704. };