aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/Program.cs
blob: c62bf4d7afededb9dddfbd1725752fe64c726f96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.AspNetCore.Http;
using CrupestApi.Config;

public class TodoItem
{
    public string Status { get; set; } = default!;
    public string Title { get; set; } = default!;
}

internal class Program
{
    private static void Main(string[] args)
    {
        using var httpClient = new HttpClient();

        var builder = WebApplication.CreateBuilder(args);

        string configFilePath = Environment.GetEnvironmentVariable("CRUPEST_API_CONFIG_FILE") ?? "/config.json";

        builder.Configuration.AddJsonFile(configFilePath, optional: false, reloadOnChange: true);

        string? logFilePath = Environment.GetEnvironmentVariable("CRUPEST_API_LOG_FILE");
        if (logFilePath is not null)
        {
            // TODO: Log to file.
            builder.Logging.AddSimpleConsole(logger =>
            {
                logger.ColorBehavior = LoggerColorBehavior.Disabled;
            });
        }

        var app = builder.Build();

        app.MapGet("/api/todos", async ([FromServices] IConfiguration configuration, [FromServices] ILoggerFactory loggerFactory) =>
        {
            var logger = loggerFactory.CreateLogger("CrupestApi.Todos");

            static string CreateGraphQLQuery(TodoConfiguration todoConfiguration)
            {
                return $$"""
{
    user(login: "{{todoConfiguration.Username}}") {
        projectV2(number: {{todoConfiguration.ProjectNumber}}) {
          items(last: {{todoConfiguration.Count ?? 20}}) {
            nodes {
              __typename
              content {
                __typename
                ... on Issue {
                  title
                  closed
                }
                ... on PullRequest {
                  title
                  closed
                }
                ... on DraftIssue {
                  title
                }
              }
            }
          }
        }
      }
    }
""";
            }

            var todoConfiguration = configuration.GetSection("Todos").Get<TodoConfiguration>();
            if (todoConfiguration is null)
            {
                throw new Exception("Fail to get todos configuration.");
            }

            using var requestContent = new StringContent(JsonSerializer.Serialize(new
            {
                query = CreateGraphQLQuery(todoConfiguration)
            }));
            requestContent.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Json, Encoding.UTF8.WebName);

            using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.github.com/graphql");
            request.Content = requestContent;
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", todoConfiguration.Token);

            using var response = await httpClient.SendAsync(request);
            var responseBody = await response.Content.ReadAsStringAsync();
            logger.LogInformation(response.StatusCode.ToString());
            logger.LogInformation(responseBody);


            if (response.IsSuccessStatusCode)
            {
                using var responseJson = JsonSerializer.Deserialize<JsonDocument>(responseBody);
                if (responseJson is null)
                {
                    throw new Exception("Fail to deserialize response body.");
                }

                var nodes = responseJson.RootElement.GetProperty("data").GetProperty("user").GetProperty("projectV2").GetProperty("items").GetProperty("nodes").EnumerateArray();

                var result = new List<TodoItem>();

                foreach (var node in nodes)
                {
                    var content = node.GetProperty("content");
                    var title = content.GetProperty("title").GetString();
                    if (title is null)
                    {
                        throw new Exception("Fail to get title.");
                    }
                    JsonElement closedElement;
                    bool closed;
                    if (content.TryGetProperty("closed", out closedElement))
                    {
                        closed = closedElement.GetBoolean();
                    }
                    else
                    {
                        closed = false;
                    }

                    result.Add(new TodoItem
                    {
                        Title = title,
                        Status = closed ? "Done" : "Todo"
                    });
                }

                return Results.Json(result, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                }, statusCode: 200);
            }
            else
            {
                const string message = "Fail to get todos from GitHub.";
                logger.LogError(message);

                return Results.Json(new
                {
                    message
                }, statusCode: StatusCodes.Status503ServiceUnavailable);
            }
        });

        app.Run();
    }
}