summaryrefslogtreecommitdiffstats
path: root/api/WhatApi/Endpoints/UploadContentEndpoint.cs
blob: b11431032e909fae85a08455691bad53cd9215f0 (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
namespace WhatApi.Endpoints;

public class UploadContentEndpoint(Database db) : BaseEndpoint
{
    public record UploadContent(IFormFile File, string LatLong);

    [HttpPost("~/upload")]
    public async Task<ActionResult> HandleAsync([FromForm] UploadContent request, CancellationToken ct = default) {
        if (string.IsNullOrWhiteSpace(Request.GetMultipartBoundary())) {
            return StatusCode(415, "Unsupported Media Type");
        }

        var blobId = Guid.NewGuid();
        var contentId = Guid.NewGuid();

        var latitude = request.LatLong.Split(',')[0];
        var longitude = request.LatLong.Split(',')[1];

        var gf = NtsGeometryServices.Instance.CreateGeometryFactory(srid: Constants.Wgs84SpatialReferenceId);
        var point = gf.CreatePoint(new Coordinate(double.Parse(longitude), double.Parse(latitude)));

        var place = new Tables.Place() {
            ContentId = contentId,
            Location = point
        };

        var content = new Tables.Content() {
            Id = contentId,
            Mime = request.File.ContentType,
            BlobId = blobId,
            Ip = GetIp()
        };

        var path = Path.Combine(Directory.GetCurrentDirectory(), "files", blobId.ToString());

        await using var writer = new FileStream(path, FileMode.CreateNew);
        await request.File.CopyToAsync(writer, ct);
        await db.Content.AddAsync(content, ct);
        await db.Places.AddAsync(place, ct);
        await db.SaveChangesAsync(ct);
        return Ok(contentId);
    }
}