|
10 | 10 | using System.Text; |
11 | 11 | using System.Text.Json; |
12 | 12 | using Microsoft.AspNetCore.Http; |
| 13 | +using Microsoft.EntityFrameworkCore.Metadata.Internal; |
13 | 14 | using Microsoft.Extensions.Caching.Distributed; |
| 15 | +using Microsoft.Extensions.Configuration; |
14 | 16 | using Microsoft.Extensions.Logging; |
15 | 17 | using NXTBackend.API.Core.Services.Implementation; |
16 | 18 | using NXTBackend.API.Core.Services.Interface; |
17 | 19 | using NXTBackend.API.Core.Utils; |
18 | 20 | using NXTBackend.API.Domain.Entities; |
| 21 | +using NXTBackend.API.Domain.Entities.Users; |
19 | 22 | using NXTBackend.API.Domain.Enums; |
20 | 23 | using NXTBackend.API.Infrastructure.Database; |
21 | 24 | using NXTBackend.API.Models; |
| 25 | +using NXTBackend.API.Models.Requests.Git; |
| 26 | +using NXTBackend.API.Models.Responses.Git; |
22 | 27 | using NXTBackend.API.Models.Responses.Gitea; |
23 | 28 |
|
24 | 29 | namespace NXTBackend.API.Core.Services; |
25 | 30 |
|
26 | | -public sealed class GitService : BaseService<Git>, IGitService |
| 31 | +public sealed class GitService( |
| 32 | + DatabaseContext ctx, |
| 33 | + IConfiguration config, |
| 34 | + ILogger<GitService> logger, |
| 35 | + IHttpClientFactory clientFactory, |
| 36 | + IHttpContextAccessor httpContext) : BaseService<Git>(ctx), IGitService |
27 | 37 | { |
28 | | - private readonly HttpClient _httpClient; |
29 | | - private readonly IDistributedCache _cache; |
30 | | - private readonly ILogger<GitService> _logger; |
31 | | - private readonly IHttpContextAccessor _httpContextAccessor; |
32 | | - |
33 | | - public GitService( |
34 | | - DatabaseContext ctx, |
35 | | - IDistributedCache cache, |
36 | | - IHttpClientFactory clientFactory, |
37 | | - ILogger<GitService> logger, |
38 | | - IHttpContextAccessor httpContextAccessor) : base(ctx) |
39 | | - { |
40 | | - _httpClient = clientFactory.CreateClient("NXTGit"); |
41 | | - _httpContextAccessor = httpContextAccessor; |
42 | | - _cache = cache; |
43 | | - _logger = logger; |
44 | | - } |
| 38 | + private readonly HttpClient _client = clientFactory.CreateClient("NXTGit"); |
| 39 | + |
| 40 | + private readonly string _gitTemplate = config.GetValue<string>("GitTemplate") |
| 41 | + ?? throw new InvalidDataException("A git template is required!"); |
45 | 42 |
|
46 | | - private async Task SetAuthorizationHeaderAsync() |
| 43 | + private void SetAuthorizationHeaderAsync() |
47 | 44 | { |
48 | | - // TODO: this is *fine* but we need to make sure our proxy is set up correctly |
49 | | - var httpContext = _httpContextAccessor.HttpContext; |
50 | | - string? claim = httpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier); |
| 45 | + var ctx = httpContext.HttpContext; |
| 46 | + string? claim = ctx?.User.FindFirstValue(ClaimTypes.NameIdentifier); |
51 | 47 | var id = Guid.TryParse(claim, out var guid) ? guid : Guid.Empty; |
52 | 48 | if (id == Guid.Empty) |
53 | 49 | throw new ServiceException(StatusCodes.Status401Unauthorized, "Unauthorized"); |
54 | 50 |
|
55 | | - string cacheKey = $"USER_{guid}"; |
56 | | - string? cachedUser = await _cache.GetStringAsync(cacheKey); |
57 | | - if (string.IsNullOrEmpty(cachedUser)) |
58 | | - throw new ServiceException(StatusCodes.Status422UnprocessableEntity, "No login found"); |
| 51 | + logger.LogInformation("Request as user: {user}", claim); |
| 52 | + _client.DefaultRequestHeaders.Add("X-WEBAUTH-USER", claim); |
| 53 | + } |
| 54 | + |
| 55 | + public Task<bool> AddCollaborator(Guid entityId, Guid userId) |
| 56 | + { |
| 57 | + SetAuthorizationHeaderAsync(); |
59 | 58 |
|
60 | | - _logger.LogInformation("Request as user: {user}", cachedUser); |
61 | | - _httpClient.DefaultRequestHeaders.Add("X-WEBAUTH-USER", cachedUser); |
| 59 | + throw new NotImplementedException(); |
62 | 60 | } |
63 | 61 |
|
64 | | - public async Task<Git> CreateRemoteRepository(string repositoryName, string? description = null) |
| 62 | + public async Task<Git> CreateRepository(GitRepoPostRequestDTO DTO, OwnerKind OwnerType) |
65 | 63 | { |
66 | | - await SetAuthorizationHeaderAsync(); |
67 | | - var createOption = new CreateRepoOption |
68 | | - { |
69 | | - Name = repositoryName, |
70 | | - Description = description, |
71 | | - Private = false, |
72 | | - AutoInit = true |
73 | | - }; |
| 64 | + SetAuthorizationHeaderAsync(); |
74 | 65 |
|
75 | | - var response = await _httpClient.PostAsJsonAsync("/api/v1/user/repos", createOption); |
76 | | - _logger.LogInformation("Response: {response}", response); |
77 | | - response.EnsureSuccessStatusCode(); |
| 66 | + var response = await _client.PostAsJsonAsync($"/api/v1/repos/{_gitTemplate}/generate", DTO); |
| 67 | + logger.LogInformation("Response: {response}", response); |
78 | 68 |
|
79 | | - var repoResponse = await response.Content.ReadFromJsonAsync<JsonElement>(); |
| 69 | + if (response.StatusCode is HttpStatusCode.Conflict) |
| 70 | + throw new ServiceException(StatusCodes.Status409Conflict, "The repository with the same name already exists"); |
80 | 71 |
|
81 | | - // Map the response to our Git entity |
| 72 | + response.EnsureSuccessStatusCode(); |
| 73 | + var model = await response.Content.ReadFromJsonAsync<RepoDO>() ?? |
| 74 | + throw new ServiceException(StatusCodes.Status500InternalServerError, "Model mistmatch"); |
82 | 75 | var git = new Git |
83 | 76 | { |
84 | | - Name = repoResponse.GetProperty("name").GetString() ?? string.Empty, |
85 | | - Namespace = repoResponse.GetProperty("full_name").GetString() ?? string.Empty, |
86 | | - Url = repoResponse.GetProperty("clone_url").GetString() ?? string.Empty, |
87 | | - Branch = repoResponse.GetProperty("default_branch").GetString() ?? "main", |
88 | | - ProviderType = GitProviderKind.Managed, |
89 | | - OwnerType = GitOwnerKind.User // TODO: Once we support organizations within the app, this needs to be configurable |
| 77 | + Name = model.Name, |
| 78 | + Namespace = model.FullName, |
| 79 | + Url = model.CloneUrl, |
| 80 | + Branch = model.DefaultBranch, |
| 81 | + ProviderType = GitProviderKind.Managed, // This as well needs to be configurable |
| 82 | + OwnerType = OwnerType |
90 | 83 | }; |
91 | 84 |
|
92 | 85 | return await CreateAsync(git); |
93 | 86 | } |
94 | 87 |
|
95 | | - public async Task ArchiveRepository(string owner, string repo) |
96 | | - { |
97 | | - await SetAuthorizationHeaderAsync(); |
98 | | - var editOption = new EditRepoOption |
99 | | - { |
100 | | - Archived = true |
101 | | - }; |
102 | | - |
103 | | - var response = await _httpClient.PatchAsync($"/api/v1/repos/{owner}/{repo}", JsonContent.Create(editOption)); |
104 | | - response.EnsureSuccessStatusCode(); |
105 | | - } |
106 | 88 |
|
107 | | - public async Task<FileContentResponse> UpsertFile( |
108 | | - string owner, |
109 | | - string repo, |
110 | | - string path, |
111 | | - string content, |
112 | | - string message, |
113 | | - string branch = "main") |
| 89 | + public async Task<string> GetFile(string GitNamespace, string Path, string Branch = "main") |
114 | 90 | { |
115 | | - await SetAuthorizationHeaderAsync(); |
| 91 | + SetAuthorizationHeaderAsync(); |
116 | 92 |
|
117 | | - // First try to get the file to check if it exists |
118 | | - var getFileResponse = await _httpClient.GetAsync($"/api/v1/repos/{owner}/{repo}/contents/{path}"); |
119 | 93 | string? sha = null; |
120 | | - |
| 94 | + var getFileResponse = await _client.GetAsync($"/api/v1/repos/{GitNamespace}/contents/{Path}"); |
121 | 95 | if (getFileResponse.IsSuccessStatusCode) |
122 | 96 | { |
123 | 97 | var existingFile = await getFileResponse.Content.ReadFromJsonAsync<ContentInfo>(); |
@@ -149,20 +123,139 @@ public async Task<FileContentResponse> UpsertFile( |
149 | 123 | response.EnsureSuccessStatusCode(); |
150 | 124 | return await response.Content.ReadFromJsonAsync<FileContentResponse>() |
151 | 125 | ?? throw new InvalidOperationException("Failed to upsert file"); |
| 126 | + |
152 | 127 | } |
153 | 128 |
|
154 | | - public async Task<string> GetRawFileContent( |
155 | | - string name, |
156 | | - string path, |
157 | | - string branch = "main") |
| 129 | + public Task<(Git?, User?)> IsCollaborator(Guid entityId, Guid userId) |
158 | 130 | { |
159 | | - await SetAuthorizationHeaderAsync(); |
| 131 | + SetAuthorizationHeaderAsync(); |
160 | 132 |
|
161 | | - var requestUri = $"/api/v1/repos/{name}/raw/{path}?ref={branch}"; |
162 | | - var response = await _httpClient.GetAsync(requestUri); |
163 | | - if (response.StatusCode == HttpStatusCode.NotFound) |
164 | | - throw new ServiceException(StatusCodes.Status404NotFound, "File not found"); |
165 | | - response.EnsureSuccessStatusCode(); |
166 | | - return await response.Content.ReadAsStringAsync(); |
| 133 | + throw new NotImplementedException(); |
| 134 | + } |
| 135 | + |
| 136 | + public Task<bool> RemoveCollaborator(Guid entityId, Guid userId) |
| 137 | + { |
| 138 | + SetAuthorizationHeaderAsync(); |
| 139 | + |
| 140 | + throw new NotImplementedException(); |
167 | 141 | } |
| 142 | + |
| 143 | + public Task SetFile(string GitNamespace, string Path, string Content, string CommitMessage, string Branch = "main") |
| 144 | + { |
| 145 | + SetAuthorizationHeaderAsync(); |
| 146 | + |
| 147 | + throw new NotImplementedException(); |
| 148 | + } |
| 149 | + |
| 150 | + public Task<Git> UpdateRepository(string GitNamespace, GitRepoPatchRequestDTO DTO) |
| 151 | + { |
| 152 | + SetAuthorizationHeaderAsync(); |
| 153 | + |
| 154 | + throw new NotImplementedException(); |
| 155 | + } |
| 156 | + |
| 157 | + // public async Task<Git> CreateRemoteRepository(string repositoryName, string? description = null) |
| 158 | + // { |
| 159 | + // await SetAuthorizationHeaderAsync(); |
| 160 | + // var createOption = new CreateRepoOption |
| 161 | + // { |
| 162 | + // Name = repositoryName, |
| 163 | + // Description = description, |
| 164 | + // Private = false, |
| 165 | + // AutoInit = true |
| 166 | + // }; |
| 167 | + |
| 168 | + // var response = await _httpClient.PostAsJsonAsync("/api/v1/user/repos", createOption); |
| 169 | + // _logger.LogInformation("Response: {response}", response); |
| 170 | + // response.EnsureSuccessStatusCode(); |
| 171 | + |
| 172 | + // var repoResponse = await response.Content.ReadFromJsonAsync<JsonElement>(); |
| 173 | + |
| 174 | + // // Map the response to our Git entity |
| 175 | + // var git = new Git |
| 176 | + // { |
| 177 | + // Name = repoResponse.GetProperty("name").GetString() ?? string.Empty, |
| 178 | + // Namespace = repoResponse.GetProperty("full_name").GetString() ?? string.Empty, |
| 179 | + // Url = repoResponse.GetProperty("clone_url").GetString() ?? string.Empty, |
| 180 | + // Branch = repoResponse.GetProperty("default_branch").GetString() ?? "main", |
| 181 | + // ProviderType = GitProviderKind.Managed, |
| 182 | + // OwnerType = GitOwnerKind.User // TODO: Once we support organizations within the app, this needs to be configurable |
| 183 | + // }; |
| 184 | + |
| 185 | + // return await CreateAsync(git); |
| 186 | + // } |
| 187 | + |
| 188 | + // public async Task ArchiveRepository(string owner, string repo) |
| 189 | + // { |
| 190 | + // await SetAuthorizationHeaderAsync(); |
| 191 | + // var editOption = new EditRepoOption |
| 192 | + // { |
| 193 | + // Archived = true |
| 194 | + // }; |
| 195 | + |
| 196 | + // var response = await _httpClient.PatchAsync($"/api/v1/repos/{owner}/{repo}", JsonContent.Create(editOption)); |
| 197 | + // response.EnsureSuccessStatusCode(); |
| 198 | + // } |
| 199 | + |
| 200 | + // public async Task<FileContentResponse> UpsertFile( |
| 201 | + // string owner, |
| 202 | + // string repo, |
| 203 | + // string path, |
| 204 | + // string content, |
| 205 | + // string message, |
| 206 | + // string branch = "main") |
| 207 | + // { |
| 208 | + // await SetAuthorizationHeaderAsync(); |
| 209 | + |
| 210 | + // // First try to get the file to check if it exists |
| 211 | + // var getFileResponse = await _httpClient.GetAsync($"/api/v1/repos/{owner}/{repo}/contents/{path}"); |
| 212 | + // string? sha = null; |
| 213 | + |
| 214 | + // if (getFileResponse.IsSuccessStatusCode) |
| 215 | + // { |
| 216 | + // var existingFile = await getFileResponse.Content.ReadFromJsonAsync<ContentInfo>(); |
| 217 | + // sha = existingFile?.Sha; |
| 218 | + // } |
| 219 | + |
| 220 | + // var fileContent = new FileContentRequest |
| 221 | + // { |
| 222 | + // Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(content)), |
| 223 | + // Message = message, |
| 224 | + // Branch = branch, |
| 225 | + // Sha = sha, |
| 226 | + // Author = new GitUserInfo |
| 227 | + // { |
| 228 | + // Name = "NXT System", |
| 229 | + |
| 230 | + // } |
| 231 | + // }; |
| 232 | + |
| 233 | + // var response = await _httpClient.PutAsync( |
| 234 | + // $"/api/v1/repos/{owner}/{repo}/contents/{path}", |
| 235 | + // new StringContent( |
| 236 | + // JsonSerializer.Serialize(fileContent), |
| 237 | + // Encoding.UTF8, |
| 238 | + // "application/json" |
| 239 | + // ) |
| 240 | + // ); |
| 241 | + |
| 242 | + // response.EnsureSuccessStatusCode(); |
| 243 | + // return await response.Content.ReadFromJsonAsync<FileContentResponse>() |
| 244 | + // ?? throw new InvalidOperationException("Failed to upsert file"); |
| 245 | + // } |
| 246 | + |
| 247 | + // public async Task<string> GetRawFileContent( |
| 248 | + // string name, |
| 249 | + // string path, |
| 250 | + // string branch = "main") |
| 251 | + // { |
| 252 | + // await SetAuthorizationHeaderAsync(); |
| 253 | + |
| 254 | + // var requestUri = $"/api/v1/repos/{name}/raw/{path}?ref={branch}"; |
| 255 | + // var response = await _httpClient.GetAsync(requestUri); |
| 256 | + // if (response.StatusCode == HttpStatusCode.NotFound) |
| 257 | + // throw new ServiceException(StatusCodes.Status404NotFound, "File not found"); |
| 258 | + // response.EnsureSuccessStatusCode(); |
| 259 | + // return await response.Content.ReadAsStringAsync(); |
| 260 | + // } |
168 | 261 | } |
0 commit comments