3 const debug = require('debug')('gitter:app:gitlab:project-service');
4 const { Projects, ProjectMembers } = require('gitlab');
5 const { secureWrapFunction } = require('gitter-web-cache-wrapper');
6 const getGitlabAccessTokenFromUser = require('./get-gitlab-access-token-from-user');
7 const getPublicTokenFromPool = require('./get-public-token-from-pool');
9 function cacheFunction(name, obj) {
10 return secureWrapFunction(`GitLabProjectService:${name}`, obj, async GitLabProjectService => {
11 const accessToken = await GitLabProjectService.getAccessTokenPromise;
16 // API reference: https://docs.gitlab.com/ee/api/projects.html
17 function standardizeProjectResponse(project) {
18 debug('standardizeProjectResponse', project);
23 description: project.description,
24 absoluteUri: project.web_url,
25 uri: project.path_with_namespace,
26 private: project.visibility !== 'public',
27 avatar_url: project.avatar_url
31 function GitLabProjectService(user) {
33 this.getAccessTokenPromise = getGitlabAccessTokenFromUser(user);
36 GitLabProjectService.prototype._getGitlabOpts = async function() {
37 const accessToken = await this.getAccessTokenPromise;
39 oauthToken: accessToken,
40 token: getPublicTokenFromPool()
44 GitLabProjectService.prototype.getProjects = cacheFunction('getProjects', async function(params) {
45 const resource = new Projects(await this._getGitlabOpts());
46 const res = await resource.all(params);
48 return (res || []).map(standardizeProjectResponse);
51 GitLabProjectService.prototype.getProject = cacheFunction('getProject', async function(id) {
52 const resource = new Projects(await this._getGitlabOpts());
53 const project = await resource.show(id);
55 return standardizeProjectResponse(project);
58 GitLabProjectService.prototype._getProjectMember = async function(projectId, gitlabUserId) {
59 const gitlabLibOpts = await this._getGitlabOpts();
60 const projectMembers = new ProjectMembers(gitlabLibOpts);
63 const projectMember = await projectMembers.show(projectId, gitlabUserId, {
64 includeInherited: true
66 debug('isMember projectMember response =>', projectMember);
69 debug('isMember error =>', err);
70 if (err && err.response && err.response.status === 404) {
78 GitLabProjectService.prototype.getMembership = cacheFunction('getMembership', async function(
82 const projectMember = await this._getProjectMember(projectId, gitlabUserId);
85 accessLevel = projectMember.access_level;
88 // https://docs.gitlab.com/ee/api/access_requests.html
91 isMember: [10, 20, 30, 40, 50].some(level => level === accessLevel),
92 isMaintainer: [40, 50].some(level => level === accessLevel),
93 isOwner: accessLevel === 50
97 module.exports = GitLabProjectService;