OneDriveClient.js 17 KB

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