OneDriveClient.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. if (!denyConvert && Graph.fileSupport && new XMLHttpRequest().upload &&
  239. (/(\.png)$/i.test(meta.name) || /(\.vs?dx)$/i.test(meta.name) ||
  240. /(\.gliffy)$/i.test(meta.name)))
  241. {
  242. this.convertFile(meta, success, error);
  243. }
  244. else
  245. {
  246. this.ui.loadUrl(meta['@content.downloadUrl'], mxUtils.bind(this, function(data)
  247. {
  248. if (asLibrary)
  249. {
  250. success(new OneDriveLibrary(this.ui, data, meta));
  251. }
  252. else
  253. {
  254. success(new OneDriveFile(this.ui, data, meta));
  255. }
  256. }), err, meta != null && meta.file != null && meta.file.mimeType != null &&
  257. meta.file.mimeType.substring(0, 6) == 'image/');
  258. }
  259. }
  260. else if (error != null)
  261. {
  262. error(this.parseRequestText(req));
  263. }
  264. }
  265. }), err);
  266. }
  267. else
  268. {
  269. error();
  270. }
  271. }));
  272. });
  273. fn();
  274. };
  275. /**
  276. * Checks if the client is authorized and calls the next step. The optional
  277. * readXml argument is used for import. Default is false. The optional
  278. * readLibrary argument is used for reading libraries. Default is false.
  279. */
  280. OneDriveClient.prototype.convertFile = function(meta, success, error)
  281. {
  282. var name = meta.name;
  283. name = name.substring(0, name.lastIndexOf('.')) + this.extension;
  284. // Gets file data
  285. var url = meta['@content.downloadUrl'];
  286. this.ui.loadUrl(url, mxUtils.bind(this, function(data)
  287. {
  288. // Handles PNG+XML files
  289. if (meta.file.mimeType == 'image/png')
  290. {
  291. data = this.ui.extractGraphModelFromPng(data);
  292. if (data != null)
  293. {
  294. this.insertFile(name, data, success, error);
  295. }
  296. else if (error != null)
  297. {
  298. error({message: mxResources.get('errorLoadingFile')});
  299. }
  300. }
  301. else
  302. {
  303. this.ui.parseFile(new Blob([data], {type: 'application/octet-stream'}), mxUtils.bind(this, function(xhr)
  304. {
  305. if (xhr.readyState == 4)
  306. {
  307. if (xhr.status >= 200 && xhr.status <= 299 && xhr.responseText.substring(0, 13) == '<mxGraphModel')
  308. {
  309. this.insertFile(name, xhr.responseText, success, error);
  310. }
  311. else if (error != null)
  312. {
  313. error({message: mxResources.get('errorLoadingFile')});
  314. }
  315. }
  316. }), meta.name);
  317. }
  318. }), error, meta.file.mimeType == 'image/png');
  319. };
  320. /**
  321. * Translates this point by the given vector.
  322. *
  323. * @param {number} dx X-coordinate of the translation.
  324. * @param {number} dy Y-coordinate of the translation.
  325. */
  326. OneDriveClient.prototype.renameFile = function(file, filename, success, error)
  327. {
  328. if (file != null && filename != null)
  329. {
  330. // TODO: How to force overwrite file with same name?
  331. this.checkExists(file.meta.parentReference.id, filename, false, mxUtils.bind(this, function(checked, token)
  332. {
  333. if (checked)
  334. {
  335. var url = this.baseUrl + '/drive/items/' + file.meta.id + '?access_token=' + token;
  336. this.writeFile(url, JSON.stringify({name: filename}), 'PATCH', 'application/json', success, error);
  337. }
  338. else
  339. {
  340. error();
  341. }
  342. }));
  343. }
  344. };
  345. /**
  346. * Translates this point by the given vector.
  347. *
  348. * @param {number} dx X-coordinate of the translation.
  349. * @param {number} dy Y-coordinate of the translation.
  350. */
  351. OneDriveClient.prototype.moveFile = function(id, folderId, success, error)
  352. {
  353. this.execute(mxUtils.bind(this, function(token)
  354. {
  355. var url = this.baseUrl + '/drive/items/' + id + '?access_token=' + token;
  356. this.writeFile(url, JSON.stringify({parentReference: {id: folderId}}), 'PATCH', 'application/json', success, error);
  357. }));
  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, token)
  379. {
  380. if (checked)
  381. {
  382. var folder = (folderId != null) ? 'items/' + folderId : 'special/documents';
  383. var url = this.baseUrl + '/drive/' + folder + '/children/' + filename + '/content?access_token=' + token;
  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 if (error != null)
  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. this.execute(mxUtils.bind(this, function(token)
  411. {
  412. var path = (parentId != null) ? 'items/' + parentId : 'special/documents';
  413. mxUtils.get(this.baseUrl + '/drive/' + path + '/children/' + filename + '?access_token=' + token, mxUtils.bind(this, function(req)
  414. {
  415. if (req.getStatus() == 404)
  416. {
  417. fn(true, token);
  418. }
  419. else
  420. {
  421. if (askReplace)
  422. {
  423. this.ui.spinner.stop();
  424. this.ui.confirm(mxResources.get('replaceIt', [filename]), function()
  425. {
  426. fn(true, token);
  427. }, function()
  428. {
  429. fn(false, token);
  430. });
  431. }
  432. else
  433. {
  434. this.ui.spinner.stop();
  435. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  436. {
  437. fn(false, token);
  438. });
  439. }
  440. }
  441. }), function(req)
  442. {
  443. fn(false, token);
  444. });
  445. }));
  446. };
  447. /**
  448. * Translates this point by the given vector.
  449. *
  450. * @param {number} dx X-coordinate of the translation.
  451. * @param {number} dy Y-coordinate of the translation.
  452. */
  453. OneDriveClient.prototype.saveFile = function(file, success, error)
  454. {
  455. this.execute(mxUtils.bind(this, function(token)
  456. {
  457. var url = this.baseUrl + '/drive/items/' + file.meta.id + '/content/?access_token=' + token;
  458. this.writeFile(url, file.getData(), 'PUT', null, success, error);
  459. }));
  460. };
  461. /**
  462. * Translates this point by the given vector.
  463. *
  464. * @param {number} dx X-coordinate of the translation.
  465. * @param {number} dy Y-coordinate of the translation.
  466. */
  467. OneDriveClient.prototype.writeFile = function(url, data, method, contentType, success, error)
  468. {
  469. if (!this.writingFile)
  470. {
  471. if (url != null && data != null)
  472. {
  473. var acceptResponse = true;
  474. var timeoutThread = null;
  475. this.writingFile = true;
  476. // Cancels any pending requests
  477. if (this.requestThread != null)
  478. {
  479. window.clearTimeout(this.requestThread);
  480. }
  481. var fn = mxUtils.bind(this, function()
  482. {
  483. if (timeoutThread != null)
  484. {
  485. window.clearTimeout(timeoutThread);
  486. }
  487. timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  488. {
  489. this.writingFile = false;
  490. acceptResponse = false;
  491. if (error != null)
  492. {
  493. error({code: App.ERROR_TIMEOUT, retry: fn});
  494. }
  495. }), this.ui.timeout);
  496. var req = new mxXmlRequest(url, data, method);
  497. req.setRequestHeaders = function(request, params)
  498. {
  499. // Space deletes content type header. Specification says "text/plain"
  500. // should work but returns an 415 Unsupported Media Type error
  501. request.setRequestHeader('Content-Type', contentType || ' ');
  502. };
  503. req.send(mxUtils.bind(this, function(req)
  504. {
  505. window.clearTimeout(timeoutThread);
  506. if (acceptResponse)
  507. {
  508. this.writingFile = false;
  509. // Returns 201 (created) for new resources
  510. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  511. {
  512. if (success != null)
  513. {
  514. success(JSON.parse(req.getText()));
  515. }
  516. }
  517. else if (error != null)
  518. {
  519. error(this.parseRequestText(req));
  520. }
  521. }
  522. }), mxUtils.bind(this, function(req)
  523. {
  524. window.clearTimeout(timeoutThread);
  525. if (acceptResponse)
  526. {
  527. this.writingFile = false;
  528. if (error != null)
  529. {
  530. error(this.parseRequestText(req));
  531. }
  532. }
  533. }));
  534. });
  535. fn();
  536. }
  537. else if (error != null)
  538. {
  539. error();
  540. }
  541. }
  542. else if (error != null)
  543. {
  544. error({code: App.ERROR_BUSY});
  545. }
  546. };
  547. /**
  548. * Checks if the client is authorized and calls the next step.
  549. */
  550. OneDriveClient.prototype.parseRequestText = function(req)
  551. {
  552. var result = {message: mxResources.get('unknownError')};
  553. try
  554. {
  555. result = JSON.parse(req.getText());
  556. }
  557. catch (e)
  558. {
  559. // ignore
  560. }
  561. return result;
  562. };
  563. /**
  564. * Checks if the client is authorized and calls the next step.
  565. */
  566. OneDriveClient.prototype.pickLibrary = function(fn)
  567. {
  568. this.pickFile(fn);
  569. };
  570. /**
  571. * Checks if the client is authorized and calls the next step.
  572. */
  573. OneDriveClient.prototype.pickFolder = function(fn)
  574. {
  575. // Default folder not supported in OneDrive
  576. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  577. {
  578. this.execute(mxUtils.bind(this, function(token)
  579. {
  580. this.ui.spinner.stop();
  581. if (token != null)
  582. {
  583. WL.fileDialog(
  584. {
  585. mode: 'save'
  586. }).then(
  587. function (resp)
  588. {
  589. fn(resp);
  590. },
  591. function (responseFailed)
  592. {
  593. fn(null);
  594. }
  595. );
  596. }
  597. }));
  598. }
  599. };
  600. /**
  601. * Checks if the client is authorized and calls the next step.
  602. */
  603. OneDriveClient.prototype.pickFile = function(fn)
  604. {
  605. fn = (fn != null) ? fn : mxUtils.bind(this, function(id)
  606. {
  607. this.ui.loadFile('W' + encodeURIComponent(id));
  608. });
  609. // First time loading is slow so show spinner
  610. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  611. {
  612. this.execute(mxUtils.bind(this, function(token)
  613. {
  614. this.ui.spinner.stop();
  615. if (token != null)
  616. {
  617. WL.fileDialog(
  618. {
  619. mode: 'open',
  620. select: 'multi'
  621. }).then(
  622. function (resp)
  623. {
  624. if (resp != null && resp.data != null && resp.data.files != null)
  625. {
  626. for (var i = 0; i < resp.data.files.length; i++)
  627. {
  628. var id = resp.data.files[i].id;
  629. id = id.substring(id.lastIndexOf('.') + 1);
  630. fn(id);
  631. }
  632. }
  633. },
  634. function (responseFailed) {}
  635. );
  636. }
  637. }));
  638. }
  639. };
  640. /**
  641. * Checks if the client is authorized and calls the next step.
  642. */
  643. OneDriveClient.prototype.logout = function()
  644. {
  645. this.setUser(null);
  646. this.clearCookie();
  647. // LATER: Check why async callback does not work
  648. WL.logout();
  649. };