summaryrefslogtreecommitdiffstats
path: root/src/Program.cs
blob: 9d5cfdd995c429a921d69bca11fb43dc5d34f6b4 (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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
global using BlobBin;
using System.Text;
using System.Text.Json;
using IOL.Helpers;
using File = BlobBin.File;

const long MAX_REQUEST_BODY_SIZE = 104_857_600;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<Eva>();
builder.Services.AddHostedService<WallE>();
builder.WebHost.UseKestrel(o => { o.Limits.MaxRequestBodySize = MAX_REQUEST_BODY_SIZE; });
var app = builder.Build();
app.UseFileServer();
app.UseStatusCodePages();
app.MapGet("/upload-link", GetFileUploadLink);
app.MapPost("/file/{id}", UploadFilePart);
app.MapPost("/file", UploadFile);
app.MapPost("/text", UploadText);
app.MapGet("/b/{id}/delete", DeleteUpload);
app.MapGet("/p/{id}/delete", DeleteUpload);
app.MapPost("/b/{id}", GetFile);
app.MapGet("/b/{id}", GetFile);
app.MapGet("/p/{id}", GetPaste);
app.MapPost("/p/{id}", GetPaste);
Tools.GetFilesDirectoryPath(true);
app.Run();

IResult DeleteUpload(HttpContext context, Eva db, string id, string key = default, bool confirmed = false) {
    if (key.IsNullOrWhiteSpace()) {
        return Results.BadRequest("No key was found");
    }

    var isPaste = context.Request.Path.StartsWithSegments("/p");
    UploadEntityBase? upload = isPaste
        ? db.Pastes.FirstOrDefault(c => c.PublicId == id)
        : db.Files.FirstOrDefault(c => c.PublicId == id);

    if (upload is not {DeletedAt: null}) {
        return Results.NotFound();
    }

    if (upload.DeletionKey != key) {
        return Results.Text("Invalid key", default, default, 400);
    }

    if (!confirmed) {
        return Results.Content($"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/index.css">
    <title>{upload.PublicId} - Confirm deletion - Blobbin</title>
</head>
<body>
    <p>Are you sure you want to delete {upload.Name}?</p>
    <a href="/{context.Request.Path.ToString()}&confirmed=true">Yes</a>
    <span>  </span>
    <a href="/">No, cancel</a>
</body>
</html>
""", "text/html");
    }

    upload.DeletedAt = DateTime.UtcNow;
    db.SaveChanges();

    return Results.Text("""
The file is marked for deletion and cannot be accessed any more, all traces off it will be gone from our systems within 7 days. 
""");
}

IResult GetFileUploadLink(HttpContext context, Eva db) {
    var file = new File {
        CreatedBy = context.Request.Headers["X-Forwarded-For"].ToString()
    };
    db.Files.Add(file);
    db.SaveChanges();
    return Results.Text(
        context.Request.GetRequestHost()
        + "/upload/"
        + file.Id
    );
}

async Task<IResult> UploadFile(HttpContext context, Eva db) {
    if (!context.Request.Form.Files.Any()) {
        return Results.BadRequest("No files was found in request");
    }

    var file = new File {
        CreatedBy = context.Request.Headers["X-Forwarded-For"].ToString(),
        Singleton = context.Request.Form["singleton"] == "on",
        AutoDeleteAfter = context.Request.Form["autoDeleteAfter"],
        Length = context.Request.Form.Files[0].Length,
        Name = context.Request.Form.Files[0].FileName,
        MimeType = context.Request.Form.Files[0].ContentType,
        PublicId = GetUnusedPublicFileId(db),
        DeletionKey = RandomString.Generate(6),
    };

    if (context.Request.Form["password"].ToString().HasValue()) {
        file.PasswordHash = PasswordHelper.HashPassword(context.Request.Form["password"]);
    }

    await using var write = System.IO.File.OpenWrite(
        Path.Combine(Tools.GetFilesDirectoryPath(), file.Id.ToString())
    );
    await context.Request.Form.Files[0].CopyToAsync(write);
    db.Files.Add(file);
    db.SaveChanges();
    var deletionNote = "The file is only deleted when you request it.";
    if (file.AutoDeleteAfter.HasValue()) {
        var relativeDateTime = file.CreatedAt.Add(Tools.ParseHumanTimeSpan(file.AutoDeleteAfter));
        deletionNote = $"The file will be automatically deleted at {relativeDateTime:u}";
    }

    return Results.Text($"""
Your file is available here: {context.Request.GetRequestHost()}/b/{file.PublicId}

To delete the file, open this url in a browser {context.Request.GetRequestHost()}/b/{file.PublicId}/delete?key={file.DeletionKey}.
{deletionNote}
""");
}

IResult UploadFilePart(HttpContext context, Eva db) {
    return Results.Ok();
}

async Task<IResult> UploadText(HttpContext context, Eva db) {
    if (context.Request.Form["content"].ToString().IsNullOrWhiteSpace()) {
        return Results.Text("No content was found in request", default, default, 400);
    }

    var paste = new Paste {
        CreatedBy = context.Request.Headers["X-Forwarded-For"].ToString(),
        Singleton = context.Request.Form["singleton"] == "on",
        AutoDeleteAfter = context.Request.Form["autoDeleteAfter"],
        Length = context.Request.Form["content"].Count,
        Name = context.Request.Form["name"],
        MimeType = context.Request.Form["mime"],
        PublicId = GetUnusedPublicPasteId(db),
        Content = context.Request.Form["content"],
        DeletionKey = RandomString.Generate(6),
    };

    if (paste.MimeType.IsNullOrWhiteSpace()) {
        paste.MimeType = "text/plain";
    }

    if (context.Request.Form["password"].ToString().HasValue()) {
        paste.PasswordHash = PasswordHelper.HashPassword(context.Request.Form["password"]);
    }

    db.Pastes.Add(paste);
    db.SaveChanges();
    var deletionNote = "The paste is only deleted when you request it.";
    if (paste.AutoDeleteAfter.HasValue()) {
        var relativeDateTime = paste.CreatedAt.Add(Tools.ParseHumanTimeSpan(paste.AutoDeleteAfter));
        deletionNote = $"The paste will be automatically deleted at {relativeDateTime:u}";
    }

    return Results.Text($"""
Your paste is available here: {context.Request.GetRequestHost()}/p/{paste.PublicId}

To delete the paste, open this url in a browser {context.Request.GetRequestHost()}/p/{paste.PublicId}/delete?key={paste.DeletionKey}.
{deletionNote}
""");
}

async Task<IResult> GetPaste(HttpContext context, string id, Eva db) {
    var paste = db.Pastes.FirstOrDefault(c => c.PublicId == id.Trim());
    if (paste is not {DeletedAt: null}) return Results.NotFound();
    if (paste.PasswordHash.HasValue()) {
        var password = context.Request.Method == "POST" ? context.Request.Form["password"].ToString() : "";
        if (password.IsNullOrWhiteSpace() || !PasswordHelper.Verify(password, paste.PasswordHash)) {
            return Results.Content($"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/index.css">
    <title>{paste.PublicId} - Authenticate - Blobbin</title>
</head>
<body>
<form action="/p/{paste.PublicId}" method="post">
    <p>Authenticate to access this paste:</p>
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Unlock</button>
</form>
</body>
</html>
""", "text/html");
        }
    }

    if (paste.Singleton) {
        paste.DeletedAt = DateTime.UtcNow;
        db.SaveChanges();
    }

    if (ShouldDeleteUpload(paste)) {
        paste.DeletedAt = DateTime.UtcNow;
        db.SaveChanges();
    }

    Console.WriteLine(JsonSerializer.Serialize(paste));
    return Results.Content(paste.Content, paste.MimeType, Encoding.UTF8);
}

