GitHubClient.js 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. GitHubClient = function(editorUi)
  6. {
  7. DrawioClient.call(this, editorUi, 'ghauth');
  8. };
  9. // Extends DrawioClient
  10. mxUtils.extend(GitHubClient, DrawioClient);
  11. /**
  12. * Specifies if thumbnails should be enabled. Default is true.
  13. * LATER: If thumbnails are disabled, make sure to replace the
  14. * existing thumbnail with the placeholder only once.
  15. */
  16. GitHubClient.prototype.clientId = (window.location.hostname == 'test.draw.io') ? '23bc97120b9035515661' : '89c9e4624ca416554489';
  17. /**
  18. * OAuth scope.
  19. */
  20. GitHubClient.prototype.scope = 'repo';
  21. /**
  22. * Default extension for new files.
  23. */
  24. GitHubClient.prototype.extension = '.xml';
  25. /**
  26. * Base URL for API calls.
  27. */
  28. GitHubClient.prototype.baseUrl = 'https://api.github.com';
  29. /**
  30. * Maximum file size of the GitHub REST API.
  31. */
  32. GitHubClient.prototype.maxFileSize = 1000000 /*1MB*/;
  33. /**
  34. * Authorizes the client, gets the userId and calls <open>.
  35. */
  36. GitHubClient.prototype.updateUser = function(success, error, failOnAuth)
  37. {
  38. var acceptResponse = true;
  39. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  40. {
  41. acceptResponse = false;
  42. error({code: App.ERROR_TIMEOUT});
  43. }), this.ui.timeout);
  44. mxUtils.get(this.baseUrl + '/user?access_token=' + this.token, mxUtils.bind(this, function(userReq)
  45. {
  46. window.clearTimeout(timeoutThread);
  47. if (acceptResponse)
  48. {
  49. if (userReq.getStatus() === 401)
  50. {
  51. if (!failOnAuth)
  52. {
  53. this.logout();
  54. this.authenticate(mxUtils.bind(this, function()
  55. {
  56. this.updateUser(success, error, true);
  57. }), error);
  58. }
  59. else
  60. {
  61. error({message: mxResources.get('accessDenied')});
  62. }
  63. }
  64. else if (userReq.getStatus() < 200 || userReq.getStatus() >= 300)
  65. {
  66. error({message: mxResources.get('accessDenied')});
  67. }
  68. else
  69. {
  70. var userInfo = JSON.parse(userReq.getText());
  71. this.setUser(new DrawioUser(userInfo.id, userInfo.email, userInfo.name));
  72. success();
  73. }
  74. }
  75. }));
  76. };
  77. /**
  78. * Authorizes the client, gets the userId and calls <open>.
  79. */
  80. GitHubClient.prototype.authenticate = function(success, error)
  81. {
  82. if (window.onGitHubCallback == null)
  83. {
  84. var auth = mxUtils.bind(this, function()
  85. {
  86. var acceptAuthResponse = true;
  87. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
  88. {
  89. var win = window.open('https://github.com/login/oauth/authorize?client_id=' +
  90. this.clientId + '&scope=' + this.scope, 'ghauth');
  91. if (win != null)
  92. {
  93. window.onGitHubCallback = mxUtils.bind(this, function(code, authWindow)
  94. {
  95. if (acceptAuthResponse)
  96. {
  97. window.onGitHubCallback = null;
  98. acceptAuthResponse = false;
  99. if (code == null)
  100. {
  101. error({message: mxResources.get('accessDenied'), retry: auth});
  102. }
  103. else
  104. {
  105. // Gets token for code via servlet
  106. var fn = mxUtils.bind(this, function()
  107. {
  108. var acceptResponse = true;
  109. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  110. {
  111. acceptResponse = false;
  112. error({code: App.ERROR_TIMEOUT, retry: fn});
  113. }), this.ui.timeout);
  114. mxUtils.get('/github?client_id=' + this.clientId + '&code=' + code, mxUtils.bind(this, function(authReq)
  115. {
  116. window.clearTimeout(timeoutThread);
  117. if (acceptResponse)
  118. {
  119. try
  120. {
  121. if (authReq.getStatus() < 200 || authReq.getStatus() >= 300)
  122. {
  123. error({message: mxResources.get('cannotLogin')});
  124. }
  125. else
  126. {
  127. if (authSuccess != null)
  128. {
  129. authSuccess();
  130. }
  131. var res = authReq.getText();
  132. this.token = res.substring(res.indexOf('=') + 1, res.indexOf('&'));
  133. this.setUser(null);
  134. if (remember)
  135. {
  136. this.setPersistentToken(this.token);
  137. }
  138. success();
  139. }
  140. }
  141. catch (e)
  142. {
  143. error(e);
  144. }
  145. finally
  146. {
  147. if (authWindow != null)
  148. {
  149. authWindow.close();
  150. }
  151. }
  152. }
  153. }));
  154. });
  155. fn();
  156. }
  157. }
  158. else if (authWindow != null)
  159. {
  160. authWindow.close();
  161. }
  162. });
  163. }
  164. else
  165. {
  166. error({message: mxResources.get('serviceUnavailableOrBlocked'), retry: auth});
  167. }
  168. }), mxUtils.bind(this, function()
  169. {
  170. if (acceptAuthResponse)
  171. {
  172. window.onGitHubCallback = null;
  173. acceptAuthResponse = false;
  174. error({message: mxResources.get('accessDenied'), retry: auth});
  175. }
  176. }));
  177. });
  178. auth();
  179. }
  180. else
  181. {
  182. error({code: App.ERROR_BUSY});
  183. }
  184. };
  185. /**
  186. * Authorizes the client, gets the userId and calls <open>.
  187. */
  188. GitHubClient.prototype.executeRequest = function(req, success, error)
  189. {
  190. var doExecute = mxUtils.bind(this, function(failOnAuth)
  191. {
  192. var acceptResponse = true;
  193. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  194. {
  195. acceptResponse = false;
  196. error({code: App.ERROR_TIMEOUT, retry: fn});
  197. }), this.ui.timeout);
  198. var temp = this.token;
  199. req.setRequestHeaders = function(request, params)
  200. {
  201. request.setRequestHeader('Authorization', 'token ' + temp);
  202. };
  203. req.send(mxUtils.bind(this, function()
  204. {
  205. window.clearTimeout(timeoutThread);
  206. if (acceptResponse)
  207. {
  208. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  209. {
  210. success(req);
  211. }
  212. else if (req.getStatus() === 401)
  213. {
  214. if (!failOnAuth)
  215. {
  216. this.authenticate(function()
  217. {
  218. doExecute(true);
  219. }, error);
  220. }
  221. else
  222. {
  223. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  224. {
  225. this.authenticate(function()
  226. {
  227. fn(true);
  228. }, error);
  229. })});
  230. }
  231. }
  232. else if (req.getStatus() === 403)
  233. {
  234. var tooLarge = false;
  235. try
  236. {
  237. var temp = JSON.parse(req.getText());
  238. if (temp != null && temp.errors != null && temp.errors.length > 0)
  239. {
  240. tooLarge = temp.errors[0].code == 'too_large';
  241. }
  242. }
  243. catch (e)
  244. {
  245. // ignore
  246. }
  247. error({message: mxResources.get((tooLarge) ? 'drawingTooLarge' : 'forbidden')});
  248. }
  249. else if (req.getStatus() === 404)
  250. {
  251. error({message: mxResources.get('fileNotFound')});
  252. }
  253. else if (req.getStatus() === 409)
  254. {
  255. // Special case: flag to the caller that there was a conflict
  256. error({status: 409});
  257. }
  258. else
  259. {
  260. error({message: mxResources.get('error') + ' ' + req.getStatus()});
  261. }
  262. }
  263. }), error);
  264. });
  265. var fn = mxUtils.bind(this, function(failOnAuth)
  266. {
  267. if (this.user == null)
  268. {
  269. this.updateUser(function()
  270. {
  271. fn(true);
  272. }, error, failOnAuth);
  273. }
  274. else
  275. {
  276. doExecute(failOnAuth);
  277. }
  278. });
  279. if (this.token == null)
  280. {
  281. this.authenticate(function()
  282. {
  283. fn(true);
  284. }, error);
  285. }
  286. else
  287. {
  288. fn(false);
  289. }
  290. };
  291. /**
  292. * Checks if the client is authorized and calls the next step.
  293. */
  294. GitHubClient.prototype.getLibrary = function(path, success, error)
  295. {
  296. this.getFile(path, success, error, true);
  297. };
  298. /**
  299. * Checks if the client is authorized and calls the next step.
  300. */
  301. GitHubClient.prototype.getFile = function(path, success, error, asLibrary)
  302. {
  303. asLibrary = (asLibrary != null) ? asLibrary : false;
  304. var tokens = path.split('/');
  305. var org = tokens[0];
  306. var repo = tokens[1];
  307. var ref = tokens[2];
  308. var path = tokens.slice(3, tokens.length).join('/');
  309. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  310. if (/\.vsdx$/i.test(path) || /\.gliffy$/i.test(path) || /\.png$/i.test(path))
  311. {
  312. // Should never be null
  313. if (this.token != null)
  314. {
  315. var url = this.baseUrl + '/repos/' + org + '/' + repo +
  316. '/contents/' + path + '?ref=' + encodeURIComponent(ref) +
  317. '&token=' + this.token;
  318. var tokens = path.split('/');
  319. var name = (tokens.length > 0) ? tokens[tokens.length - 1] : path;
  320. this.ui.convertFile(url, name, null, this.extension, success, error);
  321. }
  322. else
  323. {
  324. error({message: mxResources.get('accessDenied')});
  325. }
  326. }
  327. else
  328. {
  329. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  330. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  331. this.executeRequest(req, mxUtils.bind(this, function(req)
  332. {
  333. try
  334. {
  335. success(this.createGitHubFile(org, repo, ref, JSON.parse(req.getText()), asLibrary));
  336. }
  337. catch (e)
  338. {
  339. error(e);
  340. }
  341. }), error);
  342. }
  343. };
  344. /**
  345. * Translates this point by the given vector.
  346. *
  347. * @param {number} dx X-coordinate of the translation.
  348. * @param {number} dy Y-coordinate of the translation.
  349. */
  350. GitHubClient.prototype.createGitHubFile = function(org, repo, ref, data, asLibrary)
  351. {
  352. var meta = {'org': org, 'repo': repo, 'ref': ref, 'name': data.name,
  353. 'path': data.path, 'sha': data.sha, 'html_url': data.html_url,
  354. 'download_url': data.download_url};
  355. var content = data.content;
  356. if (data.encoding === 'base64')
  357. {
  358. if (/\.jpe?g$/i.test(data.name))
  359. {
  360. content = 'data:image/jpeg;base64,' + content;
  361. }
  362. else if (/\.gif$/i.test(data.name))
  363. {
  364. content = 'data:image/gif;base64,' + content;
  365. }
  366. else
  367. {
  368. content = Base64.decode(content);
  369. }
  370. }
  371. return (asLibrary) ? new GitHubLibrary(this.ui, content, meta) : new GitHubFile(this.ui, content, meta);
  372. };
  373. /**
  374. * Translates this point by the given vector.
  375. *
  376. * @param {number} dx X-coordinate of the translation.
  377. * @param {number} dy Y-coordinate of the translation.
  378. */
  379. GitHubClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  380. {
  381. this.insertFile(filename, data, success, error, true, folderId, false);
  382. };
  383. /**
  384. * Translates this point by the given vector.
  385. *
  386. * @param {number} dx X-coordinate of the translation.
  387. * @param {number} dy Y-coordinate of the translation.
  388. */
  389. GitHubClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  390. {
  391. asLibrary = (asLibrary != null) ? asLibrary : false;
  392. var tokens = folderId.split('/');
  393. var org = tokens[0];
  394. var repo = tokens[1];
  395. var ref = tokens[2];
  396. var path = tokens.slice(3, tokens.length).join('/');
  397. if (path.length > 0)
  398. {
  399. path = path + '/';
  400. }
  401. path = path + filename;
  402. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, sha)
  403. {
  404. if (checked)
  405. {
  406. // Does not insert file here as there is another writeFile implicit via fileCreated
  407. if (!asLibrary)
  408. {
  409. success(new GitHubFile(this.ui, data, {'org': org, 'repo': repo, 'ref': ref,
  410. 'name': filename, 'path': path, 'sha': sha, isNew: true}));
  411. }
  412. else
  413. {
  414. if (!base64Encoded)
  415. {
  416. data = Base64.encode(data);
  417. }
  418. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  419. {
  420. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  421. {
  422. try
  423. {
  424. var msg = JSON.parse(req.getText());
  425. success(this.createGitHubFile(org, repo, ref, msg.content, asLibrary));
  426. }
  427. catch (e)
  428. {
  429. error(e);
  430. }
  431. }), error);
  432. }), error);
  433. }
  434. }
  435. else
  436. {
  437. error();
  438. }
  439. }))
  440. };
  441. /**
  442. *
  443. */
  444. GitHubClient.prototype.showCommitDialog = function(filename, isNew, success, cancel)
  445. {
  446. // Pauses spinner while commit message dialog is shown
  447. var resume = this.ui.spinner.pause();
  448. var dlg = new FilenameDialog(this.ui, mxResources.get((isNew) ? 'addedFile' : 'updateFile',
  449. [filename]), mxResources.get('ok'), mxUtils.bind(this, function(message)
  450. {
  451. resume();
  452. success(message);
  453. }), mxResources.get('commitMessage'), null, null, null, null, mxUtils.bind(this, function()
  454. {
  455. cancel();
  456. }));
  457. this.ui.showDialog(dlg.container, 300, 80, true, false);
  458. dlg.init();
  459. };
  460. /**
  461. *
  462. */
  463. GitHubClient.prototype.writeFile = function(org, repo, ref, path, message, data, sha, success, error)
  464. {
  465. if (data.length >= this.maxFileSize)
  466. {
  467. error({message: mxResources.get('drawingTooLarge') + ' (' +
  468. this.ui.formatFileSize(data.length) + ' / 1 MB)'});
  469. }
  470. else
  471. {
  472. var entity =
  473. {
  474. path: path,
  475. message: message,
  476. content: data
  477. };
  478. if (sha != null)
  479. {
  480. entity.sha = sha;
  481. }
  482. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  483. '/contents/' + path + '?ref=' + encodeURIComponent(ref),
  484. JSON.stringify(entity), 'PUT');
  485. this.executeRequest(req, mxUtils.bind(this, function(req)
  486. {
  487. success(req);
  488. }), error);
  489. }
  490. };
  491. /**
  492. * Translates this point by the given vector.
  493. *
  494. * @param {number} dx X-coordinate of the translation.
  495. * @param {number} dy Y-coordinate of the translation.
  496. */
  497. GitHubClient.prototype.checkExists = function(path, askReplace, fn)
  498. {
  499. this.getFile(path, mxUtils.bind(this, function(file)
  500. {
  501. if (askReplace && file.meta != null)
  502. {
  503. var resume = this.ui.spinner.pause();
  504. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  505. {
  506. resume();
  507. fn(true, file.meta.sha);
  508. }, function()
  509. {
  510. resume();
  511. fn(false);
  512. });
  513. }
  514. else
  515. {
  516. this.ui.spinner.stop();
  517. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  518. {
  519. fn(false);
  520. });
  521. }
  522. }), mxUtils.bind(this, function(err)
  523. {
  524. fn(true);
  525. }));
  526. };
  527. /**
  528. * Translates this point by the given vector.
  529. *
  530. * @param {number} dx X-coordinate of the translation.
  531. * @param {number} dy Y-coordinate of the translation.
  532. */
  533. GitHubClient.prototype.saveFile = function(file, success, error)
  534. {
  535. var org = file.meta.org;
  536. var repo = file.meta.repo;
  537. var ref = file.meta.ref;
  538. var path = file.meta.path;
  539. this.showCommitDialog(file.meta.name, file.meta.sha == null || file.meta.isNew, mxUtils.bind(this, function(message)
  540. {
  541. var data = Base64.encode(file.getData());
  542. var fn = mxUtils.bind(this, function(sha)
  543. {
  544. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  545. {
  546. delete file.meta.isNew;
  547. success(JSON.parse(req.getText()));
  548. }), mxUtils.bind(this, function(err)
  549. {
  550. // Handles special conflict case where overwrite needs an update of the sha
  551. if (err != null && err.status == 409)
  552. {
  553. resume = this.ui.spinner.pause();
  554. var dlg = new ErrorDialog(this.ui, mxResources.get('errorSavingFile'),
  555. mxResources.get('fileChangedOverwrite'), mxResources.get('cancel'), mxUtils.bind(this, function()
  556. {
  557. error();
  558. }), null, mxResources.get('overwrite'), mxUtils.bind(this, function()
  559. {
  560. resume();
  561. // Gets the latest sha and tries again
  562. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  563. {
  564. fn(tempFile.meta.sha);
  565. }), mxUtils.bind(this, function()
  566. {
  567. fn(null);
  568. }));
  569. }));
  570. this.ui.showDialog(dlg.container, 340, 150, true, false);
  571. dlg.init();
  572. }
  573. else
  574. {
  575. error(err);
  576. }
  577. }));
  578. });
  579. fn(file.meta.sha);
  580. }), mxUtils.bind(this, function()
  581. {
  582. error();
  583. }));
  584. };
  585. /**
  586. * Checks if the client is authorized and calls the next step.
  587. */
  588. GitHubClient.prototype.pickLibrary = function(fn)
  589. {
  590. this.pickFile(fn);
  591. };
  592. /**
  593. * Checks if the client is authorized and calls the next step.
  594. */
  595. GitHubClient.prototype.pickFolder = function(fn)
  596. {
  597. this.showGitHubDialog(false, fn);
  598. };
  599. /**
  600. * Checks if the client is authorized and calls the next step.
  601. */
  602. GitHubClient.prototype.pickFile = function(fn)
  603. {
  604. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  605. {
  606. this.ui.loadFile('H' + encodeURIComponent(path));
  607. });
  608. this.showGitHubDialog(true, fn);
  609. };
  610. /**
  611. *
  612. */
  613. GitHubClient.prototype.showGitHubDialog = function(showFiles, fn)
  614. {
  615. var org = null;
  616. var repo = null;
  617. var ref = null;
  618. var path = null;
  619. var content = document.createElement('div');
  620. content.style.whiteSpace = 'nowrap';
  621. content.style.overflow = 'hidden';
  622. content.style.height = '224px';
  623. var hd = document.createElement('h3');
  624. mxUtils.write(hd, mxResources.get((showFiles) ? 'selectFile' : 'selectFolder'));
  625. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  626. content.appendChild(hd);
  627. var div = document.createElement('div');
  628. div.style.whiteSpace = 'nowrap';
  629. div.style.overflow = 'auto';
  630. div.style.height = '194px';
  631. content.appendChild(div);
  632. var dlg = new CustomDialog(this.ui, content, mxUtils.bind(this, function()
  633. {
  634. fn(org + '/' + repo + '/' + ref + '/' + path);
  635. }));
  636. this.ui.showDialog(dlg.container, 340, 270, true, true);
  637. if (showFiles)
  638. {
  639. dlg.okButton.parentNode.removeChild(dlg.okButton);
  640. }
  641. var createLink = mxUtils.bind(this, function(label, fn)
  642. {
  643. var link = document.createElement('a');
  644. link.setAttribute('href', 'javascript:void(0);');
  645. mxUtils.write(link, label);
  646. mxEvent.addListener(link, 'click', fn);
  647. return link;
  648. });
  649. var updatePathInfo = mxUtils.bind(this, function(hideRef)
  650. {
  651. var pathInfo = document.createElement('div');
  652. pathInfo.style.marginBottom = '8px';
  653. pathInfo.appendChild(createLink(org + '/' + repo, mxUtils.bind(this, function()
  654. {
  655. path = null;
  656. selectRepo();
  657. })));
  658. if (!hideRef)
  659. {
  660. mxUtils.write(pathInfo, ' / ');
  661. pathInfo.appendChild(createLink(ref, mxUtils.bind(this, function()
  662. {
  663. path = null;
  664. selectRef();
  665. })));
  666. }
  667. if (path != null && path.length > 0)
  668. {
  669. var tokens = path.split('/');
  670. for (var i = 0; i < tokens.length; i++)
  671. {
  672. (function(index)
  673. {
  674. mxUtils.write(pathInfo, ' / ');
  675. pathInfo.appendChild(createLink(tokens[index], mxUtils.bind(this, function()
  676. {
  677. path = tokens.slice(0, index + 1).join('/');
  678. selectFile();
  679. })));
  680. })(i);
  681. }
  682. }
  683. div.appendChild(pathInfo);
  684. });
  685. var error = mxUtils.bind(this, function(err)
  686. {
  687. this.ui.handleError(err, null, mxUtils.bind(this, function()
  688. {
  689. this.ui.spinner.stop();
  690. this.ui.hideDialog();
  691. }));
  692. });
  693. var selectFile = mxUtils.bind(this, function()
  694. {
  695. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  696. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  697. dlg.okButton.removeAttribute('disabled');
  698. div.innerHTML = '';
  699. this.ui.spinner.spin(div, mxResources.get('loading'));
  700. this.executeRequest(req, mxUtils.bind(this, function(req)
  701. {
  702. updatePathInfo();
  703. this.ui.spinner.stop();
  704. var files = JSON.parse(req.getText());
  705. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  706. {
  707. if (path == '')
  708. {
  709. path = null;
  710. selectRepo();
  711. }
  712. else
  713. {
  714. var tokens = path.split('/');
  715. path = tokens.slice(0, tokens.length - 1).join('/');
  716. selectFile();
  717. }
  718. })));
  719. mxUtils.br(div);
  720. if (files == null || files.length == 0)
  721. {
  722. mxUtils.write(div, mxResources.get('noFiles'));
  723. }
  724. else
  725. {
  726. var listFiles = mxUtils.bind(this, function(showFolders)
  727. {
  728. for (var i = 0; i < files.length; i++)
  729. {
  730. (mxUtils.bind(this, function(file)
  731. {
  732. if (showFolders == (file.type == 'dir'))
  733. {
  734. div.appendChild(createLink(file.name + ((file.type == 'dir') ? '/' : ''), mxUtils.bind(this, function()
  735. {
  736. if (file.type == 'dir')
  737. {
  738. path = file.path;
  739. selectFile();
  740. }
  741. else if (showFiles && file.type == 'file')
  742. {
  743. this.ui.hideDialog();
  744. fn(org + '/' + repo + '/' + ref + '/' + file.path);
  745. }
  746. })));
  747. mxUtils.br(div);
  748. }
  749. }))(files[i]);
  750. }
  751. });
  752. listFiles(true);
  753. if (showFiles)
  754. {
  755. listFiles(false);
  756. }
  757. }
  758. }), error);
  759. });
  760. // Adds paging for repos and branches (files limited to 1000 by API)
  761. var pageSize = 100;
  762. var selectRef = mxUtils.bind(this, function(page)
  763. {
  764. if (page == null)
  765. {
  766. div.innerHTML = '';
  767. page = 1;
  768. }
  769. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  770. '/branches?per_page=' + pageSize + '&page=' + page, null, 'GET');
  771. dlg.okButton.setAttribute('disabled', 'disabled');
  772. this.ui.spinner.spin(div, mxResources.get('loading'));
  773. this.executeRequest(req, mxUtils.bind(this, function(req)
  774. {
  775. this.ui.spinner.stop();
  776. updatePathInfo(true);
  777. var branches = JSON.parse(req.getText());
  778. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  779. {
  780. path = null;
  781. selectRepo();
  782. })));
  783. mxUtils.br(div);
  784. if (branches == null || branches.length == 0)
  785. {
  786. mxUtils.write(div, mxResources.get('noFiles'));
  787. }
  788. else
  789. {
  790. for (var i = 0; i < branches.length; i++)
  791. {
  792. (mxUtils.bind(this, function(branch)
  793. {
  794. div.appendChild(createLink(branch.name, mxUtils.bind(this, function()
  795. {
  796. ref = branch.name;
  797. path = '';
  798. selectFile();
  799. })));
  800. mxUtils.br(div);
  801. }))(branches[i]);
  802. }
  803. if (branches.length == pageSize)
  804. {
  805. var nextPage = mxUtils.bind(this, function()
  806. {
  807. if (div.scrollTop == div.scrollHeight - div.offsetHeight)
  808. {
  809. mxEvent.removeListener(div, 'scroll', nextPage);
  810. selectRef(page + 1);
  811. }
  812. });
  813. mxEvent.addListener(div, 'scroll', nextPage);
  814. }
  815. }
  816. }), error);
  817. });
  818. var selectRepo = mxUtils.bind(this, function(page)
  819. {
  820. if (page == null)
  821. {
  822. div.innerHTML = '';
  823. page = 1;
  824. }
  825. var req = new mxXmlRequest(this.baseUrl + '/user/repos?per_page=' +
  826. pageSize + '&page=' + page, null, 'GET');
  827. dlg.okButton.setAttribute('disabled', 'disabled');
  828. this.ui.spinner.spin(div, mxResources.get('loading'));
  829. this.executeRequest(req, mxUtils.bind(this, function(req)
  830. {
  831. this.ui.spinner.stop();
  832. var repos = JSON.parse(req.getText());
  833. if (repos == null || repos.length == 0)
  834. {
  835. mxUtils.write(div, mxResources.get('noFiles'));
  836. }
  837. else
  838. {
  839. div.appendChild(createLink(mxResources.get('enterValue') + '...', mxUtils.bind(this, function()
  840. {
  841. var dlg = new FilenameDialog(this.ui, 'org/repo/ref', mxResources.get('ok'), mxUtils.bind(this, function(value)
  842. {
  843. if (value != null)
  844. {
  845. this.ui.spinner.spin(div, mxResources.get('loading'));
  846. this.getFile(value, mxUtils.bind(this, function(file)
  847. {
  848. this.ui.spinner.stop();
  849. org = file.meta.org;
  850. repo = file.meta.repo;
  851. ref = file.meta.ref;
  852. if (file.meta.path != null && showFiles)
  853. {
  854. this.ui.hideDialog();
  855. fn(org + '/' + repo + '/' + ref + '/' + file.meta.path);
  856. }
  857. else
  858. {
  859. path = '';
  860. selectFile();
  861. }
  862. }), mxUtils.bind(this, function(err)
  863. {
  864. this.ui.spinner.stop();
  865. this.ui.handleError({message: mxResources.get('fileNotFound')});
  866. }));
  867. }
  868. }), mxResources.get('enterValue'));
  869. this.ui.showDialog(dlg.container, 300, 80, true, false);
  870. dlg.init();
  871. })));
  872. mxUtils.br(div);
  873. mxUtils.br(div);
  874. for (var i = 0; i < repos.length; i++)
  875. {
  876. (mxUtils.bind(this, function(repository)
  877. {
  878. div.appendChild(createLink(repository.full_name, mxUtils.bind(this, function()
  879. {
  880. org = repository.owner.login;
  881. repo = repository.name;
  882. ref = repository.default_branch;
  883. path = '';
  884. selectFile();
  885. })));
  886. mxUtils.br(div);
  887. }))(repos[i]);
  888. }
  889. }
  890. if (repos.length == pageSize)
  891. {
  892. var nextPage = mxUtils.bind(this, function()
  893. {
  894. if (div.scrollTop == div.scrollHeight - div.offsetHeight)
  895. {
  896. mxEvent.removeListener(div, 'scroll', nextPage);
  897. selectRepo(page + 1);
  898. }
  899. });
  900. mxEvent.addListener(div, 'scroll', nextPage);
  901. }
  902. }), error);
  903. });
  904. selectRepo();
  905. };
  906. /**
  907. * Checks if the client is authorized and calls the next step.
  908. */
  909. GitHubClient.prototype.logout = function()
  910. {
  911. this.clearPersistentToken();
  912. this.setUser(null);
  913. this.token = null;
  914. };