From 46615aba5b5f0f8b452f44eea44798d945cb9345 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 25 Oct 2024 16:40:26 -0400 Subject: [PATCH] Refactor endpoints and update HTML for new API Simplified /archive endpoint to return static HTML without dynamic content or database queries. Refactored CreatePaste method to accept a Paste object and conditionally write compressed or uncompressed content based on size. Added new /api/pastes/get endpoint for fetching paginated pastes in JSON format. Updated archives.html to remove dynamic placeholders, using JavaScript for fetching and displaying pastes, and handling user authentication and pagination. Improved index.html with new font family and font weight for buttons. Updated paste.html to truncate long paste titles for display. Removed unused using directive in Turnstile.cs. Updated Program.cs to include new API endpoint and refactored CreatePaste method. --- PasteBin/Program.cs | 206 ++++++++++++++++++---------------- PasteBin/Turnstile.cs | 2 - PasteBin/assets/archives.html | 76 +++++++++++-- PasteBin/assets/index.html | 2 + PasteBin/assets/paste.html | 3 +- 5 files changed, 185 insertions(+), 104 deletions(-) diff --git a/PasteBin/Program.cs b/PasteBin/Program.cs index adf01b8..f90ae1c 100644 --- a/PasteBin/Program.cs +++ b/PasteBin/Program.cs @@ -632,87 +632,10 @@ class Program { var html = File.ReadAllText("assets/archives.html"); var page = context.Request?.Query["page"].ToString(); + context.Response.ContentType = "text/html"; + await context.Response.WriteAsync(html); + return; - bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]); - if (loggedIn) - { - html = html.Replace("{html}", "dashboard"); - } - else - { - html = html.Replace("{html}", "login sign up"); - } - - int pageNumber; - if (!int.TryParse(page, out pageNumber) || pageNumber <= 0) - { - pageNumber = 1; - } - int pastesPerPage = 50; - int skipCount = (pageNumber - 1) * pastesPerPage; - - using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) - { - await connection.OpenAsync(); - var command = connection.CreateCommand(); - command.CommandText = $"SELECT * FROM pastes WHERE Visibility != 'Private' AND Visibility != 'Unlisted' ORDER BY UID DESC LIMIT {pastesPerPage} OFFSET {skipCount}"; - var reader = await command.ExecuteReaderAsync(); - string pastes = string.Empty; - while (await reader.ReadAsync()) - { - var paste = new Paste - { - Title = reader.GetString(1), - UnixDate = long.Parse(reader.GetString(2)), - Size = reader.GetString(3), - Visibility = reader.GetString(4), - Id = reader.GetString(5), - }; - - string title = paste.Title; - if (paste.Visibility == "Private" || paste.Visibility == "Unlisted") - { - continue; - } - if (paste.Title == "" || string.IsNullOrEmpty(paste.Title)) - { - title = $"Untitled {reader.GetString(0)}"; - } - if (paste.Title.Length > 40) - { - title = paste.Title.Substring(0, 40) + "..."; - } - var difference = GetTimeDifference(DateTimeOffset.FromUnixTimeSeconds(paste.UnixDate ?? 0), DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.Now.ToUnixTimeSeconds())); - pastes += $"
  • {title} {difference} {ConvertToBytes(paste.Size)}
  • "; - } - - var findCountCommand = connection.CreateCommand(); - findCountCommand.CommandText = "SELECT COUNT(*) FROM pastes WHERE Visibility != 'Private' AND Visibility != 'Unlisted'"; - int totalPastes = Convert.ToInt32(await findCountCommand.ExecuteScalarAsync()); - int totalPages = (int)Math.Ceiling((double)totalPastes / pastesPerPage); - - if (pageNumber > totalPages && totalPages != 0) - { - context.Response.Redirect($"/archive?page={totalPages}"); - return; - } - if (string.IsNullOrEmpty(pastes)) - { - pastes = "

    No pastes found

    "; - html = html.Replace("", ""); - html = html.Replace("", ""); - html += ".buttons-wrapper{\r\n display: none !important;\r\n}"; - html += "\n"; - } - html = html.Replace("{pastes}", pastes); - html = html.Replace("{backpagenum}", $"{pageNumber - 1}"); - html = html.Replace("{pagenum}", $"{pageNumber + 1}"); - html = html.Replace("{currentpagenum}", $"{pageNumber}"); - html = html.Replace("{totalpages}", $"{totalPages}"); - context.Response.ContentType = "text/html"; - await context.Response.WriteAsync(html); - return; - } }).RequireRateLimiting("fixed-bigger"); app.MapGet("/u/{username}", async (HttpContext context) => { @@ -1680,7 +1603,14 @@ class Program } else { - paste = await CreatePaste(content, title, visibility, uploaderUUID); + var pasteData = new Paste + { + Content = content, + Title = title, + Visibility = visibility, + Uploader = uploaderUUID + }; + paste = await CreatePaste(pasteData); } @@ -2047,6 +1977,92 @@ class Program } }).RequireRateLimiting("fixed-bigger"); + app.MapPost("/api/pastes/get", async (HttpContext context) => + { + var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); + if (string.IsNullOrEmpty(body)) + { + context.Response.StatusCode = 400; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "No data uploaded" }.ToString()); + return; + } + try + { + JObject.Parse(body); + } + catch + { + context.Response.StatusCode = 400; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Invalid JSON" }.ToString()); + return; + } + var data = JObject.Parse(body); + var page = data["page"]?.ToObject() ?? 1; + + using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) + { + await connection.OpenAsync(); + long pages = 1; + var pagesCommand = connection.CreateCommand(); + pagesCommand.CommandText = "SELECT COUNT(*) FROM pastes WHERE Visibility != 'Private' AND Visibility != 'Untitled'"; + var pagesReader = await pagesCommand.ExecuteReaderAsync(); + await pagesReader.ReadAsync(); + if (pagesReader.HasRows) + { + pages = (long)Math.Ceiling(pagesReader.GetInt32(0) / 50.0); + } + var command = connection.CreateCommand(); + if (page <= 1) + { + command.CommandText = "SELECT * FROM pastes WHERE Visibility != 'Private' AND Visibility != 'Untitled' ORDER BY UID DESC LIMIT 50"; + } + else + { + command.CommandText = "SELECT * FROM pastes WHERE Visibility != 'Private' AND Visibility != 'Untitled' ORDER BY UID DESC LIMIT 50 OFFSET @Offset"; + command.Parameters.AddWithValue("@Offset", (page - 1) * 50); + } + var reader = await command.ExecuteReaderAsync(); + JArray pastes = new JArray(); + while (await reader.ReadAsync()) + { + var paste = new Paste + { + Title = reader.GetString(1), + UnixDate = long.Parse(reader.GetString(2)), + Size = reader.GetString(3), + Visibility = reader.GetString(4), + Id = reader.GetString(5), + }; + if (paste.Title == "") + { + paste.Title = $"Untitled {reader.GetString(0)}"; + } + var difference = GetTimeDifference(DateTimeOffset.FromUnixTimeSeconds(paste.UnixDate ?? 0), DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.Now.ToUnixTimeSeconds())); + if (paste.Visibility == "Private" || paste.Visibility == "Unlisted") + { + continue; + } + var _paste = new JObject(); + _paste["title"] = paste.Title; + _paste["id"] = paste.Id; + _paste["size"] = ConvertToBytes(paste.Size); + _paste["date"] = difference; + _paste["visibility"] = paste.Visibility; + pastes.Add(_paste); + } + await connection.CloseAsync(); + JObject resdata = new JObject(); + resdata["pages"] = pages; + resdata["page"] = page; + resdata["pastes"] = pastes; + context.Response.StatusCode = 200; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(resdata.ToString()); + } + + }).RequireRateLimiting("fixed-xl"); app.MapGet("/api/pastes/info", async (HttpContext context) => { var query = context.Request.Query; @@ -2496,27 +2512,29 @@ class Program context.Response.StatusCode = 200; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(responseJson.ToString()); - })).RequireRateLimiting("fixed-xl"); ; + })).RequireRateLimiting("fixed-xl"); #endregion await app.RunAsync(); } - public static async Task CreatePaste(string content, string title, string visibility, string UUID) + public static async Task CreatePaste(Paste paste) { - var paste = new Paste - { - Content = content, - Title = title, - UnixDate = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), - Size = content.Length.ToString(), - Visibility = visibility, - Id = GenerateRandomString(12), - Uploader = UUID - }; + paste.Id = GenerateRandomString(12); + paste.UnixDate = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + paste.Size = paste.Content.Length.ToString(); + var compressedText = await Compression.CompressString(paste.Content); - await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedText); + if (compressedText.LongLength < paste.Content.Length) + { + await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedText); + } + else + { + await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", paste.Content); + } + using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) { await connection.OpenAsync(); diff --git a/PasteBin/Turnstile.cs b/PasteBin/Turnstile.cs index d253d60..6e2d16d 100644 --- a/PasteBin/Turnstile.cs +++ b/PasteBin/Turnstile.cs @@ -1,6 +1,4 @@ using Newtonsoft.Json.Linq; -using System; -using System.Net.Http; using System.Text; namespace Sharpbin diff --git a/PasteBin/assets/archives.html b/PasteBin/assets/archives.html index ba47270..22297f2 100644 --- a/PasteBin/assets/archives.html +++ b/PasteBin/assets/archives.html @@ -13,10 +13,13 @@ home recent pastes archive - {html} + + +
    @@ -32,18 +37,73 @@

    paste archive

    - {pastes} + Loading...
    - < -

    {currentpagenum}/{totalpages}

    - > + < +

    + >