GitHubClient.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  275. if (/\.vsdx$/i.test(path) || /\.gliffy$/i.test(path) || /\.png$/i.test(path))
  276. {
  277. // Should never be null
  278. if (this.token != null)
  279. {
  280. var url = this.baseUrl + '/repos/' + org + '/' + repo +
  281. '/contents/' + path + '?ref=' + encodeURIComponent(ref) +
  282. '&token=' + this.token;
  283. var tokens = path.split('/');
  284. var name = (tokens.length > 0) ? tokens[tokens.length - 1] : path;
  285. this.ui.convertFile(url, name, null, this.extension, success, error);
  286. }
  287. else if (error != null)
  288. {
  289. error();
  290. }
  291. }
  292. else
  293. {
  294. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  295. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  296. this.executeRequest(req, mxUtils.bind(this, function(req)
  297. {
  298. try
  299. {
  300. success(this.createGitHubFile(org, repo, ref, req, asLibrary));
  301. }
  302. catch (e)
  303. {
  304. if (error != null)
  305. {
  306. error(e);
  307. }
  308. }
  309. }), error);
  310. }
  311. };
  312. /**
  313. * Translates this point by the given vector.
  314. *
  315. * @param {number} dx X-coordinate of the translation.
  316. * @param {number} dy Y-coordinate of the translation.
  317. */
  318. GitHubClient.prototype.createGitHubFile = function(org, repo, ref, req, asLibrary)
  319. {
  320. var data = JSON.parse(req.getText());
  321. var meta = {'org': org, 'repo': repo, 'ref': ref, 'name': data.name,
  322. 'path': data.path, 'sha': data.sha, 'html_url': data.html_url,
  323. 'download_url': data.download_url};
  324. var content = data.content;
  325. if (data.encoding === 'base64')
  326. {
  327. // Workaround for character encoding issues in IE10/11
  328. content = (window.atob && !mxClient.IS_IE && !mxClient.IS_IE11) ? atob(content) : Base64.decode(content);
  329. }
  330. return (asLibrary) ? new GitHubLibrary(this.ui, content, meta) : new GitHubFile(this.ui, content, meta);
  331. };
  332. /**
  333. * Translates this point by the given vector.
  334. *
  335. * @param {number} dx X-coordinate of the translation.
  336. * @param {number} dy Y-coordinate of the translation.
  337. */
  338. GitHubClient.prototype.insertLibrary = function(filename, data, success, error, folderId)
  339. {
  340. this.insertFile(filename, data, success, error, true, folderId, false);
  341. };
  342. /**
  343. * Translates this point by the given vector.
  344. *
  345. * @param {number} dx X-coordinate of the translation.
  346. * @param {number} dy Y-coordinate of the translation.
  347. */
  348. GitHubClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  349. {
  350. asLibrary = (asLibrary != null) ? asLibrary : false;
  351. var tokens = folderId.split('/');
  352. var org = tokens[0];
  353. var repo = tokens[1];
  354. var ref = tokens[2];
  355. var path = tokens.slice(3, tokens.length).join('/');
  356. if (path.length > 0)
  357. {
  358. path = path + '/';
  359. }
  360. path = path + filename;
  361. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, sha)
  362. {
  363. if (checked)
  364. {
  365. // Does not insert file here as there is another writeFile implicit via fileCreated
  366. if (!asLibrary)
  367. {
  368. success(new GitHubFile(this.ui, data, {'org': org, 'repo': repo, 'ref': ref,
  369. 'name': filename, 'path': path, 'sha': sha, isNew: true}));
  370. }
  371. else
  372. {
  373. if (!base64Encoded)
  374. {
  375. data = (window.btoa) ? btoa(data) : Base64.encode(data);
  376. }
  377. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  378. {
  379. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  380. {
  381. this.getFile(org + '/' + repo + '/' + ref + '/' + path, success, error, asLibrary);
  382. }), error);
  383. }), mxUtils.bind(this, function()
  384. {
  385. if (error != null)
  386. {
  387. error();
  388. }
  389. }));
  390. }
  391. }
  392. else if (error != null)
  393. {
  394. error();
  395. }
  396. }))
  397. };
  398. /**
  399. *
  400. */
  401. GitHubClient.prototype.showCommitDialog = function(filename, isNew, success, cancel)
  402. {
  403. // Pauses spinner while commit message dialog is shown
  404. var resume = this.ui.spinner.pause();
  405. var dlg = new FilenameDialog(this.ui, mxResources.get((isNew) ? 'addedFile' : 'updateFile',
  406. [filename]), mxResources.get('ok'), mxUtils.bind(this, function(message)
  407. {
  408. resume();
  409. success(message);
  410. }), mxResources.get('commitMessage'), null, null, null, null, mxUtils.bind(this, function()
  411. {
  412. cancel();
  413. }));
  414. this.ui.showDialog(dlg.container, 300, 80, true, false);
  415. dlg.init();
  416. };
  417. /**
  418. *
  419. */
  420. GitHubClient.prototype.writeFile = function(org, repo, ref, path, message, data, sha, success, error)
  421. {
  422. var entity =
  423. {
  424. path: path,
  425. message: message,
  426. content: data
  427. };
  428. if (sha != null)
  429. {
  430. entity.sha = sha;
  431. }
  432. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  433. '/contents/' + path + '?ref=' + encodeURIComponent(ref),
  434. JSON.stringify(entity), 'PUT');
  435. this.executeRequest(req, mxUtils.bind(this, function(req)
  436. {
  437. success(req);
  438. }), error);
  439. };
  440. /**
  441. * Translates this point by the given vector.
  442. *
  443. * @param {number} dx X-coordinate of the translation.
  444. * @param {number} dy Y-coordinate of the translation.
  445. */
  446. GitHubClient.prototype.checkExists = function(path, askReplace, fn)
  447. {
  448. this.getFile(path, mxUtils.bind(this, function(file)
  449. {
  450. if (askReplace)
  451. {
  452. var resume = this.ui.spinner.pause();
  453. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  454. {
  455. resume();
  456. fn(true, file.meta.sha);
  457. }, function()
  458. {
  459. resume();
  460. fn(false);
  461. });
  462. }
  463. else
  464. {
  465. this.ui.spinner.stop();
  466. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  467. {
  468. fn(false);
  469. });
  470. }
  471. }), mxUtils.bind(this, function(err)
  472. {
  473. fn(true);
  474. }));
  475. };
  476. /**
  477. * Translates this point by the given vector.
  478. *
  479. * @param {number} dx X-coordinate of the translation.
  480. * @param {number} dy Y-coordinate of the translation.
  481. */
  482. GitHubClient.prototype.saveFile = function(file, success, error)
  483. {
  484. var org = file.meta.org;
  485. var repo = file.meta.repo;
  486. var ref = file.meta.ref;
  487. var path = file.meta.path;
  488. this.showCommitDialog(file.meta.name, file.meta.sha == null || file.meta.isNew, mxUtils.bind(this, function(message)
  489. {
  490. var data = (window.btoa) ? btoa(file.getData()) : Base64.encode(file.getData());
  491. var fn = mxUtils.bind(this, function(sha)
  492. {
  493. this.writeFile(org, repo, ref, path, message, data, sha, mxUtils.bind(this, function(req)
  494. {
  495. delete file.meta.isNew;
  496. success(JSON.parse(req.getText()));
  497. }), mxUtils.bind(this, function(err)
  498. {
  499. // Handles special conflict case where overwrite needs an update of the sha
  500. if (err != null && err.status == 409)
  501. {
  502. resume = this.ui.spinner.pause();
  503. var dlg = new ErrorDialog(this.ui, mxResources.get('errorSavingFile'),
  504. mxResources.get('fileChangedOverwrite'), mxResources.get('cancel'), mxUtils.bind(this, function()
  505. {
  506. error();
  507. }), null, mxResources.get('overwrite'), mxUtils.bind(this, function()
  508. {
  509. resume();
  510. // Gets the latest sha and tries again
  511. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  512. {
  513. fn(tempFile.meta.sha);
  514. }));
  515. }));
  516. this.ui.showDialog(dlg.container, 340, 150, true, false);
  517. dlg.init();
  518. }
  519. else
  520. {
  521. error(err);
  522. }
  523. }));
  524. });
  525. fn(file.meta.sha);
  526. }), mxUtils.bind(this, function()
  527. {
  528. error();
  529. }));
  530. };
  531. /**
  532. * Checks if the client is authorized and calls the next step.
  533. */
  534. GitHubClient.prototype.pickLibrary = function(fn)
  535. {
  536. this.pickFile(fn);
  537. };
  538. /**
  539. * Checks if the client is authorized and calls the next step.
  540. */
  541. GitHubClient.prototype.pickFolder = function(fn)
  542. {
  543. this.showGitHubDialog(false, fn);
  544. };
  545. /**
  546. * Checks if the client is authorized and calls the next step.
  547. */
  548. GitHubClient.prototype.pickFile = function(fn)
  549. {
  550. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  551. {
  552. this.ui.loadFile('H' + encodeURIComponent(path));
  553. });
  554. this.showGitHubDialog(true, fn);
  555. };
  556. /**
  557. *
  558. */
  559. GitHubClient.prototype.showGitHubDialog = function(showFiles, fn)
  560. {
  561. var org = null;
  562. var repo = null;
  563. var ref = null;
  564. var path = null;
  565. var content = document.createElement('div');
  566. content.style.whiteSpace = 'nowrap';
  567. content.style.overflow = 'hidden';
  568. content.style.height = '224px';
  569. var hd = document.createElement('h3');
  570. mxUtils.write(hd, mxResources.get((showFiles) ? 'selectFile' : 'selectFolder'));
  571. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  572. content.appendChild(hd);
  573. var div = document.createElement('div');
  574. div.style.whiteSpace = 'nowrap';
  575. div.style.overflow = 'auto';
  576. div.style.height = '194px';
  577. content.appendChild(div);
  578. var dlg = new CustomDialog(this.ui, content, mxUtils.bind(this, function()
  579. {
  580. fn(org + '/' + repo + '/' + ref + '/' + path);
  581. }));
  582. this.ui.showDialog(dlg.container, 340, 270, true, true);
  583. if (showFiles)
  584. {
  585. dlg.okButton.parentNode.removeChild(dlg.okButton);
  586. }
  587. var updatePathInfo = mxUtils.bind(this, function(hideRef)
  588. {
  589. var pathInfo = document.createElement('div');
  590. pathInfo.style.marginBottom = '8px';
  591. var link = document.createElement('a');
  592. link.setAttribute('href', 'javascript:void(0);');
  593. mxUtils.write(link, org + '/' + repo);
  594. pathInfo.appendChild(link);
  595. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  596. {
  597. path = null;
  598. selectRepo();
  599. }));
  600. if (!hideRef)
  601. {
  602. mxUtils.write(pathInfo, ' / ');
  603. var link = document.createElement('a');
  604. link.setAttribute('href', 'javascript:void(0);');
  605. mxUtils.write(link, ref);
  606. pathInfo.appendChild(link);
  607. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  608. {
  609. path = null;
  610. selectRef();
  611. }));
  612. }
  613. if (path != null && path.length > 0)
  614. {
  615. var tokens = path.split('/');
  616. for (var i = 0; i < tokens.length; i++)
  617. {
  618. (function(index)
  619. {
  620. mxUtils.write(pathInfo, ' / ');
  621. var link = document.createElement('a');
  622. link.setAttribute('href', 'javascript:void(0);');
  623. mxUtils.write(link, tokens[index]);
  624. pathInfo.appendChild(link);
  625. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  626. {
  627. path = tokens.slice(0, index + 1).join('/');
  628. selectFile();
  629. }));
  630. })(i);
  631. }
  632. }
  633. div.appendChild(pathInfo);
  634. });
  635. var selectFile = mxUtils.bind(this, function()
  636. {
  637. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo +
  638. '/contents/' + path + '?ref=' + encodeURIComponent(ref), null, 'GET');
  639. dlg.okButton.removeAttribute('disabled');
  640. div.innerHTML = '';
  641. this.ui.spinner.spin(div, mxResources.get('loading'));
  642. this.executeRequest(req, mxUtils.bind(this, function(req)
  643. {
  644. updatePathInfo();
  645. this.ui.spinner.stop();
  646. var files = JSON.parse(req.getText());
  647. var link = document.createElement('a');
  648. link.setAttribute('href', 'javascript:void(0);');
  649. mxUtils.write(link, '../ [Up]');
  650. div.appendChild(link);
  651. mxUtils.br(div);
  652. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  653. {
  654. if (path == '')
  655. {
  656. path = null;
  657. selectRepo();
  658. }
  659. else
  660. {
  661. var tokens = path.split('/');
  662. path = tokens.slice(0, tokens.length - 1).join('/');
  663. selectFile();
  664. }
  665. }));
  666. if (files == null || files.length == 0)
  667. {
  668. mxUtils.write(div, mxResources.get('noFiles'));
  669. }
  670. else
  671. {
  672. var listFiles = mxUtils.bind(this, function(showFolders)
  673. {
  674. for (var i = 0; i < files.length; i++)
  675. {
  676. (mxUtils.bind(this, function(file)
  677. {
  678. if (showFolders == (file.type == 'dir'))
  679. {
  680. var link = document.createElement('a');
  681. link.setAttribute('href', 'javascript:void(0);');
  682. mxUtils.write(link, file.name + ((file.type == 'dir') ? '/' : ''));
  683. div.appendChild(link);
  684. mxUtils.br(div);
  685. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  686. {
  687. if (file.type == 'dir')
  688. {
  689. path = file.path;
  690. selectFile();
  691. }
  692. else if (showFiles && file.type == 'file')
  693. {
  694. this.ui.hideDialog();
  695. fn(org + '/' + repo + '/' + ref + '/' + file.path);
  696. }
  697. }));
  698. }
  699. }))(files[i]);
  700. }
  701. });
  702. listFiles(true);
  703. if (showFiles)
  704. {
  705. listFiles(false);
  706. }
  707. }
  708. }), mxUtils.bind(this, function(err)
  709. {
  710. this.ui.spinner.stop();
  711. updatePathInfo(true);
  712. this.ui.handleError(err);
  713. }));
  714. });
  715. var selectRef = mxUtils.bind(this, function()
  716. {
  717. var req = new mxXmlRequest(this.baseUrl + '/repos/' + org + '/' + repo + '/branches', null, 'GET');
  718. dlg.okButton.setAttribute('disabled', 'disabled');
  719. div.innerHTML = '';
  720. this.ui.spinner.spin(div, mxResources.get('loading'));
  721. this.executeRequest(req, mxUtils.bind(this, function(req)
  722. {
  723. this.ui.spinner.stop();
  724. updatePathInfo(true);
  725. var branches = JSON.parse(req.getText());
  726. var link = document.createElement('a');
  727. link.setAttribute('href', 'javascript:void(0);');
  728. mxUtils.write(link, '../ [Up]');
  729. div.appendChild(link);
  730. mxUtils.br(div);
  731. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  732. {
  733. path = null;
  734. selectRepo();
  735. }));
  736. if (branches == null || branches.length == 0)
  737. {
  738. mxUtils.write(div, mxResources.get('noFiles'));
  739. }
  740. else
  741. {
  742. for (var i = 0; i < branches.length; i++)
  743. {
  744. (mxUtils.bind(this, function(branch)
  745. {
  746. var link = document.createElement('a');
  747. link.setAttribute('href', 'javascript:void(0);');
  748. mxUtils.write(link, branch.name);
  749. div.appendChild(link);
  750. mxUtils.br(div);
  751. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  752. {
  753. ref = branch.name;
  754. path = '';
  755. selectFile();
  756. }));
  757. }))(branches[i]);
  758. }
  759. }
  760. }), mxUtils.bind(this, function(err)
  761. {
  762. this.ui.spinner.stop();
  763. updatePathInfo(true);
  764. this.ui.handleError(err);
  765. }));
  766. });
  767. var selectRepo = mxUtils.bind(this, function()
  768. {
  769. var req = new mxXmlRequest(this.baseUrl + '/user/repos', null, 'GET');
  770. dlg.okButton.setAttribute('disabled', 'disabled');
  771. div.innerHTML = '';
  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. var repos = JSON.parse(req.getText());
  777. if (repos == null || repos.length == 0)
  778. {
  779. mxUtils.write(div, mxResources.get('noFiles'));
  780. }
  781. else
  782. {
  783. for (var i = 0; i < repos.length; i++)
  784. {
  785. (mxUtils.bind(this, function(repository)
  786. {
  787. var link = document.createElement('a');
  788. link.setAttribute('href', 'javascript:void(0);');
  789. mxUtils.write(link, repository.full_name);
  790. div.appendChild(link);
  791. mxUtils.br(div);
  792. mxEvent.addListener(link, 'click', mxUtils.bind(this, function()
  793. {
  794. org = repository.owner.login;
  795. repo = repository.name;
  796. ref = repository.default_branch;
  797. path = '';
  798. selectFile();
  799. }));
  800. }))(repos[i]);
  801. }
  802. }
  803. }), mxUtils.bind(this, function(err)
  804. {
  805. this.ui.spinner.stop();
  806. this.ui.handleError(err);
  807. }));
  808. });
  809. selectRepo();
  810. };
  811. /**
  812. * Checks if the client is authorized and calls the next step.
  813. */
  814. GitHubClient.prototype.logout = function()
  815. {
  816. this.setUser(null);
  817. this.clearPersistentToken();
  818. this.token = null;
  819. };