GitHubClient.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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, 'download_url': data.download_url};
  299. var content = data.content;
  300. if (data.encoding === 'base64')
  301. {
  302. if ((/(\.png)$/i.test(data.name)))
  303. {
  304. content = 'data:image/png;base64,' + content;
  305. }
  306. else
  307. {
  308. content = (window.atob) ? atob(content) : Base64.decode(content, true);
  309. }
  310. }
  311. return (asLibrary) ? new GitHubLibrary(this.ui, content, meta) : new GitHubFile(this.ui, content, meta);
  312. };
  313. /**
  314. * Translates this point by the given vector.
  315. *
  316. * @param {number} dx X-coordinate of the translation.
  317. * @param {number} dy Y-coordinate of the translation.
  318. */
  319. GitHubClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  320. {
  321. this.insertFile(filename, data, success, error, true, folderId, false);
  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. GitHubClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  330. {
  331. asLibrary = (asLibrary != null) ? asLibrary : false;
  332. var tokens = folderId.split('/');
  333. var org = tokens[0];
  334. var repo = tokens[1];
  335. var ref = tokens[2];
  336. var path = tokens.slice(3, tokens.length).join('/');
  337. if (path.length > 0)
  338. {
  339. path = path + '/';
  340. }
  341. path = path + filename;
  342. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, sha)
  343. {
  344. if (checked)
  345. {
  346. // Does not insert file here as there is another writeFile implicit via fileCreated
  347. if (!asLibrary)
  348. {
  349. success(new GitHubFile(this.ui, data, {'org': org, 'repo': repo,
  350. 'ref': ref, 'name': filename, 'path': path}));
  351. }
  352. else
  353. {
  354. if (!base64Encoded)
  355. {
  356. data = (window.btoa) ? btoa(data) : Base64.encode(data);
  357. }
  358. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  359. {
  360. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  361. {
  362. this.getFile(org + '/' + repo + '/' + ref + '/' + path, success, error, asLibrary);
  363. }), error);
  364. }), mxUtils.bind(this, function()
  365. {
  366. // do nothing
  367. }));
  368. }
  369. }
  370. else if (error != null)
  371. {
  372. error();
  373. }
  374. }))
  375. };
  376. /**
  377. *
  378. */
  379. GitHubClient.prototype.showCommitDialog = function(filename, isNew, success, cancel)
  380. {
  381. // Pauses spinner while commit message dialog is shown
  382. var resume = this.ui.spinner.pause();
  383. var dlg = new FilenameDialog(this.ui, mxResources.get((isNew) ? 'addedFile' : 'updateFile',
  384. [filename]), mxResources.get('ok'), mxUtils.bind(this, function(message)
  385. {
  386. resume();
  387. success(message);
  388. }), mxResources.get('changes'), null, null, null, null, mxUtils.bind(this, function()
  389. {
  390. cancel();
  391. }));
  392. this.ui.showDialog(dlg.container, 300, 80, true, false);
  393. dlg.init();
  394. };
  395. /**
  396. *
  397. */
  398. GitHubClient.prototype.writeFile = function(org, repo, ref, path, message, data, sha, success, error)
  399. {
  400. var entity =
  401. {
  402. path: path,
  403. message: message,
  404. content: data
  405. };
  406. if (sha != null)
  407. {
  408. entity.sha = sha;
  409. }
  410. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  411. '/contents/' + path + '?ref=' + encodeURIComponent(ref),
  412. JSON.stringify(entity), 'PUT');
  413. this.executeRequest(req, mxUtils.bind(this, function(req)
  414. {
  415. success(req);
  416. }), error);
  417. };
  418. /**
  419. * Translates this point by the given vector.
  420. *
  421. * @param {number} dx X-coordinate of the translation.
  422. * @param {number} dy Y-coordinate of the translation.
  423. */
  424. GitHubClient.prototype.checkExists = function(path, askReplace, fn)
  425. {
  426. this.getFile(path, mxUtils.bind(this, function(file)
  427. {
  428. if (askReplace)
  429. {
  430. var resume = this.ui.spinner.pause();
  431. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  432. {
  433. resume();
  434. fn(true, file.meta.sha);
  435. }, function()
  436. {
  437. resume();
  438. fn(false);
  439. });
  440. }
  441. else
  442. {
  443. this.ui.spinner.stop();
  444. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  445. {
  446. fn(false);
  447. });
  448. }
  449. }), mxUtils.bind(this, function(err)
  450. {
  451. fn(true);
  452. }));
  453. };
  454. /**
  455. * Translates this point by the given vector.
  456. *
  457. * @param {number} dx X-coordinate of the translation.
  458. * @param {number} dy Y-coordinate of the translation.
  459. */
  460. GitHubClient.prototype.saveFile = function(file, success, error)
  461. {
  462. var org = file.meta.org;
  463. var repo = file.meta.repo;
  464. var ref = file.meta.ref;
  465. var path = file.meta.path;
  466. this.showCommitDialog(file.meta.name, file.meta.sha == null, mxUtils.bind(this, function(message)
  467. {
  468. var data = (window.btoa) ? btoa(file.getData()) : Base64.encode(file.getData());
  469. var fn = mxUtils.bind(this, function(sha)
  470. {
  471. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  472. {
  473. var data = JSON.parse(req.getText());
  474. success(data.content.sha);
  475. }), mxUtils.bind(this, function(err)
  476. {
  477. // Handles special conflict case where overwrite needs an update of the sha
  478. if (err != null && err.status == 409)
  479. {
  480. resume = this.ui.spinner.pause();
  481. var dlg = new ErrorDialog(this.ui, mxResources.get('errorSavingFile'),
  482. mxResources.get('fileChangedOverwrite'), mxResources.get('cancel'), mxUtils.bind(this, function()
  483. {
  484. success(null);
  485. }), null, mxResources.get('overwrite'), mxUtils.bind(this, function()
  486. {
  487. resume();
  488. // Gets the latest sha and tries again
  489. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  490. {
  491. fn(tempFile.meta.sha);
  492. }));
  493. }));
  494. this.ui.showDialog(dlg.container, 340, 150, true, false);
  495. dlg.init();
  496. }
  497. else
  498. {
  499. error(err);
  500. }
  501. }));
  502. });
  503. fn(file.meta.sha);
  504. }), mxUtils.bind(this, function()
  505. {
  506. success(null);
  507. }));
  508. };
  509. /**
  510. * Checks if the client is authorized and calls the next step.
  511. */
  512. GitHubClient.prototype.pickLibrary = function(fn)
  513. {
  514. this.pickFile(fn);
  515. };
  516. /**
  517. * Checks if the client is authorized and calls the next step.
  518. */
  519. GitHubClient.prototype.pickFolder = function(fn)
  520. {
  521. var ask = mxUtils.bind(this, function(defaultPath)
  522. {
  523. this.ui.showGitHubDialog(false, mxUtils.bind(this, function(org, repo, ref, path)
  524. {
  525. if (this.ui.spinner.spin(document.body, mxResources.get('loading')))
  526. {
  527. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  528. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  529. this.executeRequest(req, mxUtils.bind(this, function(req)
  530. {
  531. this.ui.spinner.stop();
  532. fn(org + '/' + repo + '/' + ref + '/' + path);
  533. }), mxUtils.bind(this, function(err)
  534. {
  535. this.ui.spinner.stop();
  536. this.ui.handleError({message: mxResources.get('folderNotFound')}, null, function()
  537. {
  538. ask(path);
  539. });
  540. }));
  541. }
  542. }), defaultPath);
  543. });
  544. ask('');
  545. };
  546. /**
  547. * Checks if the client is authorized and calls the next step.
  548. */
  549. GitHubClient.prototype.pickFile = function(fn)
  550. {
  551. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  552. {
  553. this.ui.loadFile('H' + encodeURIComponent(path));
  554. });
  555. this.ui.showGitHubDialog(true, mxUtils.bind(this, function(org, repo, ref, path)
  556. {
  557. fn(org + '/' + repo + '/' + ref + '/' + path);
  558. }));
  559. };
  560. /**
  561. * Checks if the client is authorized and calls the next step.
  562. */
  563. GitHubClient.prototype.logout = function()
  564. {
  565. this.setUser(null);
  566. this.clearPersistentToken();
  567. this.token = null;
  568. };