aboutsummaryrefslogtreecommitdiffstats
path: root/code/api/src/Endpoints/Internal/Account/GetArchiveRoute.cs
blob: 0d9f81799a52a8104279e7645cd7f4ce6dde5804 (plain) (blame)
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
namespace IOL.GreatOffice.Api.Endpoints.Internal.Account;

public class GetAccountArchiveRoute : RouteBaseAsync.WithoutRequest.WithActionResult<UserArchiveDto>
{
    private readonly MainAppDatabase _database;

    public GetAccountArchiveRoute(MainAppDatabase database) {
        _database = database;
    }

    /// <summary>
    /// Get a data archive with the currently logged on user's data.
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [HttpGet("~/_/account/archive")]
    public override async Task<ActionResult<UserArchiveDto>> HandleAsync(CancellationToken cancellationToken = default) {
        var user = _database.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id);
        if (user == default) {
            await HttpContext.SignOutAsync();
            return Unauthorized();
        }

        var entries = _database.TimeEntries
            .AsNoTracking()
            .Include(c => c.Labels)
            .Include(c => c.Category)
            .Where(c => c.UserId == user.Id)
            .ToList();

        var jsonOptions = new JsonSerializerOptions {
            WriteIndented = true
        };

        var dto = new UserArchiveDto(user);
        dto.Entries.AddRange(entries.Select(entry => new UserArchiveDto.EntryDto {
            CreatedAt = entry.CreatedAt.ToString("yyyy-MM-ddTHH:mm:ssZ"),
            StartDateTime = entry.Start,
            StopDateTime = entry.Stop,
            Description = entry.Description,
            Labels = entry.Labels
                .Select(c => new UserArchiveDto.LabelDto {
                    Name = c.Name,
                    Color = c.Color
                })
                .ToList(),
            Category = new UserArchiveDto.CategoryDto {
                Name = entry.Category.Name,
                Color = entry.Category.Color
            },
        }));

        dto.CountEntries();

        var entriesSerialized = JsonSerializer.SerializeToUtf8Bytes(dto, jsonOptions);

        return File(entriesSerialized,
            "application/json",
            user.Username + "-time-tracker-archive-" + AppDateTime.UtcNow.ToString("yyyyMMddTHHmmss") + ".json");
    }
}