OneDriveClient.js 16 KB

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