GitHubClient.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. GitHubClient = 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. this.token = this.getPersistentToken();
  13. };
  14. // Extends mxEventSource
  15. mxUtils.extend(GitHubClient, mxEventSource);
  16. /**
  17. * Specifies if thumbnails should be enabled. Default is true.
  18. * LATER: If thumbnails are disabled, make sure to replace the
  19. * existing thumbnail with the placeholder only once.
  20. */
  21. GitHubClient.prototype.clientId = (window.location.hostname == 'test.draw.io') ? '23bc97120b9035515661' : '89c9e4624ca416554489';
  22. /**
  23. * OAuth scope.
  24. */
  25. GitHubClient.prototype.scope = 'repo';
  26. /**
  27. * Default extension for new files.
  28. */
  29. GitHubClient.prototype.extension = '.xml';
  30. /**
  31. * Base URL for API calls.
  32. */
  33. GitHubClient.prototype.baseUrl = 'https://api.github.com';
  34. /**
  35. * Token for the current user.
  36. */
  37. GitHubClient.prototype.token = null;
  38. /**
  39. * Authorizes the client, gets the userId and calls <open>.
  40. */
  41. GitHubClient.prototype.setUser = function(user)
  42. {
  43. this.user = user;
  44. this.fireEvent(new mxEventObject('userChanged'));
  45. };
  46. /**
  47. * Authorizes the client, gets the userId and calls <open>.
  48. */
  49. GitHubClient.prototype.getUser = function()
  50. {
  51. return this.user;
  52. };
  53. /**
  54. *
  55. */
  56. GitHubClient.prototype.clearPersistentToken = function()
  57. {
  58. var expiration = new Date();
  59. expiration.setYear(expiration.getFullYear() - 1);
  60. document.cookie = 'ghauth=; expires=' + expiration.toUTCString();
  61. };
  62. /**
  63. * Authorizes the client, gets the userId and calls <open>.
  64. */
  65. GitHubClient.prototype.getPersistentToken = function()
  66. {
  67. var cookies = document.cookie;
  68. var name = 'ghauth=';
  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.length > 0) ? value : null;
  84. }
  85. return null;
  86. };
  87. /**
  88. * Authorizes the client, gets the userId and calls <open>.
  89. */
  90. GitHubClient.prototype.setPersistentToken = function(token)
  91. {
  92. if (token != null)
  93. {
  94. var expiration = new Date();
  95. expiration.setYear(expiration.getFullYear() + 10);
  96. var cookie = 'ghauth=' + token +'; path=/; expires=' + expiration.toUTCString();
  97. if (document.location.protocol.toLowerCase() == 'https')
  98. {
  99. cookie = cookie + ';secure';
  100. }
  101. document.cookie = cookie;
  102. }
  103. else
  104. {
  105. this.clearPersistentToken();
  106. }
  107. };
  108. /**
  109. * Authorizes the client, gets the userId and calls <open>.
  110. */
  111. GitHubClient.prototype.updateUser = function(success, error)
  112. {
  113. var fn = mxUtils.bind(this, function()
  114. {
  115. var acceptResponse = true;
  116. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  117. {
  118. acceptResponse = false;
  119. error({code: App.ERROR_TIMEOUT, retry: fn});
  120. }), this.ui.timeout);
  121. mxUtils.get(this.baseUrl + '/user?access_token=' + this.token, mxUtils.bind(this, function(userReq)
  122. {
  123. window.clearTimeout(timeoutThread);
  124. if (acceptResponse)
  125. {
  126. if (userReq.getStatus() === 401)
  127. {
  128. this.authorizeRequest(fn, error);
  129. }
  130. else
  131. {
  132. var userInfo = JSON.parse(userReq.getText());
  133. this.setUser(new DrawioUser(userInfo.id, userInfo.email, userInfo.name));
  134. success();
  135. }
  136. }
  137. }));
  138. });
  139. fn();
  140. };
  141. /**
  142. * Authorizes the client, gets the userId and calls <open>.
  143. */
  144. GitHubClient.prototype.authorizeRequest = function(success, error)
  145. {
  146. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
  147. {
  148. if (authSuccess != null)
  149. {
  150. authSuccess();
  151. }
  152. // Initializes oauth flow
  153. window.open('https://github.com/login/oauth/authorize?client_id=' + this.clientId + '&scope=' + this.scope);
  154. window.onGitHubCallback = mxUtils.bind(this, function(code, authWindow)
  155. {
  156. window.onGitHubCallback = null;
  157. if (authWindow != null)
  158. {
  159. authWindow.close();
  160. }
  161. // Gets token for code via servlet
  162. var fn = mxUtils.bind(this, function()
  163. {
  164. var acceptResponse = true;
  165. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  166. {
  167. acceptResponse = false;
  168. error({code: App.ERROR_TIMEOUT, retry: fn});
  169. }), this.ui.timeout);
  170. mxUtils.get('/github?client_id=' + this.clientId + '&code=' + code, mxUtils.bind(this, function(authReq)
  171. {
  172. window.clearTimeout(timeoutThread);
  173. if (acceptResponse)
  174. {
  175. var res = authReq.getText();
  176. this.token = res.substring(res.indexOf('=') + 1, res.indexOf('&'));
  177. if (remember)
  178. {
  179. this.setPersistentToken(this.token);
  180. }
  181. success();
  182. }
  183. }));
  184. });
  185. fn();
  186. });
  187. }));
  188. };
  189. /**
  190. * Authorizes the client, gets the userId and calls <open>.
  191. */
  192. GitHubClient.prototype.executeRequest = function(req, success, error, refresh, overwrite)
  193. {
  194. var doExecute = mxUtils.bind(this, function()
  195. {
  196. var acceptResponse = true;
  197. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  198. {
  199. acceptResponse = false;
  200. error({code: App.ERROR_TIMEOUT, retry: fn});
  201. }), this.ui.timeout);
  202. var temp = this.token;
  203. req.setRequestHeaders = function(request, params)
  204. {
  205. request.setRequestHeader('Authorization', 'token ' + temp);
  206. };
  207. req.send(mxUtils.bind(this, function()
  208. {
  209. window.clearTimeout(timeoutThread);
  210. if (acceptResponse)
  211. {
  212. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  213. {
  214. success(req);
  215. }
  216. else if (req.getStatus() === 401)
  217. {
  218. this.authorizeRequest(fn, error);
  219. }
  220. else if (req.getStatus() === 404)
  221. {
  222. error({message: mxResources.get('fileNotFound')});
  223. }
  224. else if (req.getStatus() === 409)
  225. {
  226. // Special case: flag to the caller that there was a conflict
  227. error({status: 409});
  228. }
  229. else
  230. {
  231. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  232. }
  233. }
  234. }), error);
  235. });
  236. var fn = mxUtils.bind(this, function()
  237. {
  238. if (this.user == null)
  239. {
  240. this.updateUser(doExecute, error);
  241. }
  242. else
  243. {
  244. doExecute();
  245. }
  246. });
  247. if (this.token === null)
  248. {
  249. this.authorizeRequest(fn, error);
  250. }
  251. else
  252. {
  253. fn();
  254. }
  255. };
  256. /**
  257. * Checks if the client is authorized and calls the next step.
  258. */
  259. GitHubClient.prototype.getLibrary = function(path, success, error)
  260. {
  261. this.getFile(path, success, error, true);
  262. };
  263. /**
  264. * Checks if the client is authorized and calls the next step.
  265. */
  266. GitHubClient.prototype.getFile = function(path, success, error, asLibrary)
  267. {
  268. asLibrary = (asLibrary != null) ? asLibrary : false;
  269. var tokens = path.split('/');
  270. var org = tokens[0];
  271. var repo = tokens[1];
  272. var ref = tokens[2];
  273. var path = tokens.slice(3, tokens.length).join('/');
  274. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  275. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  276. this.executeRequest(req, mxUtils.bind(this, function(req)
  277. {
  278. try
  279. {
  280. success(this.createGitHubFile(org, repo, ref, req, asLibrary));
  281. }
  282. catch (e)
  283. {
  284. error(e);
  285. }
  286. }), error);
  287. };
  288. /**
  289. * Translates this point by the given vector.
  290. *
  291. * @param {number} dx X-coordinate of the translation.
  292. * @param {number} dy Y-coordinate of the translation.
  293. */
  294. GitHubClient.prototype.createGitHubFile = function(org, repo, ref, req, asLibrary)
  295. {
  296. var data = JSON.parse(req.getText());
  297. var meta = {'org': org, 'repo': repo, 'ref': ref, 'name': data.name,
  298. 'path': data.path, 'sha': data.sha, 'html_url': data.html_url,
  299. 'download_url': data.download_url};
  300. var content = data.content;
  301. if (data.encoding === 'base64')
  302. {
  303. if ((/(\.png)$/i.test(data.name)))
  304. {
  305. content = 'data:image/png;base64,' + content;
  306. }
  307. else
  308. {
  309. content = (window.atob) ? atob(content) : Base64.decode(content, true);
  310. }
  311. }
  312. return (asLibrary) ? new GitHubLibrary(this.ui, content, meta) : new GitHubFile(this.ui, content, meta);
  313. };
  314. /**
  315. * Translates this point by the given vector.
  316. *
  317. * @param {number} dx X-coordinate of the translation.
  318. * @param {number} dy Y-coordinate of the translation.
  319. */
  320. GitHubClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  321. {
  322. this.insertFile(filename, data, success, error, true, folderId, false);
  323. };
  324. /**
  325. * Translates this point by the given vector.
  326. *
  327. * @param {number} dx X-coordinate of the translation.
  328. * @param {number} dy Y-coordinate of the translation.
  329. */
  330. GitHubClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  331. {
  332. asLibrary = (asLibrary != null) ? asLibrary : false;
  333. var tokens = folderId.split('/');
  334. var org = tokens[0];
  335. var repo = tokens[1];
  336. var ref = tokens[2];
  337. var path = tokens.slice(3, tokens.length).join('/');
  338. if (path.length > 0)
  339. {
  340. path = path + '/';
  341. }
  342. path = path + filename;
  343. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, sha)
  344. {
  345. if (checked)
  346. {
  347. // Does not insert file here as there is another writeFile implicit via fileCreated
  348. if (!asLibrary)
  349. {
  350. success(new GitHubFile(this.ui, data, {'org': org, 'repo': repo, 'ref': ref,
  351. 'name': filename, 'path': path, 'sha': sha, isNew: true}));
  352. }
  353. else
  354. {
  355. if (!base64Encoded)
  356. {
  357. data = (window.btoa) ? btoa(data) : Base64.encode(data);
  358. }
  359. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  360. {
  361. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  362. {
  363. this.getFile(org + '/' + repo + '/' + ref + '/' + path, success, error, asLibrary);
  364. }), error);
  365. }), mxUtils.bind(this, function()
  366. {
  367. // do nothing
  368. }));
  369. }
  370. }
  371. else if (error != null)
  372. {
  373. error();
  374. }
  375. }))
  376. };
  377. /**
  378. *
  379. */
  380. GitHubClient.prototype.showCommitDialog = function(filename, isNew, success, cancel)
  381. {
  382. // Pauses spinner while commit message dialog is shown
  383. var resume = this.ui.spinner.pause();
  384. var dlg = new FilenameDialog(this.ui, mxResources.get((isNew) ? 'addedFile' : 'updateFile',
  385. [filename]), mxResources.get('ok'), mxUtils.bind(this, function(message)
  386. {
  387. resume();
  388. success(message);
  389. }), mxResources.get('changes'), null, null, null, null, mxUtils.bind(this, function()
  390. {
  391. cancel();
  392. }));
  393. this.ui.showDialog(dlg.container, 300, 80, true, false);
  394. dlg.init();
  395. };
  396. /**
  397. *
  398. */
  399. GitHubClient.prototype.writeFile = function(org, repo, ref, path, message, data, sha, success, error)
  400. {
  401. var entity =
  402. {
  403. path: path,
  404. message: message,
  405. content: data
  406. };
  407. if (sha != null)
  408. {
  409. entity.sha = sha;
  410. }
  411. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  412. '/contents/' + path + '?ref=' + encodeURIComponent(ref),
  413. JSON.stringify(entity), 'PUT');
  414. this.executeRequest(req, mxUtils.bind(this, function(req)
  415. {
  416. success(req);
  417. }), error);
  418. };
  419. /**
  420. * Translates this point by the given vector.
  421. *
  422. * @param {number} dx X-coordinate of the translation.
  423. * @param {number} dy Y-coordinate of the translation.
  424. */
  425. GitHubClient.prototype.checkExists = function(path, askReplace, fn)
  426. {
  427. this.getFile(path, mxUtils.bind(this, function(file)
  428. {
  429. if (askReplace)
  430. {
  431. var resume = this.ui.spinner.pause();
  432. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  433. {
  434. resume();
  435. fn(true, file.meta.sha);
  436. }, function()
  437. {
  438. resume();
  439. fn(false);
  440. });
  441. }
  442. else
  443. {
  444. this.ui.spinner.stop();
  445. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  446. {
  447. fn(false);
  448. });
  449. }
  450. }), mxUtils.bind(this, function(err)
  451. {
  452. fn(true);
  453. }));
  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. GitHubClient.prototype.saveFile = function(file, success, error)
  462. {
  463. var org = file.meta.org;
  464. var repo = file.meta.repo;
  465. var ref = file.meta.ref;
  466. var path = file.meta.path;
  467. this.showCommitDialog(file.meta.name, file.meta.sha == null || file.meta.isNew, mxUtils.bind(this, function(message)
  468. {
  469. var data = (window.btoa) ? btoa(file.getData()) : Base64.encode(file.getData());
  470. var fn = mxUtils.bind(this, function(sha)
  471. {
  472. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  473. {
  474. delete file.meta.isNew;
  475. success(JSON.parse(req.getText()));
  476. }), mxUtils.bind(this, function(err)
  477. {
  478. // Handles special conflict case where overwrite needs an update of the sha
  479. if (err != null && err.status == 409)
  480. {
  481. resume = this.ui.spinner.pause();
  482. var dlg = new ErrorDialog(this.ui, mxResources.get('errorSavingFile'),
  483. mxResources.get('fileChangedOverwrite'), mxResources.get('cancel'), mxUtils.bind(this, function()
  484. {
  485. success(null);
  486. }), null, mxResources.get('overwrite'), mxUtils.bind(this, function()
  487. {
  488. resume();
  489. // Gets the latest sha and tries again
  490. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  491. {
  492. fn(tempFile.meta.sha);
  493. }));
  494. }));
  495. this.ui.showDialog(dlg.container, 340, 150, true, false);
  496. dlg.init();
  497. }
  498. else
  499. {
  500. error(err);
  501. }
  502. }));
  503. });
  504. fn(file.meta.sha);
  505. }), mxUtils.bind(this, function()
  506. {
  507. success(null);
  508. }));
  509. };
  510. /**
  511. * Checks if the client is authorized and calls the next step.
  512. */
  513. GitHubClient.prototype.pickLibrary = function(fn)
  514. {
  515. this.pickFile(fn);
  516. };
  517. /**
  518. * Checks if the client is authorized and calls the next step.
  519. */
  520. GitHubClient.prototype.pickFolder = function(fn)
  521. {
  522. var ask = mxUtils.bind(this, function(defaultPath)
  523. {
  524. this.ui.showGitHubDialog(false, mxUtils.bind(this, function(org, repo, ref, path)
  525. {
  526. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  527. {
  528. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  529. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  530. this.executeRequest(req, mxUtils.bind(this, function(req)
  531. {
  532. this.ui.spinner.stop();
  533. fn(org + '/' + repo + '/' + ref + '/' + path);
  534. }), mxUtils.bind(this, function(err)
  535. {
  536. this.ui.spinner.stop();
  537. this.ui.handleError({message: mxResources.get('folderNotFound')}, null, function()
  538. {
  539. ask(path);
  540. });
  541. }));
  542. }
  543. }), defaultPath);
  544. });
  545. ask('');
  546. };
  547. /**
  548. * Checks if the client is authorized and calls the next step.
  549. */
  550. GitHubClient.prototype.pickFile = function(fn)
  551. {
  552. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  553. {
  554. this.ui.loadFile('H' + encodeURIComponent(path));
  555. });
  556. this.ui.showGitHubDialog(true, mxUtils.bind(this, function(org, repo, ref, path)
  557. {
  558. fn(org + '/' + repo + '/' + ref + '/' + path);
  559. }));
  560. };
  561. /**
  562. * Checks if the client is authorized and calls the next step.
  563. */
  564. GitHubClient.prototype.logout = function()
  565. {
  566. this.setUser(null);
  567. this.clearPersistentToken();
  568. this.token = null;
  569. };