OneDriveClient.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  283. if ((/\.vsdx$/i.test(meta.name) || /\.gliffy$/i.test(meta.name) || /\.png$/i.test(meta.name)))
  284. {
  285. var mimeType = (meta.file != null) ? meta.file.mimeType : null;
  286. this.ui.convertFile(meta['@microsoft.graph.downloadUrl'], meta.name, mimeType,
  287. this.extension, success, error);
  288. }
  289. else
  290. {
  291. var acceptResponse = true;
  292. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  293. {
  294. acceptResponse = false;
  295. error({code: App.ERROR_TIMEOUT})
  296. }), this.ui.timeout);
  297. this.ui.loadUrl(meta['@microsoft.graph.downloadUrl'], mxUtils.bind(this, function(data)
  298. {
  299. window.clearTimeout(timeoutThread);
  300. if (acceptResponse)
  301. {
  302. if (asLibrary)
  303. {
  304. success(new OneDriveLibrary(this.ui, data, meta));
  305. }
  306. else
  307. {
  308. success(new OneDriveFile(this.ui, data, meta));
  309. }
  310. }
  311. }), mxUtils.bind(this, function(req)
  312. {
  313. window.clearTimeout(timeoutThread);
  314. if (acceptResponse)
  315. {
  316. error(this.parseRequestText(req));
  317. }
  318. }), meta.file != null && meta.file.mimeType != null &&
  319. meta.file.mimeType.substring(0, 6) == 'image/');
  320. }
  321. }
  322. else
  323. {
  324. error(this.parseRequestText(req));
  325. }
  326. }), error);
  327. };
  328. /**
  329. * Translates this point by the given vector.
  330. *
  331. * @param {number} dx X-coordinate of the translation.
  332. * @param {number} dy Y-coordinate of the translation.
  333. */
  334. OneDriveClient.prototype.renameFile = function(file, filename, success, error)
  335. {
  336. if (file != null && filename != null)
  337. {
  338. // TODO: How to force overwrite file with same name?
  339. this.checkExists(file.meta.parentReference.id, filename, false, mxUtils.bind(this, function(checked)
  340. {
  341. if (checked)
  342. {
  343. var url = this.baseUrl + '/me/drive/items/' + file.meta.id;
  344. this.writeFile(url, JSON.stringify({name: filename}), 'PATCH', 'application/json', success, error);
  345. }
  346. else
  347. {
  348. error();
  349. }
  350. }));
  351. }
  352. };
  353. /**
  354. * Translates this point by the given vector.
  355. *
  356. * @param {number} dx X-coordinate of the translation.
  357. * @param {number} dy Y-coordinate of the translation.
  358. */
  359. OneDriveClient.prototype.moveFile = function(id, folderId, success, error)
  360. {
  361. var url = this.baseUrl + '/me/drive/items/' + id;
  362. this.writeFile(url, JSON.stringify({parentReference: {id: folderId}}), 'PATCH', 'application/json', success, error);
  363. };
  364. /**
  365. * Translates this point by the given vector.
  366. *
  367. * @param {number} dx X-coordinate of the translation.
  368. * @param {number} dy Y-coordinate of the translation.
  369. */
  370. OneDriveClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  371. {
  372. this.insertFile(filename, data, success, error, true, folderId);
  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.insertFile = function(filename, data, success, error, asLibrary, folderId)
  381. {
  382. asLibrary = (asLibrary != null) ? asLibrary : false;
  383. this.checkExists(folderId, filename, true, mxUtils.bind(this, function(checked)
  384. {
  385. if (checked)
  386. {
  387. var folder = (folderId != null) ? '/me/drive/items/' + folderId : '/me/drive/root';
  388. var url = this.baseUrl + folder + '/children/' + filename + '/content';
  389. this.writeFile(url, data, 'PUT', null, mxUtils.bind(this, function(meta)
  390. {
  391. if (asLibrary)
  392. {
  393. success(new OneDriveLibrary(this.ui, data, meta));
  394. }
  395. else
  396. {
  397. success(new OneDriveFile(this.ui, data, meta));
  398. }
  399. }), error);
  400. }
  401. else
  402. {
  403. error();
  404. }
  405. }))
  406. };
  407. /**
  408. * Translates this point by the given vector.
  409. *
  410. * @param {number} dx X-coordinate of the translation.
  411. * @param {number} dy Y-coordinate of the translation.
  412. */
  413. OneDriveClient.prototype.checkExists = function(parentId, filename, askReplace, fn)
  414. {
  415. var folder = (parentId != null) ? '/me/drive/items/' + parentId : '/me/drive/root';
  416. this.executeRequest(this.baseUrl + folder + '/children/' + filename, mxUtils.bind(this, function(req)
  417. {
  418. if (req.getStatus() == 404)
  419. {
  420. fn(true);
  421. }
  422. else
  423. {
  424. if (askReplace)
  425. {
  426. this.ui.spinner.stop();
  427. this.ui.confirm(mxResources.get('replaceIt', [filename]), function()
  428. {
  429. fn(true);
  430. }, function()
  431. {
  432. fn(false);
  433. });
  434. }
  435. else
  436. {
  437. this.ui.spinner.stop();
  438. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  439. {
  440. fn(false);
  441. });
  442. }
  443. }
  444. }), function(req)
  445. {
  446. fn(false);
  447. }, true);
  448. };
  449. /**
  450. * Translates this point by the given vector.
  451. *
  452. * @param {number} dx X-coordinate of the translation.
  453. * @param {number} dy Y-coordinate of the translation.
  454. */
  455. OneDriveClient.prototype.saveFile = function(file, success, error)
  456. {
  457. var url = this.baseUrl + '/me/drive/items/' + file.meta.id + '/content/';
  458. this.writeFile(url, file.getData(), 'PUT', null, success, error);
  459. };
  460. /**
  461. * Translates this point by the given vector.
  462. *
  463. * @param {number} dx X-coordinate of the translation.
  464. * @param {number} dy Y-coordinate of the translation.
  465. */
  466. OneDriveClient.prototype.writeFile = function(url, data, method, contentType, success, error)
  467. {
  468. if (url != null && data != null)
  469. {
  470. var doExecute = mxUtils.bind(this, function(failOnAuth)
  471. {
  472. var acceptResponse = true;
  473. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  474. {
  475. acceptResponse = false;
  476. error({code: App.ERROR_TIMEOUT, retry: fn});
  477. }), this.ui.timeout);
  478. var req = new mxXmlRequest(url, data, method);
  479. req.setRequestHeaders = mxUtils.bind(this, function(request, params)
  480. {
  481. // Space deletes content type header. Specification says "text/plain"
  482. // should work but returns an 415 Unsupported Media Type error
  483. request.setRequestHeader('Content-Type', contentType || ' ');
  484. request.setRequestHeader('Authorization', 'Bearer ' + this.token);
  485. });
  486. req.send(mxUtils.bind(this, function(req)
  487. {
  488. window.clearTimeout(timeoutThread);
  489. if (acceptResponse)
  490. {
  491. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  492. {
  493. success(JSON.parse(req.getText()));
  494. }
  495. else if (req.getStatus() === 401)
  496. {
  497. this.clearPersistentToken();
  498. this.setUser(null);
  499. this.token = null;
  500. if (!failOnAuth)
  501. {
  502. this.authenticate(function()
  503. {
  504. doExecute(true);
  505. }, error);
  506. }
  507. else
  508. {
  509. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  510. {
  511. this.authenticate(function()
  512. {
  513. fn(true);
  514. }, error);
  515. })});
  516. }
  517. }
  518. else
  519. {
  520. error(this.parseRequestText(req));
  521. }
  522. }
  523. }), mxUtils.bind(this, function(req)
  524. {
  525. window.clearTimeout(timeoutThread);
  526. if (acceptResponse)
  527. {
  528. error(this.parseRequestText(req));
  529. }
  530. }));
  531. });
  532. var fn = mxUtils.bind(this, function(failOnAuth)
  533. {
  534. if (this.user == null)
  535. {
  536. this.updateUser(function()
  537. {
  538. fn(true);
  539. }, error, failOnAuth);
  540. }
  541. else
  542. {
  543. doExecute(failOnAuth);
  544. }
  545. });
  546. if (this.token == null)
  547. {
  548. this.authenticate(function()
  549. {
  550. fn(true);
  551. }, error);
  552. }
  553. else
  554. {
  555. fn(false);
  556. }
  557. }
  558. else
  559. {
  560. error({message: mxResources.get('unknownError')});
  561. }
  562. };
  563. /**
  564. * Checks if the client is authorized and calls the next step.
  565. */
  566. OneDriveClient.prototype.parseRequestText = function(req)
  567. {
  568. var result = {message: mxResources.get('unknownError')};
  569. try
  570. {
  571. result = JSON.parse(req.getText());
  572. }
  573. catch (e)
  574. {
  575. // ignore
  576. }
  577. return result;
  578. };
  579. /**
  580. * Checks if the client is authorized and calls the next step.
  581. */
  582. OneDriveClient.prototype.pickLibrary = function(fn)
  583. {
  584. this.pickFile(fn);
  585. };
  586. /**
  587. * Checks if the client is authorized and calls the next step.
  588. */
  589. OneDriveClient.prototype.pickFolder = function(fn)
  590. {
  591. OneDrive.save(
  592. {
  593. clientId: this.clientId,
  594. action: 'query',
  595. openInNewWindow: true,
  596. advanced:
  597. {
  598. 'redirectUri': this.redirectUri
  599. },
  600. success: mxUtils.bind(this, function(files)
  601. {
  602. // KNOWN: Token should be per I/O operation
  603. this.token = files.accessToken;
  604. fn(files);
  605. }),
  606. cancel: function()
  607. {
  608. // do nothing
  609. },
  610. error: mxUtils.bind(this, function(e)
  611. {
  612. this.ui.showError(mxResources.get('error'), e);
  613. })
  614. });
  615. };
  616. /**
  617. * Checks if the client is authorized and calls the next step.
  618. */
  619. OneDriveClient.prototype.pickFile = function(fn, returnObject)
  620. {
  621. fn = (fn != null) ? fn : mxUtils.bind(this, function(id)
  622. {
  623. this.ui.loadFile('W' + encodeURIComponent(id));
  624. });
  625. OneDrive.open(
  626. {
  627. clientId: this.clientId,
  628. action: 'query',
  629. multiSelect: false,
  630. advanced:
  631. {
  632. 'redirectUri': this.redirectUri
  633. },
  634. success: mxUtils.bind(this, function(files)
  635. {
  636. if (files != null && files.value != null && files.value.length > 0)
  637. {
  638. // KNOWN: Token should be per I/O operation
  639. this.token = files.accessToken;
  640. fn((returnObject) ? files : files.value[0].id);
  641. }
  642. }),
  643. cancel: function()
  644. {
  645. // do nothing
  646. },
  647. error: mxUtils.bind(this, function(e)
  648. {
  649. this.ui.showError(mxResources.get('error'), e);
  650. })
  651. });
  652. };
  653. /**
  654. * Checks if the client is authorized and calls the next step.
  655. */
  656. OneDriveClient.prototype.logout = function()
  657. {
  658. if (isLocalStorage)
  659. {
  660. var check = localStorage.getItem('odpickerv7cache');
  661. if (check != null && check.substring(0, 19) == '{"odsdkLoginHint":{')
  662. {
  663. localStorage.removeItem('odpickerv7cache');
  664. }
  665. }
  666. this.clearPersistentToken();
  667. this.setUser(null);
  668. this.token = null;
  669. };