async Task<IResult> GetFile(HttpContext context, Eva db, string id, bool download = false) {
    var file = db.Files.FirstOrDefault(c => c.PublicId == id.Trim());
    if (file is not {DeletedAt: null}) return Results.NotFound();
    if (file.PasswordHash.HasValue()) {
        var password = context.Request.Method == "POST" ? context.Request.Form["password"].ToString() : "";
        if (password.IsNullOrWhiteSpace() || !PasswordHelper.Verify(password, file.PasswordHash)) {
            return Results.Content($"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/index.css">
    <title>{file.PublicId} - Authenticate - Blobbin</title>
</head>
<body>
<form action="/b/{file.PublicId}" method="post">
    <p>Authenticate to access this file:</p>
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Unlock</button>
</form>
</body>
</html>
""", "text/html");
        }
    }

    if (file.Singleton) {
        file.DeletedAt = DateTime.UtcNow;
        db.SaveChanges();
    }

    if (ShouldDeleteUpload(file)) {
        file.DeletedAt = DateTime.UtcNow;
        db.SaveChanges();
    }

    var reader = await System.IO.File.ReadAllBytesAsync(
        Path.Combine(
            Tools.GetFilesDirectoryPath(), file.Id.ToString()
        )
    );
    return download ? Results.File(reader, file.MimeType, file.Name) : Results.Bytes(reader, file.MimeType);
}

bool ShouldDeleteUpload(UploadEntityBase entity) {
    if (entity.AutoDeleteAfter.IsNullOrWhiteSpace()) {
        return false;
    }

    var deletedDateTime = entity.CreatedAt.Add(Tools.ParseHumanTimeSpan(entity.AutoDeleteAfter));
    return DateTime.Compare(DateTime.UtcNow, deletedDateTime) > 0;
}

string GetUnusedPublicFileId(Eva db) {
    string id() => RandomString.Generate(3);
    var res = id();
    while (db.Files.Any(c => c.PublicId == res)) {
        res = id();
    }

    return res;
}

string GetUnusedPublicPasteId(Eva db) {
    string id() => RandomString.Generate(3);
    var res = id();
    while (db.Pastes.Any(c => c.PublicId == res)) {
        res = id();
    }

    return res;
}