summaryrefslogtreecommitdiffstats
path: root/src/server/Api/Internal/Account/GetArchiveRoute.cs
blob: 5dc006e68a647eea62ea75a68f37b883df75aed0 (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
using IOL.BookmarkThing.Server.Api.Internal.Dtos;

namespace IOL.BookmarkThing.Server.Api.Internal.Account;

public class GetArchiveRoute : RouteBaseInternalSync.WithoutRequest.WithActionResult
{
	private readonly AppDbContext _context;

	public GetArchiveRoute(AppDbContext context) {
		_context = context;
	}

	[ApiVersionNeutral]
	[ApiExplorerSettings(IgnoreApi = true)]
	[HttpGet("~/v{version:apiVersion}/account/archive")]
	public override ActionResult Handle() {
		var user = _context.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id);
		if (user == default) {
			return NotFound();
		}

		var entries = _context.Entries.Where(c => c.UserId == user.Id);
		var archive = new UserArchiveDto() {
				Created = DateTime.UtcNow,
				User = new UserArchiveDto.UserArchiveUser(user),
				Entries = entries.Select(c => new UserArchiveDto.UserArchiveEntry(c)).ToList()
		};
		var jsonOptions = new JsonSerializerOptions {
				WriteIndented = true
		};
		var archiveBytes = JsonSerializer.SerializeToUtf8Bytes(archive, jsonOptions);
		return File(archiveBytes,
					"application/json",
					"bookmark-thing-archive-" + user.Username + "-" + DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + ".json");
	}
}