GitHubClient.js 26 KB

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