GitHubClient.js 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 + '/contents/' +
  316. path + '?ref=' + ref + '&token=' + this.token;
  317. var tokens = path.split('/');
  318. var name = (tokens.length > 0) ? tokens[tokens.length - 1] : path;
  319. this.ui.convertFile(url, name, null, this.extension, success, error);
  320. }
  321. else
  322. {
  323. error({message: mxResources.get('accessDenied')});
  324. }
  325. }
  326. else
  327. {
  328. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  329. '/contents/' + path + '?ref=' + ref, null, 'GET');
  330. this.executeRequest(req, mxUtils.bind(this, function(req)
  331. {
  332. try
  333. {
  334. success(this.createGitHubFile(org, repo, ref, JSON.parse(req.getText()), asLibrary));
  335. }
  336. catch (e)
  337. {
  338. error(e);
  339. }
  340. }), error);
  341. }
  342. };
  343. /**
  344. * Translates this point by the given vector.
  345. *
  346. * @param {number} dx X-coordinate of the translation.
  347. * @param {number} dy Y-coordinate of the translation.
  348. */
  349. GitHubClient.prototype.createGitHubFile = function(org, repo, ref, data, asLibrary)
  350. {
  351. var meta = {'org': org, 'repo': repo, 'ref': ref, 'name': data.name,
  352. 'path': data.path, 'sha': data.sha, 'html_url': data.html_url,
  353. 'download_url': data.download_url};
  354. var content = data.content;
  355. if (data.encoding === 'base64')
  356. {
  357. if (/\.jpe?g$/i.test(data.name))
  358. {
  359. content = 'data:image/jpeg;base64,' + content;
  360. }
  361. else if (/\.gif$/i.test(data.name))
  362. {
  363. content = 'data:image/gif;base64,' + content;
  364. }
  365. else
  366. {
  367. content = Base64.decode(content);
  368. }
  369. }
  370. return (asLibrary) ? new GitHubLibrary(this.ui, content, meta) : new GitHubFile(this.ui, content, meta);
  371. };
  372. /**
  373. * Translates this point by the given vector.
  374. *
  375. * @param {number} dx X-coordinate of the translation.
  376. * @param {number} dy Y-coordinate of the translation.
  377. */
  378. GitHubClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  379. {
  380. this.insertFile(filename, data, success, error, true, folderId, false);
  381. };
  382. /**
  383. * Translates this point by the given vector.
  384. *
  385. * @param {number} dx X-coordinate of the translation.
  386. * @param {number} dy Y-coordinate of the translation.
  387. */
  388. GitHubClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  389. {
  390. asLibrary = (asLibrary != null) ? asLibrary : false;
  391. var tokens = folderId.split('/');
  392. var org = tokens[0];
  393. var repo = tokens[1];
  394. var ref = tokens[2];
  395. var path = tokens.slice(3, tokens.length).join('/');
  396. if (path.length > 0)
  397. {
  398. path = path + '/';
  399. }
  400. path = path + filename;
  401. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, sha)
  402. {
  403. if (checked)
  404. {
  405. // Does not insert file here as there is another writeFile implicit via fileCreated
  406. if (!asLibrary)
  407. {
  408. success(new GitHubFile(this.ui, data, {'org': org, 'repo': repo, 'ref': ref,
  409. 'name': filename, 'path': path, 'sha': sha, isNew: true}));
  410. }
  411. else
  412. {
  413. if (!base64Encoded)
  414. {
  415. data = Base64.encode(data);
  416. }
  417. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  418. {
  419. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  420. {
  421. try
  422. {
  423. var msg = JSON.parse(req.getText());
  424. success(this.createGitHubFile(org, repo, ref, msg.content, asLibrary));
  425. }
  426. catch (e)
  427. {
  428. error(e);
  429. }
  430. }), error);
  431. }), error);
  432. }
  433. }
  434. else
  435. {
  436. error();
  437. }
  438. }))
  439. };
  440. /**
  441. *
  442. */
  443. GitHubClient.prototype.showCommitDialog = function(filename, isNew, success, cancel)
  444. {
  445. // Pauses spinner while commit message dialog is shown
  446. var resume = this.ui.spinner.pause();
  447. var dlg = new FilenameDialog(this.ui, mxResources.get((isNew) ? 'addedFile' : 'updateFile',
  448. [filename]), mxResources.get('ok'), mxUtils.bind(this, function(message)
  449. {
  450. resume();
  451. success(message);
  452. }), mxResources.get('commitMessage'), null, null, null, null, mxUtils.bind(this, function()
  453. {
  454. cancel();
  455. }));
  456. this.ui.showDialog(dlg.container, 300, 80, true, false);
  457. dlg.init();
  458. };
  459. /**
  460. *
  461. */
  462. GitHubClient.prototype.writeFile = function(org, repo, ref, path, message, data, sha, success, error)
  463. {
  464. if (data.length >= this.maxFileSize)
  465. {
  466. error({message: mxResources.get('drawingTooLarge') + ' (' +
  467. this.ui.formatFileSize(data.length) + ' / 1 MB)'});
  468. }
  469. else
  470. {
  471. var entity =
  472. {
  473. path: path,
  474. branch: decodeURIComponent(ref),
  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, JSON.stringify(entity), 'PUT');
  484. this.executeRequest(req, mxUtils.bind(this, function(req)
  485. {
  486. success(req);
  487. }), error);
  488. }
  489. };
  490. /**
  491. * Translates this point by the given vector.
  492. *
  493. * @param {number} dx X-coordinate of the translation.
  494. * @param {number} dy Y-coordinate of the translation.
  495. */
  496. GitHubClient.prototype.checkExists = function(path, askReplace, fn)
  497. {
  498. this.getFile(path, mxUtils.bind(this, function(file)
  499. {
  500. if (askReplace && file.meta != null)
  501. {
  502. var resume = this.ui.spinner.pause();
  503. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  504. {
  505. resume();
  506. fn(true, file.meta.sha);
  507. }, function()
  508. {
  509. resume();
  510. fn(false);
  511. });
  512. }
  513. else
  514. {
  515. this.ui.spinner.stop();
  516. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  517. {
  518. fn(false);
  519. });
  520. }
  521. }), mxUtils.bind(this, function(err)
  522. {
  523. fn(true);
  524. }));
  525. };
  526. /**
  527. * Translates this point by the given vector.
  528. *
  529. * @param {number} dx X-coordinate of the translation.
  530. * @param {number} dy Y-coordinate of the translation.
  531. */
  532. GitHubClient.prototype.saveFile = function(file, success, error)
  533. {
  534. var org = file.meta.org;
  535. var repo = file.meta.repo;
  536. var ref = file.meta.ref;
  537. var path = file.meta.path;
  538. this.showCommitDialog(file.meta.name, file.meta.sha == null || file.meta.isNew, mxUtils.bind(this, function(message)
  539. {
  540. var data = Base64.encode(file.getData());
  541. var fn = mxUtils.bind(this, function(sha)
  542. {
  543. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  544. {
  545. delete file.meta.isNew;
  546. success(JSON.parse(req.getText()));
  547. }), mxUtils.bind(this, function(err)
  548. {
  549. // Handles special conflict case where overwrite needs an update of the sha
  550. if (err != null && err.status == 409)
  551. {
  552. resume = this.ui.spinner.pause();
  553. var dlg = new ErrorDialog(this.ui, mxResources.get('errorSavingFile'),
  554. mxResources.get('fileChangedOverwrite'), mxResources.get('cancel'), mxUtils.bind(this, function()
  555. {
  556. error();
  557. }), null, mxResources.get('overwrite'), mxUtils.bind(this, function()
  558. {
  559. resume();
  560. // Gets the latest sha and tries again
  561. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  562. {
  563. fn(tempFile.meta.sha);
  564. }), mxUtils.bind(this, function()
  565. {
  566. fn(null);
  567. }));
  568. }));
  569. this.ui.showDialog(dlg.container, 340, 150, true, false);
  570. dlg.init();
  571. }
  572. else
  573. {
  574. error(err);
  575. }
  576. }));
  577. });
  578. fn(file.meta.sha);
  579. }), mxUtils.bind(this, function()
  580. {
  581. error();
  582. }));
  583. };
  584. /**
  585. * Checks if the client is authorized and calls the next step.
  586. */
  587. GitHubClient.prototype.pickLibrary = function(fn)
  588. {
  589. this.pickFile(fn);
  590. };
  591. /**
  592. * Checks if the client is authorized and calls the next step.
  593. */
  594. GitHubClient.prototype.pickFolder = function(fn)
  595. {
  596. this.showGitHubDialog(false, fn);
  597. };
  598. /**
  599. * Checks if the client is authorized and calls the next step.
  600. */
  601. GitHubClient.prototype.pickFile = function(fn)
  602. {
  603. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  604. {
  605. this.ui.loadFile('H' + encodeURIComponent(path));
  606. });
  607. this.showGitHubDialog(true, fn);
  608. };
  609. /**
  610. *
  611. */
  612. GitHubClient.prototype.showGitHubDialog = function(showFiles, fn)
  613. {
  614. var org = null;
  615. var repo = null;
  616. var ref = null;
  617. var path = null;
  618. var content = document.createElement('div');
  619. content.style.whiteSpace = 'nowrap';
  620. content.style.overflow = 'hidden';
  621. content.style.height = '224px';
  622. var hd = document.createElement('h3');
  623. mxUtils.write(hd, mxResources.get((showFiles) ? 'selectFile' : 'selectFolder'));
  624. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  625. content.appendChild(hd);
  626. var div = document.createElement('div');
  627. div.style.whiteSpace = 'nowrap';
  628. div.style.overflow = 'auto';
  629. div.style.height = '194px';
  630. content.appendChild(div);
  631. var dlg = new CustomDialog(this.ui, content, mxUtils.bind(this, function()
  632. {
  633. fn(org + '/' + repo + '/' + encodeURIComponent(ref) + '/' + path);
  634. }));
  635. this.ui.showDialog(dlg.container, 340, 270, true, true);
  636. if (showFiles)
  637. {
  638. dlg.okButton.parentNode.removeChild(dlg.okButton);
  639. }
  640. var createLink = mxUtils.bind(this, function(label, fn)
  641. {
  642. var link = document.createElement('a');
  643. link.setAttribute('href', 'javascript:void(0);');
  644. mxUtils.write(link, label);
  645. mxEvent.addListener(link, 'click', fn);
  646. return link;
  647. });
  648. var updatePathInfo = mxUtils.bind(this, function(hideRef)
  649. {
  650. var pathInfo = document.createElement('div');
  651. pathInfo.style.marginBottom = '8px';
  652. pathInfo.appendChild(createLink(org + '/' + repo, mxUtils.bind(this, function()
  653. {
  654. path = null;
  655. selectRepo();
  656. })));
  657. if (!hideRef)
  658. {
  659. mxUtils.write(pathInfo, ' / ');
  660. pathInfo.appendChild(createLink(decodeURIComponent(ref), mxUtils.bind(this, function()
  661. {
  662. path = null;
  663. selectRef();
  664. })));
  665. }
  666. if (path != null && path.length > 0)
  667. {
  668. var tokens = path.split('/');
  669. for (var i = 0; i < tokens.length; i++)
  670. {
  671. (function(index)
  672. {
  673. mxUtils.write(pathInfo, ' / ');
  674. pathInfo.appendChild(createLink(tokens[index], mxUtils.bind(this, function()
  675. {
  676. path = tokens.slice(0, index + 1).join('/');
  677. selectFile();
  678. })));
  679. })(i);
  680. }
  681. }
  682. div.appendChild(pathInfo);
  683. });
  684. var error = mxUtils.bind(this, function(err)
  685. {
  686. this.ui.handleError(err, null, mxUtils.bind(this, function()
  687. {
  688. this.ui.spinner.stop();
  689. if (this.getUser() != null)
  690. {
  691. org = null;
  692. repo = null;
  693. ref = null;
  694. path = null;
  695. selectRepo();
  696. }
  697. else
  698. {
  699. this.ui.hideDialog();
  700. }
  701. }));
  702. });
  703. var selectFile = mxUtils.bind(this, function()
  704. {
  705. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  706. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  707. dlg.okButton.removeAttribute('disabled');
  708. div.innerHTML = '';
  709. this.ui.spinner.spin(div, mxResources.get('loading'));
  710. this.executeRequest(req, mxUtils.bind(this, function(req)
  711. {
  712. updatePathInfo();
  713. this.ui.spinner.stop();
  714. var files = JSON.parse(req.getText());
  715. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  716. {
  717. if (path == '')
  718. {
  719. path = null;
  720. selectRepo();
  721. }
  722. else
  723. {
  724. var tokens = path.split('/');
  725. path = tokens.slice(0, tokens.length - 1).join('/');
  726. selectFile();
  727. }
  728. })));
  729. mxUtils.br(div);
  730. if (files == null || files.length == 0)
  731. {
  732. mxUtils.write(div, mxResources.get('noFiles'));
  733. }
  734. else
  735. {
  736. var listFiles = mxUtils.bind(this, function(showFolders)
  737. {
  738. for (var i = 0; i < files.length; i++)
  739. {
  740. (mxUtils.bind(this, function(file)
  741. {
  742. if (showFolders == (file.type == 'dir'))
  743. {
  744. div.appendChild(createLink(file.name + ((file.type == 'dir') ? '/' : ''), mxUtils.bind(this, function()
  745. {
  746. if (file.type == 'dir')
  747. {
  748. path = file.path;
  749. selectFile();
  750. }
  751. else if (showFiles && file.type == 'file')
  752. {
  753. this.ui.hideDialog();
  754. fn(org + '/' + repo + '/' + encodeURIComponent(ref) + '/' + file.path);
  755. }
  756. })));
  757. mxUtils.br(div);
  758. }
  759. }))(files[i]);
  760. }
  761. });
  762. listFiles(true);
  763. if (showFiles)
  764. {
  765. listFiles(false);
  766. }
  767. }
  768. }), error);
  769. });
  770. // Adds paging for repos and branches (files limited to 1000 by API)
  771. var pageSize = 100;
  772. var selectRef = mxUtils.bind(this, function(page)
  773. {
  774. if (page == null)
  775. {
  776. div.innerHTML = '';
  777. page = 1;
  778. }
  779. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  780. '/branches?per_page=' + pageSize + '&page=' + page, null, 'GET');
  781. dlg.okButton.setAttribute('disabled', 'disabled');
  782. this.ui.spinner.spin(div, mxResources.get('loading'));
  783. this.executeRequest(req, mxUtils.bind(this, function(req)
  784. {
  785. this.ui.spinner.stop();
  786. updatePathInfo(true);
  787. var branches = JSON.parse(req.getText());
  788. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  789. {
  790. path = null;
  791. selectRepo();
  792. })));
  793. mxUtils.br(div);
  794. if (branches == null || branches.length == 0)
  795. {
  796. mxUtils.write(div, mxResources.get('noFiles'));
  797. }
  798. else
  799. {
  800. for (var i = 0; i < branches.length; i++)
  801. {
  802. (mxUtils.bind(this, function(branch)
  803. {
  804. div.appendChild(createLink(branch.name, mxUtils.bind(this, function()
  805. {
  806. ref = branch.name;
  807. path = '';
  808. selectFile();
  809. })));
  810. mxUtils.br(div);
  811. }))(branches[i]);
  812. }
  813. if (branches.length == pageSize)
  814. {
  815. var nextPage = mxUtils.bind(this, function()
  816. {
  817. if (div.scrollTop == div.scrollHeight - div.offsetHeight)
  818. {
  819. mxEvent.removeListener(div, 'scroll', nextPage);
  820. selectRef(page + 1);
  821. }
  822. });
  823. mxEvent.addListener(div, 'scroll', nextPage);
  824. }
  825. }
  826. }), error);
  827. });
  828. var selectRepo = mxUtils.bind(this, function(page)
  829. {
  830. if (page == null)
  831. {
  832. div.innerHTML = '';
  833. page = 1;
  834. }
  835. var req = new mxXmlRequest(this.baseUrl + '/user/repos?per_page=' +
  836. pageSize + '&page=' + page, null, 'GET');
  837. dlg.okButton.setAttribute('disabled', 'disabled');
  838. this.ui.spinner.spin(div, mxResources.get('loading'));
  839. this.executeRequest(req, mxUtils.bind(this, function(req)
  840. {
  841. this.ui.spinner.stop();
  842. var repos = JSON.parse(req.getText());
  843. if (repos == null || repos.length == 0)
  844. {
  845. mxUtils.write(div, mxResources.get('noFiles'));
  846. }
  847. else
  848. {
  849. div.appendChild(createLink(mxResources.get('enterValue') + '...', mxUtils.bind(this, function()
  850. {
  851. var dlg = new FilenameDialog(this.ui, 'org/repo/ref', mxResources.get('ok'), mxUtils.bind(this, function(value)
  852. {
  853. if (value != null)
  854. {
  855. var tokens = value.split('/');
  856. if (tokens.length > 1 && this.ui.spinner.spin(div, mxResources.get('loading')))
  857. {
  858. var tmpOrg = tokens[0];
  859. var tmpRepo = tokens[1];
  860. var tmpRef = encodeURIComponent(tokens.slice(2, tokens.length).join('/'));
  861. this.getFile(tmpOrg + '/' + tmpRepo + '/' + tmpRef, mxUtils.bind(this, function(file)
  862. {
  863. this.ui.spinner.stop();
  864. org = file.meta.org;
  865. repo = file.meta.repo;
  866. ref = decodeURIComponent(file.meta.ref);
  867. path = '';
  868. selectFile();
  869. }), mxUtils.bind(this, function(err)
  870. {
  871. this.ui.spinner.stop();
  872. this.ui.handleError({message: mxResources.get('fileNotFound')});
  873. }));
  874. }
  875. else
  876. {
  877. this.ui.spinner.stop();
  878. this.ui.handleError({message: mxResources.get('invalidName')});
  879. }
  880. }
  881. }), mxResources.get('enterValue'));
  882. this.ui.showDialog(dlg.container, 300, 80, true, false);
  883. dlg.init();
  884. })));
  885. mxUtils.br(div);
  886. mxUtils.br(div);
  887. for (var i = 0; i < repos.length; i++)
  888. {
  889. (mxUtils.bind(this, function(repository)
  890. {
  891. div.appendChild(createLink(repository.full_name, mxUtils.bind(this, function()
  892. {
  893. org = repository.owner.login;
  894. repo = repository.name;
  895. ref = repository.default_branch;
  896. path = '';
  897. selectFile();
  898. })));
  899. mxUtils.br(div);
  900. }))(repos[i]);
  901. }
  902. }
  903. if (repos.length == pageSize)
  904. {
  905. var nextPage = mxUtils.bind(this, function()
  906. {
  907. if (div.scrollTop == div.scrollHeight - div.offsetHeight)
  908. {
  909. mxEvent.removeListener(div, 'scroll', nextPage);
  910. selectRepo(page + 1);
  911. }
  912. });
  913. mxEvent.addListener(div, 'scroll', nextPage);
  914. }
  915. }), error);
  916. });
  917. selectRepo();
  918. };
  919. /**
  920. * Checks if the client is authorized and calls the next step.
  921. */
  922. GitHubClient.prototype.logout = function()
  923. {
  924. this.clearPersistentToken();
  925. this.setUser(null);
  926. this.token = null;
  927. };