GitLabClient.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. /**
  2. * Copyright (c) 2006-2024, JGraph Ltd
  3. * Copyright (c) 2006-2024, draw.io AG
  4. */
  5. //Add a closure to hide the class private variables without changing the code a lot
  6. (function()
  7. {
  8. var _token = null;
  9. window.GitLabClient = function(editorUi)
  10. {
  11. GitHubClient.call(this, editorUi, 'gitlabauth');
  12. };
  13. // Extends DrawioClient
  14. mxUtils.extend(GitLabClient, GitHubClient);
  15. /**
  16. * Gitlab Client ID, see https://gitlab.com/oauth/applications/135239
  17. */
  18. GitLabClient.prototype.clientId = DRAWIO_GITLAB_ID;
  19. /**
  20. * OAuth scope.
  21. */
  22. GitLabClient.prototype.scope = 'api%20read_repository%20write_repository';
  23. /**
  24. * Base URL for API calls.
  25. */
  26. GitLabClient.prototype.baseUrl = DRAWIO_GITLAB_URL + '/api/v4';
  27. /**
  28. * Maximum file size of the GitLab REST API.
  29. */
  30. GitLabClient.prototype.maxFileSize = 10000000 /*10MB*/;
  31. /**
  32. * Name for the auth token header.
  33. */
  34. GitLabClient.prototype.authToken = 'Bearer';
  35. GitLabClient.prototype.redirectUri = window.DRAWIO_SERVER_URL + 'gitlab';
  36. /**
  37. * Authorizes the client, gets the userId and calls <open>.
  38. */
  39. GitLabClient.prototype.authenticate = function(success, error)
  40. {
  41. var req = new mxXmlRequest(this.redirectUri + '?getState=1', null, 'GET');
  42. req.send(mxUtils.bind(this, function(req)
  43. {
  44. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  45. {
  46. this.authenticateStep2(req.getText(), success, error);
  47. }
  48. else if (error != null)
  49. {
  50. error(req);
  51. }
  52. }), error);
  53. };
  54. GitLabClient.prototype.authenticateStep2 = function(state, success, error)
  55. {
  56. if (window.onGitLabCallback == null)
  57. {
  58. var auth = mxUtils.bind(this, function()
  59. {
  60. var acceptAuthResponse = true;
  61. var authRemembered = this.getPersistentToken(true);
  62. if (authRemembered != null)
  63. {
  64. var req = new mxXmlRequest(this.redirectUri + '?state=' + encodeURIComponent('cId=' + this.clientId + '&domain=' + window.location.host + '&token=' + state), null, 'GET'); //To identify which app/domain is used
  65. req.send(mxUtils.bind(this, function(req)
  66. {
  67. if (req.getStatus() >= 200 && req.getStatus() <= 299)
  68. {
  69. try
  70. {
  71. _token = JSON.parse(req.getText()).access_token;
  72. this.setToken(_token);
  73. this.setUser(null);
  74. success();
  75. }
  76. catch (e)
  77. {
  78. error({message: mxResources.get('authFailed'), retry: auth});
  79. }
  80. }
  81. else
  82. {
  83. this.clearPersistentToken();
  84. this.setUser(null);
  85. _token = null;
  86. this.setToken(null);
  87. if (req.getStatus() == 401) // (Unauthorized) [e.g, invalid refresh token]
  88. {
  89. auth();
  90. }
  91. else
  92. {
  93. error({message: mxResources.get('accessDenied'), retry: auth});
  94. }
  95. }
  96. }), error);
  97. }
  98. else
  99. {
  100. this.ui.showAuthDialog(this, true, mxUtils.bind(this, function(remember, authSuccess)
  101. {
  102. var win = window.open(DRAWIO_GITLAB_URL + '/oauth/authorize?client_id=' +
  103. this.clientId + '&scope=' + this.scope +
  104. '&redirect_uri=' + encodeURIComponent(this.redirectUri) +
  105. '&response_type=code&state=' + encodeURIComponent('cId=' + this.clientId + //To identify which app/domain is used
  106. '&domain=' + window.location.host + '&token=' + state) , 'gitlabauth');
  107. if (win != null)
  108. {
  109. window.onGitLabCallback = mxUtils.bind(this, function(newAuthInfo, authWindow)
  110. {
  111. if (acceptAuthResponse)
  112. {
  113. window.onGitLabCallback = null;
  114. acceptAuthResponse = false;
  115. if (newAuthInfo == null)
  116. {
  117. error({message: mxResources.get('accessDenied'), retry: auth});
  118. }
  119. else
  120. {
  121. if (authSuccess != null)
  122. {
  123. authSuccess();
  124. }
  125. _token = newAuthInfo.access_token;
  126. this.setToken(_token);
  127. this.setUser(null);
  128. if (remember)
  129. {
  130. this.setPersistentToken('remembered');
  131. }
  132. success();
  133. if (authWindow != null)
  134. {
  135. authWindow.close();
  136. }
  137. }
  138. }
  139. else if (authWindow != null)
  140. {
  141. authWindow.close();
  142. }
  143. });
  144. }
  145. else
  146. {
  147. error({message: mxResources.get('serviceUnavailableOrBlocked'), retry: auth});
  148. }
  149. }), mxUtils.bind(this, function()
  150. {
  151. if (acceptAuthResponse)
  152. {
  153. window.onGitLabCallback = null;
  154. acceptAuthResponse = false;
  155. error({message: mxResources.get('accessDenied'), retry: auth});
  156. }
  157. }));
  158. }
  159. });
  160. auth();
  161. }
  162. else
  163. {
  164. error({code: App.ERROR_BUSY});
  165. }
  166. };
  167. /**
  168. * Authorizes the client, gets the userId and calls <open>.
  169. */
  170. GitLabClient.prototype.executeRequest = function(req, success, error, ignoreNotFound)
  171. {
  172. var doExecute = mxUtils.bind(this, function(failOnAuth)
  173. {
  174. var acceptResponse = true;
  175. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  176. {
  177. acceptResponse = false;
  178. error({code: App.ERROR_TIMEOUT, message: mxResources.get('timeout')});
  179. }), this.ui.timeout);
  180. var temp = this.authToken + ' ' + _token;
  181. req.setRequestHeaders = function(request, params)
  182. {
  183. request.setRequestHeader('Authorization', temp);
  184. request.setRequestHeader('PRIVATE_TOKEN', temp);
  185. request.setRequestHeader('Content-Type', 'application/json');
  186. };
  187. req.send(mxUtils.bind(this, function()
  188. {
  189. window.clearTimeout(timeoutThread);
  190. if (acceptResponse)
  191. {
  192. if ((req.getStatus() >= 200 && req.getStatus() <= 299) ||
  193. (ignoreNotFound && req.getStatus() == 404))
  194. {
  195. success(req);
  196. }
  197. else if (req.getStatus() === 401)
  198. {
  199. if (!failOnAuth)
  200. {
  201. this.authenticate(function()
  202. {
  203. doExecute(true);
  204. }, error);
  205. }
  206. else
  207. {
  208. error({message: mxResources.get('accessDenied'), retry: mxUtils.bind(this, function()
  209. {
  210. this.authenticate(function()
  211. {
  212. fn(true);
  213. }, error);
  214. })});
  215. }
  216. }
  217. else if (req.getStatus() === 403)
  218. {
  219. var tooLarge = false;
  220. try
  221. {
  222. var temp = JSON.parse(req.getText());
  223. if (temp != null && temp.errors != null && temp.errors.length > 0)
  224. {
  225. tooLarge = temp.errors[0].code == 'too_large';
  226. }
  227. }
  228. catch (e)
  229. {
  230. // ignore
  231. }
  232. error({message: mxResources.get((tooLarge) ? 'drawingTooLarge' : 'forbidden')});
  233. }
  234. else if (req.getStatus() === 404)
  235. {
  236. error({message: this.getErrorMessage(req, mxResources.get('fileNotFound'))});
  237. }
  238. else
  239. {
  240. error({status: req.getStatus(), message: this.getErrorMessage(req,
  241. mxResources.get('error') + ' ' + req.getStatus())});
  242. }
  243. }
  244. }), mxUtils.bind(this, function(err)
  245. {
  246. window.clearTimeout(timeoutThread);
  247. if (acceptResponse)
  248. {
  249. error(err);
  250. }
  251. }));
  252. });
  253. var fn = mxUtils.bind(this, function(failOnAuth)
  254. {
  255. if (this.user == null)
  256. {
  257. this.updateUser(function()
  258. {
  259. fn(true);
  260. }, error, failOnAuth);
  261. }
  262. else
  263. {
  264. doExecute(failOnAuth);
  265. }
  266. });
  267. if (_token == null)
  268. {
  269. this.authenticate(function()
  270. {
  271. fn(true);
  272. }, error);
  273. }
  274. else
  275. {
  276. fn(false);
  277. }
  278. };
  279. /**
  280. * Finds index of ref in given token list. This is required to support groups and subgroups.
  281. */
  282. GitLabClient.prototype.getRefIndex = function(tokens, isFolder, success, error, knownRefPos, checkRepo)
  283. {
  284. if (knownRefPos != null)
  285. {
  286. success(tokens, knownRefPos);
  287. }
  288. else
  289. {
  290. var refPos = tokens.length - 2;
  291. // Finds ref in token list by checking which URL works
  292. var checkUrl = mxUtils.bind(this, function()
  293. {
  294. if (refPos < 2)
  295. {
  296. error({message: mxResources.get('fileNotFound')});
  297. }
  298. else
  299. {
  300. var repoPos = Math.max(refPos - 1, 0);
  301. var org = tokens.slice(0, repoPos).join('/');
  302. var repo = tokens[repoPos];
  303. var ref = tokens[refPos];
  304. var path = tokens.slice(refPos + 1, tokens.length).join('/');
  305. var url = this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) + '/repository/' +
  306. (!isFolder ? 'files/' + encodeURIComponent(path) + '?ref=' + ref : (checkRepo ?
  307. 'branches?per_page=1&page=1&ref=' + ref : 'tree?path=' + path + '&ref=' + ref));
  308. var req = new mxXmlRequest(url, null, 'HEAD');
  309. this.executeRequest(req, mxUtils.bind(this, function()
  310. {
  311. if (req.getStatus() == 200)
  312. {
  313. success(tokens, refPos);
  314. }
  315. else
  316. {
  317. error({message: mxResources.get('fileNotFound')});
  318. }
  319. }), mxUtils.bind(this, function()
  320. {
  321. if (req.getStatus() == 404)
  322. {
  323. refPos--;
  324. checkUrl();
  325. }
  326. else
  327. {
  328. error({message: mxResources.get('fileNotFound')});
  329. }
  330. }));
  331. }
  332. });
  333. checkUrl();
  334. }
  335. };
  336. /**
  337. * Checks if the client is authorized and calls the next step.
  338. */
  339. GitLabClient.prototype.getFile = function(path, success, error, asLibrary, checkExists, knownRefPos)
  340. {
  341. asLibrary = (asLibrary != null) ? asLibrary : false;
  342. this.getRefIndex(path.split('/'), false, mxUtils.bind(this, function(tokens, refPos)
  343. {
  344. var repoPos = Math.max(refPos - 1, 0);
  345. var org = tokens.slice(0, repoPos).join('/');
  346. var repo = tokens[repoPos];
  347. var ref = tokens[refPos];
  348. path = tokens.slice(refPos + 1, tokens.length).join('/');
  349. var binary = /\.png$/i.test(path);
  350. // Handles .vsdx, Gliffy and PNG+XML files by creating a temporary file
  351. if (!checkExists && (/\.v(dx|sdx?)$/i.test(path) || /\.gliffy$/i.test(path) ||
  352. /\.pdf$/i.test(path) || (!this.ui.useCanvasForExport && binary)))
  353. {
  354. // Should never be null
  355. if (_token != null)
  356. {
  357. // Adds random parameter to bypass cache
  358. var rnd = '&t=' + new Date().getTime();
  359. var url = this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) +
  360. '/repository/files/' + encodeURIComponent(path) + '?ref=' + ref;
  361. var tokens = path.split('/');
  362. var name = (tokens.length > 0) ? tokens[tokens.length - 1] : path;
  363. this.ui.convertFile(url + rnd, name, null, this.extension, success, error, mxUtils.bind(this, function(url, cb, err)
  364. {
  365. var req = new mxXmlRequest(url, null, 'GET');
  366. this.executeRequest(req, mxUtils.bind(this, function(req)
  367. {
  368. try
  369. {
  370. cb(this.getFileContent(JSON.parse(req.getText())));
  371. }
  372. catch (e)
  373. {
  374. err(e);
  375. }
  376. }), err);
  377. }));
  378. }
  379. else
  380. {
  381. error({message: mxResources.get('accessDenied')});
  382. }
  383. }
  384. else
  385. {
  386. // Adds random parameter to bypass cache
  387. var rnd = '&t=' + new Date().getTime();
  388. url = this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) +
  389. '/repository/files/' + encodeURIComponent(path) + '?ref=' + ref;
  390. var req = new mxXmlRequest(url + rnd, null, 'GET');
  391. this.executeRequest(req, mxUtils.bind(this, function(req)
  392. {
  393. try
  394. {
  395. success(this.createGitLabFile(org, repo, ref, JSON.parse(req.getText()), asLibrary, refPos));
  396. }
  397. catch (e)
  398. {
  399. error(e);
  400. }
  401. }), error);
  402. }
  403. }), error, knownRefPos);
  404. };
  405. /**
  406. * Translates this point by the given vector.
  407. *
  408. * @param {number} dx X-coordinate of the translation.
  409. * @param {number} dy Y-coordinate of the translation.
  410. */
  411. GitLabClient.prototype.getFileContent = function(data)
  412. {
  413. var fileName = data.file_name;
  414. var content = data.content;
  415. if (data.encoding === 'base64')
  416. {
  417. if (/\.jpe?g$/i.test(fileName))
  418. {
  419. content = 'data:image/jpeg;base64,' + content;
  420. }
  421. else if (/\.gif$/i.test(fileName))
  422. {
  423. content = 'data:image/gif;base64,' + content;
  424. }
  425. else if (/\.pdf$/i.test(fileName))
  426. {
  427. content = 'data:application/pdf;base64,' + content;
  428. }
  429. else
  430. {
  431. if (/\.png$/i.test(fileName))
  432. {
  433. var xml = this.ui.extractGraphModelFromPng(content);
  434. if (xml != null && xml.length > 0)
  435. {
  436. content = xml;
  437. }
  438. else
  439. {
  440. content = 'data:image/png;base64,' + content;
  441. }
  442. }
  443. else
  444. {
  445. content = Base64.decode(content);
  446. }
  447. }
  448. }
  449. return content;
  450. };
  451. /**
  452. * Translates this point by the given vector.
  453. *
  454. * @param {number} dx X-coordinate of the translation.
  455. * @param {number} dy Y-coordinate of the translation.
  456. */
  457. GitLabClient.prototype.createGitLabFile = function(org, repo, ref, data, asLibrary, refPos)
  458. {
  459. var gitLabUrl = DRAWIO_GITLAB_URL + '/';
  460. var htmlUrl = gitLabUrl + org + '/' + repo + '/blob/' + ref + '/' + data.file_path;
  461. var downloadUrl = gitLabUrl + org + '/' + repo + '/raw/' + ref + '/' + data.file_path + '?inline=false';
  462. var fileName = data.file_name;
  463. var meta = {'org': org, 'repo': repo, 'ref': ref, 'name': fileName,
  464. 'path': data.file_path, 'html_url': htmlUrl, 'download_url': downloadUrl,
  465. 'last_commit_id': data.last_commit_id, 'refPos': refPos};
  466. var content = this.getFileContent(data);
  467. return (asLibrary) ? new GitLabLibrary(this.ui, content, meta) : new GitLabFile(this.ui, content, meta);
  468. };
  469. /**
  470. * Translates this point by the given vector.
  471. *
  472. * @param {number} dx X-coordinate of the translation.
  473. * @param {number} dy Y-coordinate of the translation.
  474. */
  475. GitLabClient.prototype.insertFile = function(filename, data, success, error, asLibrary, folderId, base64Encoded)
  476. {
  477. asLibrary = (asLibrary != null) ? asLibrary : false;
  478. var tok = folderId.split('/');
  479. this.getRefIndex(tok, true, mxUtils.bind(this, function(tokens, refPos)
  480. {
  481. var repoPos = Math.max(refPos - 1, 0);
  482. var org = tokens.slice(0, repoPos).join('/');
  483. var repo = tokens[repoPos];
  484. var ref = tokens[refPos];
  485. path = tokens.slice(refPos + 1, tokens.length).join('/');
  486. if (path.length > 0)
  487. {
  488. path = path + '/';
  489. }
  490. path = path + filename;
  491. this.checkExists(org + '/' + repo + '/' + ref + '/' + path, true, mxUtils.bind(this, function(checked, last_commit_id)
  492. {
  493. if (checked)
  494. {
  495. // Does not insert file here as there is another writeFile implicit via fileCreated
  496. if (!asLibrary)
  497. {
  498. var gitLabUrl = DRAWIO_GITLAB_URL + '/';
  499. var htmlUrl = gitLabUrl + org + '/' + repo + '/blob/' + ref + '/' + path;
  500. var downloadUrl = gitLabUrl + org + '/' + repo + '/raw/' + ref + '/' + path + '?inline=false';
  501. success(new GitLabFile(this.ui, data, {'org': org, 'repo': repo, 'ref': ref, 'name': filename,
  502. 'path': path, 'html_url': htmlUrl, 'download_url': downloadUrl, 'refPos': refPos,
  503. 'last_commit_id': last_commit_id, isNew: true}));
  504. }
  505. else
  506. {
  507. if (!base64Encoded)
  508. {
  509. data = Base64.encode(data);
  510. }
  511. this.showCommitDialog(filename, true, mxUtils.bind(this, function(message)
  512. {
  513. this.writeFile(org, repo, ref, path, message, data, last_commit_id, mxUtils.bind(this, function(req)
  514. {
  515. try
  516. {
  517. var msg = JSON.parse(req.getText());
  518. success(this.createGitLabFile(org, repo, ref,
  519. (msg.content != null) ? msg.content : msg,
  520. asLibrary, refPos));
  521. }
  522. catch (e)
  523. {
  524. error(e);
  525. }
  526. }), error);
  527. }), error);
  528. }
  529. }
  530. else
  531. {
  532. // create if it does not exists
  533. error();
  534. }
  535. }))
  536. }), error, null, tok.length <= 4);
  537. };
  538. /**
  539. * Translates this point by the given vector.
  540. *
  541. * @param {number} dx X-coordinate of the translation.
  542. * @param {number} dy Y-coordinate of the translation.
  543. */
  544. GitLabClient.prototype.checkExists = function(path, askReplace, fn)
  545. {
  546. this.getFile(path, mxUtils.bind(this, function(file)
  547. {
  548. if (askReplace)
  549. {
  550. var resume = this.ui.spinner.pause();
  551. this.ui.confirm(mxResources.get('replaceIt', [path]), function()
  552. {
  553. resume();
  554. fn(true, file.getCurrentEtag());
  555. }, function()
  556. {
  557. resume();
  558. fn(false);
  559. });
  560. }
  561. else
  562. {
  563. this.ui.spinner.stop();
  564. this.ui.showError(mxResources.get('error'), mxResources.get('fileExists'), mxResources.get('ok'), function()
  565. {
  566. fn(false);
  567. });
  568. }
  569. }), mxUtils.bind(this, function(err)
  570. {
  571. fn(true);
  572. }), null, true);
  573. };
  574. /**
  575. *
  576. */
  577. GitLabClient.prototype.writeFile = function(org, repo, ref, path, message, data, last_commit_id, success, error)
  578. {
  579. if (data.length >= this.maxFileSize)
  580. {
  581. error({message: mxResources.get('drawingTooLarge') + ' (' +
  582. this.ui.formatFileSize(data.length) + ' / 10 MB)'});
  583. }
  584. else
  585. {
  586. var method = 'POST';
  587. var entity = {
  588. path: encodeURIComponent(path),
  589. branch: decodeURIComponent(ref),
  590. commit_message: message,
  591. content: data,
  592. encoding: 'base64'
  593. };
  594. if (last_commit_id != null)
  595. {
  596. entity.last_commit_id = last_commit_id;
  597. method = 'PUT';
  598. }
  599. // See https://docs.gitlab.com/ee/api/repository_files.html#update-existing-file-in-repository
  600. var url = this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) + '/repository/files/' + encodeURIComponent(path);
  601. var req = new mxXmlRequest(url, JSON.stringify(entity), method);
  602. this.executeRequest(req, mxUtils.bind(this, function(req)
  603. {
  604. success(req);
  605. }), error);
  606. }
  607. };
  608. /**
  609. * Translates this point by the given vector.
  610. *
  611. * @param {number} dx X-coordinate of the translation.
  612. * @param {number} dy Y-coordinate of the translation.
  613. */
  614. GitLabClient.prototype.saveFile = function(file, success, error, overwrite, message)
  615. {
  616. var org = file.meta.org;
  617. var repo = file.meta.repo;
  618. var ref = file.meta.ref;
  619. var path = file.meta.path;
  620. var fn = mxUtils.bind(this, function(last_commit_id, data)
  621. {
  622. this.writeFile(org, repo, ref, path, message, data, last_commit_id, mxUtils.bind(this, function(req)
  623. {
  624. delete file.meta.isNew;
  625. // Response does not return last_commit_id so we have to get the file
  626. // to to update last_commit_id and compare data to avoid lost commit
  627. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  628. {
  629. if (tempFile.getData() == file.getData())
  630. {
  631. success(tempFile.getCurrentEtag());
  632. }
  633. else
  634. {
  635. success({content: file.getCurrentEtag()});
  636. }
  637. }), error, null, null, file.meta.refPos);
  638. }), error);
  639. });
  640. var fn2 = mxUtils.bind(this, function()
  641. {
  642. if (this.ui.useCanvasForExport && /(\.png)$/i.test(path))
  643. {
  644. var p = this.ui.getPngFileProperties(this.ui.fileNode);
  645. this.ui.getEmbeddedPng(mxUtils.bind(this, function(data)
  646. {
  647. fn(file.meta.last_commit_id, data);
  648. }), error, (this.ui.getCurrentFile() != file) ?
  649. file.getData() : null, p.scale, p.border);
  650. }
  651. else
  652. {
  653. fn(file.meta.last_commit_id, Base64.encode(file.getData()));
  654. }
  655. });
  656. // LATER: Get last_commit_id is currently not possible since HEAD does
  657. // not have Access-Control-Expose-Headers for X-Gitlab-Last-Commit-Id
  658. if (overwrite)
  659. {
  660. this.getFile(org + '/' + repo + '/' + ref + '/' + path, mxUtils.bind(this, function(tempFile)
  661. {
  662. file.meta.last_commit_id = tempFile.meta.last_commit_id;
  663. fn2();
  664. }), error);
  665. }
  666. else
  667. {
  668. fn2();
  669. }
  670. };
  671. /**
  672. * Checks if the client is authorized and calls the next step.
  673. */
  674. GitLabClient.prototype.pickFolder = function(fn)
  675. {
  676. this.showGitLabDialog(false, fn, true);
  677. };
  678. /**
  679. * Checks if the client is authorized and calls the next step.
  680. */
  681. GitLabClient.prototype.pickFile = function(fn)
  682. {
  683. fn = (fn != null) ? fn : mxUtils.bind(this, function(path)
  684. {
  685. this.ui.loadFile('A' + encodeURIComponent(path));
  686. });
  687. this.showGitLabDialog(true, fn);
  688. };
  689. /**
  690. * LATER: Refactor to use common code with GitHubClient
  691. */
  692. GitLabClient.prototype.showGitLabDialog = function(showFiles, fn, hideNoFilesError)
  693. {
  694. var org = null;
  695. var repo = null;
  696. var ref = null;
  697. var path = null;
  698. var content = document.createElement('div');
  699. content.style.whiteSpace = 'nowrap';
  700. content.style.overflow = 'hidden';
  701. content.style.height = '304px';
  702. var hd = document.createElement('h3');
  703. mxUtils.write(hd, mxResources.get((showFiles) ? 'selectFile' : 'selectFolder'));
  704. hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:12px';
  705. content.appendChild(hd);
  706. var div = document.createElement('div');
  707. div.style.whiteSpace = 'nowrap';
  708. div.style.border = '1px solid lightgray';
  709. div.style.boxSizing = 'border-box';
  710. div.style.padding = '4px';
  711. div.style.overflow = 'auto';
  712. div.style.lineHeight = '1.2em';
  713. div.style.height = '274px';
  714. content.appendChild(div);
  715. var listItem = document.createElement('div');
  716. listItem.style.textOverflow = 'ellipsis';
  717. listItem.style.boxSizing = 'border-box';
  718. listItem.style.overflow = 'hidden';
  719. listItem.style.padding = '4px';
  720. listItem.style.width = '100%';
  721. var dlg = new CustomDialog(this.ui, content, mxUtils.bind(this, function()
  722. {
  723. fn(org + '/' + repo + '/' + encodeURIComponent(ref) + '/' + path);
  724. }));
  725. this.ui.showDialog(dlg.container, 420, 370, true, true);
  726. if (showFiles)
  727. {
  728. dlg.okButton.parentNode.removeChild(dlg.okButton);
  729. }
  730. var createLink = mxUtils.bind(this, function(label, fn, padding, underline)
  731. {
  732. var link = document.createElement('a');
  733. link.setAttribute('title', label);
  734. link.style.cursor = 'pointer';
  735. mxUtils.write(link, label);
  736. mxEvent.addListener(link, 'click', fn);
  737. if (underline)
  738. {
  739. link.style.textDecoration = 'underline';
  740. }
  741. if (padding != null)
  742. {
  743. var temp = listItem.cloneNode();
  744. temp.style.padding = padding;
  745. temp.appendChild(link);
  746. link = temp;
  747. }
  748. return link;
  749. });
  750. var updatePathInfo = mxUtils.bind(this, function(hideRef)
  751. {
  752. var pathInfo = document.createElement('div');
  753. pathInfo.style.marginBottom = '8px';
  754. pathInfo.appendChild(createLink(org + '/' + repo, mxUtils.bind(this, function()
  755. {
  756. path = null;
  757. selectRepo();
  758. }), null, true));
  759. if (!hideRef)
  760. {
  761. mxUtils.write(pathInfo, ' / ');
  762. pathInfo.appendChild(createLink(decodeURIComponent(ref), mxUtils.bind(this, function()
  763. {
  764. path = null;
  765. selectRef();
  766. }), null, true));
  767. }
  768. if (path != null && path.length > 0)
  769. {
  770. var tokens = path.split('/');
  771. for (var i = 0; i < tokens.length; i++)
  772. {
  773. (function(index)
  774. {
  775. mxUtils.write(pathInfo, ' / ');
  776. pathInfo.appendChild(createLink(tokens[index], mxUtils.bind(this, function()
  777. {
  778. path = tokens.slice(0, index + 1).join('/');
  779. selectFile();
  780. }), null, true));
  781. })(i);
  782. }
  783. }
  784. div.appendChild(pathInfo);
  785. });
  786. var error = mxUtils.bind(this, function(err)
  787. {
  788. this.ui.handleError(err, null, mxUtils.bind(this, function()
  789. {
  790. this.ui.spinner.stop();
  791. if (this.getUser() != null)
  792. {
  793. org = null;
  794. repo = null;
  795. ref = null;
  796. path = null;
  797. selectRepo();
  798. }
  799. else
  800. {
  801. this.ui.hideDialog();
  802. }
  803. }));
  804. });
  805. // Adds paging for repos, branches and files
  806. var nextPageDiv = null;
  807. var scrollFn = null;
  808. var pageSize = 100;
  809. var selectFile = mxUtils.bind(this, function(page)
  810. {
  811. if (page == null)
  812. {
  813. div.innerText = '';
  814. page = 1;
  815. }
  816. var req = new mxXmlRequest(this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) +
  817. '/repository/tree?path=' + path + '&ref=' + ref + '&per_page=' + pageSize + '&page=' + page, null, 'GET');
  818. this.ui.spinner.spin(div, mxResources.get('loading'));
  819. dlg.okButton.removeAttribute('disabled');
  820. if (scrollFn != null)
  821. {
  822. mxEvent.removeListener(div, 'scroll', scrollFn);
  823. scrollFn = null;
  824. }
  825. if (nextPageDiv != null && nextPageDiv.parentNode != null)
  826. {
  827. nextPageDiv.parentNode.removeChild(nextPageDiv);
  828. }
  829. nextPageDiv = document.createElement('a');
  830. nextPageDiv.style.display = 'block';
  831. nextPageDiv.style.cursor = 'pointer';
  832. mxUtils.write(nextPageDiv, mxResources.get('more') + '...');
  833. var nextPage = mxUtils.bind(this, function()
  834. {
  835. selectFile(page + 1);
  836. });
  837. mxEvent.addListener(nextPageDiv, 'click', nextPage);
  838. this.executeRequest(req, mxUtils.bind(this, function(req)
  839. {
  840. this.ui.tryAndHandle(mxUtils.bind(this, function()
  841. {
  842. this.ui.spinner.stop();
  843. if (page == 1)
  844. {
  845. updatePathInfo(!ref);
  846. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  847. {
  848. if (path == '' || path == null)
  849. {
  850. path = null;
  851. selectRepo();
  852. }
  853. else
  854. {
  855. var tokens = path.split('/');
  856. path = tokens.slice(0, tokens.length - 1).join('/');
  857. selectFile();
  858. }
  859. }), '4px'));
  860. }
  861. var files = JSON.parse(req.getText());
  862. if (files == null || files.length == 0)
  863. {
  864. if (!hideNoFilesError)
  865. {
  866. mxUtils.br(div);
  867. mxUtils.write(div, mxResources.get('noFiles'));
  868. }
  869. }
  870. else
  871. {
  872. var gray = true;
  873. var count = 0;
  874. var listFiles = mxUtils.bind(this, function(showFolders)
  875. {
  876. for (var i = 0; i < files.length; i++)
  877. {
  878. (mxUtils.bind(this, function(file)
  879. {
  880. if (showFolders == (file.type == 'tree'))
  881. {
  882. var temp = listItem.cloneNode();
  883. temp.style.backgroundColor = (gray) ?
  884. ((Editor.isDarkMode()) ? '#000000' : '#eeeeee') : '';
  885. gray = !gray;
  886. var typeImg = document.createElement('img');
  887. typeImg.src = IMAGE_PATH + '/' + (file.type == 'tree'? 'folder.png' : 'file.png');
  888. typeImg.setAttribute('align', 'absmiddle');
  889. typeImg.style.marginRight = '4px';
  890. typeImg.style.marginTop = '-4px';
  891. typeImg.width = 20;
  892. temp.appendChild(typeImg);
  893. temp.appendChild(createLink(file.name + ((file.type == 'tree') ? '/' : ''), mxUtils.bind(this, function()
  894. {
  895. if (file.type == 'tree')
  896. {
  897. path = file.path;
  898. selectFile();
  899. }
  900. else if (showFiles && file.type == 'blob')
  901. {
  902. this.ui.hideDialog();
  903. fn(org + '/' + repo + '/' + ref + '/' + file.path);
  904. }
  905. })));
  906. div.appendChild(temp);
  907. count++;
  908. }
  909. }))(files[i]);
  910. }
  911. });
  912. listFiles(true);
  913. if (showFiles)
  914. {
  915. listFiles(false);
  916. }
  917. if (count == pageSize)
  918. {
  919. div.appendChild(nextPageDiv);
  920. scrollFn = function()
  921. {
  922. if (div.scrollTop >= div.scrollHeight - div.offsetHeight)
  923. {
  924. nextPage();
  925. }
  926. };
  927. mxEvent.addListener(div, 'scroll', scrollFn);
  928. }
  929. }
  930. }));
  931. }), error, true);
  932. });
  933. var selectRef = mxUtils.bind(this, function(page, auto)
  934. {
  935. if (page == null)
  936. {
  937. div.innerText = '';
  938. page = 1;
  939. }
  940. var req = new mxXmlRequest(this.baseUrl + '/projects/' + encodeURIComponent(org + '/' + repo) +
  941. '/repository/branches?per_page=' + pageSize + '&page=' + page, null, 'GET');
  942. dlg.okButton.setAttribute('disabled', 'disabled');
  943. this.ui.spinner.spin(div, mxResources.get('loading'));
  944. if (scrollFn != null)
  945. {
  946. mxEvent.removeListener(div, 'scroll', scrollFn);
  947. scrollFn = null;
  948. }
  949. if (nextPageDiv != null && nextPageDiv.parentNode != null)
  950. {
  951. nextPageDiv.parentNode.removeChild(nextPageDiv);
  952. }
  953. nextPageDiv = document.createElement('a');
  954. nextPageDiv.style.display = 'block';
  955. nextPageDiv.style.cursor = 'pointer';
  956. mxUtils.write(nextPageDiv, mxResources.get('more') + '...');
  957. var nextPage = mxUtils.bind(this, function()
  958. {
  959. selectRef(page + 1);
  960. });
  961. mxEvent.addListener(nextPageDiv, 'click', nextPage);
  962. this.executeRequest(req, mxUtils.bind(this, function(req)
  963. {
  964. this.ui.tryAndHandle(mxUtils.bind(this, function()
  965. {
  966. this.ui.spinner.stop();
  967. if (page == 1)
  968. {
  969. updatePathInfo(true);
  970. div.appendChild(createLink('../ [Up]', mxUtils.bind(this, function()
  971. {
  972. path = null;
  973. selectRepo();
  974. }), '4px'));
  975. }
  976. var branches = JSON.parse(req.getText());
  977. if (branches == null || branches.length == 0)
  978. {
  979. mxUtils.br(div);
  980. mxUtils.write(div, mxResources.get('repositoryNotFound'));
  981. }
  982. else if (branches.length == 1 && auto)
  983. {
  984. ref = branches[0].name;
  985. path = '';
  986. selectFile();
  987. }
  988. else
  989. {
  990. for (var i = 0; i < branches.length; i++)
  991. {
  992. (mxUtils.bind(this, function(branch, idx)
  993. {
  994. var temp = listItem.cloneNode();
  995. temp.style.backgroundColor = (idx % 2 == 0) ?
  996. ((Editor.isDarkMode()) ? '#000000' : '#eeeeee') : '';
  997. temp.appendChild(createLink(branch.name, mxUtils.bind(this, function()
  998. {
  999. ref = encodeURIComponent(branch.name);
  1000. path = '';
  1001. selectFile();
  1002. })));
  1003. div.appendChild(temp);
  1004. }))(branches[i], i);
  1005. }
  1006. if (branches.length == pageSize)
  1007. {
  1008. div.appendChild(nextPageDiv);
  1009. scrollFn = function()
  1010. {
  1011. if (div.scrollTop >= div.scrollHeight - div.offsetHeight)
  1012. {
  1013. nextPage();
  1014. }
  1015. };
  1016. mxEvent.addListener(div, 'scroll', scrollFn);
  1017. }
  1018. }
  1019. }));
  1020. }), error);
  1021. });
  1022. dlg.okButton.setAttribute('disabled', 'disabled');
  1023. this.ui.spinner.spin(div, mxResources.get('loading'));
  1024. var selectRepo = mxUtils.bind(this, function(page)
  1025. {
  1026. var spinner = this.ui.spinner;
  1027. var inFlightRequests = 0;
  1028. this.ui.spinner.stop();
  1029. var spinnerRequestStarted = function()
  1030. {
  1031. spinner.spin(div, mxResources.get('loading'));
  1032. inFlightRequests += 1;
  1033. }
  1034. var spinnerRequestFinished = function()
  1035. {
  1036. inFlightRequests -= 1;
  1037. if (inFlightRequests === 0)
  1038. {
  1039. spinner.stop();
  1040. }
  1041. }
  1042. if (page == null)
  1043. {
  1044. div.innerText = '';
  1045. page = 1;
  1046. }
  1047. if (scrollFn != null)
  1048. {
  1049. mxEvent.removeListener(div, 'scroll', scrollFn);
  1050. scrollFn = null;
  1051. }
  1052. if (nextPageDiv != null && nextPageDiv.parentNode != null)
  1053. {
  1054. nextPageDiv.parentNode.removeChild(nextPageDiv);
  1055. }
  1056. nextPageDiv = document.createElement('a');
  1057. nextPageDiv.style.display = 'block';
  1058. nextPageDiv.style.cursor = 'pointer';
  1059. mxUtils.write(nextPageDiv, mxResources.get('more') + '...');
  1060. var nextPage = mxUtils.bind(this, function()
  1061. {
  1062. if (inFlightRequests === 0)
  1063. {
  1064. selectRepo(page + 1);
  1065. }
  1066. });
  1067. mxEvent.addListener(nextPageDiv, 'click', nextPage);
  1068. var listGroups = mxUtils.bind(this, function(callback)
  1069. {
  1070. spinnerRequestStarted();
  1071. var req = new mxXmlRequest(this.baseUrl + '/groups?per_page=100', null, 'GET');
  1072. this.executeRequest(req, mxUtils.bind(this, function(req)
  1073. {
  1074. this.ui.tryAndHandle(mxUtils.bind(this, function()
  1075. {
  1076. callback(JSON.parse(req.getText()));
  1077. spinnerRequestFinished();
  1078. }));
  1079. }), error);
  1080. });
  1081. var listProjects = mxUtils.bind(this, function(group, callback)
  1082. {
  1083. spinnerRequestStarted();
  1084. var req = new mxXmlRequest(this.baseUrl + '/groups/' + group.id + '/projects?per_page=100', null, 'GET');
  1085. this.executeRequest(req, mxUtils.bind(this, function(req)
  1086. {
  1087. this.ui.tryAndHandle(mxUtils.bind(this, function()
  1088. {
  1089. callback(group, JSON.parse(req.getText()));
  1090. spinnerRequestFinished();
  1091. }));
  1092. }), error);
  1093. });
  1094. listGroups(mxUtils.bind(this, function(groups)
  1095. {
  1096. if (this.user == null)
  1097. {
  1098. mxUtils.write(div, mxResources.get('loggedOut'));
  1099. }
  1100. else
  1101. {
  1102. spinnerRequestStarted();
  1103. var req = new mxXmlRequest(this.baseUrl + '/users/' + this.user.id + '/projects?per_page=' +
  1104. pageSize + '&page=' + page, null, 'GET');
  1105. this.executeRequest(req, mxUtils.bind(this, function(req)
  1106. {
  1107. var repos = JSON.parse(req.getText());
  1108. if ((repos == null || repos.length == 0) && (groups == null || groups.length == 0))
  1109. {
  1110. spinnerRequestFinished();
  1111. mxUtils.br(div);
  1112. mxUtils.write(div, mxResources.get('repositoryNotFound'));
  1113. }
  1114. else
  1115. {
  1116. if (page == 1)
  1117. {
  1118. div.appendChild(createLink(mxResources.get('enterValue') + '...', mxUtils.bind(this, function()
  1119. {
  1120. if (inFlightRequests === 0)
  1121. {
  1122. var dlg = new FilenameDialog(this.ui, 'org/repo/ref', mxResources.get('ok'),
  1123. mxUtils.bind(this, function(value)
  1124. {
  1125. if (value != null)
  1126. {
  1127. var tokens = value.split('/');
  1128. if (tokens.length > 1)
  1129. {
  1130. org = tokens[0];
  1131. repo = tokens[1];
  1132. path = null;
  1133. ref = null;
  1134. if (tokens.length > 2)
  1135. {
  1136. ref = encodeURIComponent(tokens.slice(2, tokens.length).join('/'));
  1137. selectFile();
  1138. }
  1139. else
  1140. {
  1141. selectRef(null, true);
  1142. }
  1143. }
  1144. else
  1145. {
  1146. this.ui.spinner.stop();
  1147. this.ui.handleError({message: mxResources.get('invalidName')});
  1148. }
  1149. }
  1150. }), mxResources.get('enterValue'));
  1151. this.ui.showDialog(dlg.container, 300, 80, true, false);
  1152. dlg.init();
  1153. }
  1154. })));
  1155. mxUtils.br(div);
  1156. mxUtils.br(div);
  1157. }
  1158. var gray = true;
  1159. for (var i = 0; i < repos.length; i++)
  1160. {
  1161. (mxUtils.bind(this, function(repository)
  1162. {
  1163. var temp = listItem.cloneNode();
  1164. temp.style.backgroundColor = (gray) ?
  1165. ((Editor.isDarkMode()) ? '#000000' : '#eeeeee') : '';
  1166. gray = !gray;
  1167. temp.appendChild(createLink(repository.name_with_namespace, mxUtils.bind(this, function()
  1168. {
  1169. if (inFlightRequests === 0)
  1170. {
  1171. org = repository.owner.username;
  1172. repo = repository.path;
  1173. path = '';
  1174. selectRef(null, true);
  1175. }
  1176. })));
  1177. div.appendChild(temp);
  1178. }))(repos[i]);
  1179. }
  1180. for (var i = 0; i < groups.length; i++)
  1181. {
  1182. spinnerRequestStarted();
  1183. listProjects(groups[i], (mxUtils.bind(this, function(group, projects)
  1184. {
  1185. spinnerRequestFinished();
  1186. for (var j = 0; j < projects.length; j++)
  1187. {
  1188. var temp = listItem.cloneNode();
  1189. temp.style.backgroundColor = (gray) ?
  1190. ((Editor.isDarkMode()) ? '#000000' : '#eeeeee') : '';
  1191. gray = !gray;
  1192. (mxUtils.bind(this, function(project)
  1193. {
  1194. temp.appendChild(createLink(project.name_with_namespace, mxUtils.bind(this, function()
  1195. {
  1196. if (inFlightRequests === 0)
  1197. {
  1198. org = group.full_path;
  1199. repo = project.path;
  1200. path = '';
  1201. selectRef(null, true);
  1202. }
  1203. })));
  1204. div.appendChild(temp);
  1205. }))(projects[j]);
  1206. }
  1207. })));
  1208. }
  1209. spinnerRequestFinished();
  1210. }
  1211. if (repos.length == pageSize)
  1212. {
  1213. div.appendChild(nextPageDiv);
  1214. scrollFn = function()
  1215. {
  1216. if (div.scrollTop >= div.scrollHeight - div.offsetHeight)
  1217. {
  1218. nextPage();
  1219. }
  1220. };
  1221. mxEvent.addListener(div, 'scroll', scrollFn);
  1222. }
  1223. }), error);
  1224. }
  1225. }));
  1226. });
  1227. if (!_token)
  1228. {
  1229. this.authenticate(mxUtils.bind(this, function()
  1230. {
  1231. this.updateUser(function()
  1232. {
  1233. selectRepo();
  1234. }, error, true);
  1235. }), error);
  1236. }
  1237. else if (!this.user)
  1238. {
  1239. this.updateUser(function()
  1240. {
  1241. selectRepo();
  1242. }, error, true);
  1243. }
  1244. else
  1245. {
  1246. selectRepo();
  1247. }
  1248. };
  1249. /**
  1250. * Checks if the client is authorized and calls the next step.
  1251. */
  1252. GitLabClient.prototype.logout = function()
  1253. {
  1254. //Send to server to clear refresh token cookie
  1255. this.ui.editor.loadUrl(this.redirectUri + '?doLogout=1&state=' + encodeURIComponent('cId=' + this.clientId + '&domain=' + window.location.host));
  1256. this.clearPersistentToken();
  1257. this.setUser(null);
  1258. _token = null;
  1259. this.setToken(null);
  1260. };
  1261. })();