GitHubClient.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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, checkExists)
  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 (!checkExists && (/\.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. }), null, true);
  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)
  857. {
  858. var tmpOrg = tokens[0];
  859. var tmpRepo = tokens[1];
  860. if (tokens.length < 3)
  861. {
  862. org = tmpOrg;
  863. repo = tmpRepo;
  864. ref = null;
  865. path = null;
  866. selectRef();
  867. }
  868. else if (this.ui.spinner.spin(div, mxResources.get('loading')))
  869. {
  870. var tmpRef = encodeURIComponent(tokens.slice(2, tokens.length).join('/'));
  871. this.getFile(tmpOrg + '/' + tmpRepo + '/' + tmpRef, mxUtils.bind(this, function(file)
  872. {
  873. this.ui.spinner.stop();
  874. org = file.meta.org;
  875. repo = file.meta.repo;
  876. ref = decodeURIComponent(file.meta.ref);
  877. path = '';
  878. selectFile();
  879. }), mxUtils.bind(this, function(err)
  880. {
  881. this.ui.spinner.stop();
  882. this.ui.handleError({message: mxResources.get('fileNotFound')});
  883. }));
  884. }
  885. }
  886. else
  887. {
  888. this.ui.spinner.stop();
  889. this.ui.handleError({message: mxResources.get('invalidName')});
  890. }
  891. }
  892. }), mxResources.get('enterValue'));
  893. this.ui.showDialog(dlg.container, 300, 80, true, false);
  894. dlg.init();
  895. })));
  896. mxUtils.br(div);
  897. mxUtils.br(div);
  898. for (var i = 0; i < repos.length; i++)
  899. {
  900. (mxUtils.bind(this, function(repository)
  901. {
  902. div.appendChild(createLink(repository.full_name, mxUtils.bind(this, function()
  903. {
  904. org = repository.owner.login;
  905. repo = repository.name;
  906. ref = repository.default_branch;
  907. path = '';
  908. selectFile();
  909. })));
  910. mxUtils.br(div);
  911. }))(repos[i]);
  912. }
  913. }
  914. if (repos.length == pageSize)
  915. {
  916. var nextPage = mxUtils.bind(this, function()
  917. {
  918. if (div.scrollTop == div.scrollHeight - div.offsetHeight)
  919. {
  920. mxEvent.removeListener(div, 'scroll', nextPage);
  921. selectRepo(page + 1);
  922. }
  923. });
  924. mxEvent.addListener(div, 'scroll', nextPage);
  925. }
  926. }), error);
  927. });
  928. selectRepo();
  929. };
  930. /**
  931. * Checks if the client is authorized and calls the next step.
  932. */
  933. GitHubClient.prototype.logout = function()
  934. {
  935. this.clearPersistentToken();
  936. this.setUser(null);
  937. this.token = null;
  938. };