diff --git a/SharpbinV2.Server/Controllers/PasteController.cs b/SharpbinV2.Server/Controllers/PasteController.cs index 0ad0f36..c8aba06 100644 --- a/SharpbinV2.Server/Controllers/PasteController.cs +++ b/SharpbinV2.Server/Controllers/PasteController.cs @@ -40,7 +40,9 @@ namespace SharpbinV2.Server.Controllers string title = queries.ContainsKey("title") ? queries["title"].ToString() : $"Untitled {await _databaseService.EnumeratePastes()}"; string syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : "none"; - int visibility = queries.ContainsKey("visibility") ? int.Parse(queries["visibility"]) : 0; + int visibility = 0; + if (queries.ContainsKey("visibility") && int.TryParse(queries["visibility"], out int parsedVisibility)) + visibility = parsedVisibility; if (title.Length > 500) return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." }); @@ -232,5 +234,113 @@ namespace SharpbinV2.Server.Controllers return StatusCode(500, new { error = "An error occurred while retrieving the paste views." }); } } + + [HttpGet("archive")] + [EnableRateLimiting("general")] + public async Task GetPastes(int page, int limit) + { + if (page < 1 || limit < 1 || limit > 25) + return BadRequest(new { success = false, message = "Invalid page or limit parameters." }); + if (page == 1) + page = 0; + + try + { + int pages = await _databaseService.EnumeratePastes() / limit; + if (page > pages) + return BadRequest(new { success = false, message = "Page number exceeds available pages." }); + + List? pastes = await _databaseService.GetPastes(limit, page, _logger); + + if (pastes == null || pastes.Count == 0) + return NotFound(new { success = false, message = "No pastes found." }); + + var pasteList = new List(); + foreach (var paste in pastes) + { + if (paste == null) + continue; + pasteList.Add(new + { + paste.ID, + paste.UUID, + paste.Title, + paste.Syntax, + paste.Visibility, + paste.Created, + paste.Size, + paste.TrueSize, + paste.AuthorUUID + }); + } + + return Ok(new + { + success = true, + pages, + pastes = pasteList + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving pastes archive"); + return StatusCode(500, new { error = "An error occurred while retrieving the pastes archive." }); + } + } + + [HttpGet("my")] + [EnableRateLimiting("general")] + public async Task GetMyPastes(int page, int limit) + { + var requestDetails = HelperService.GetRequestDetails(HttpContext); + if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null) + return Unauthorized(new { success = false, message = "Invalid or missing authentication token." }); + User? user = await _databaseService.UserFromToken(requestDetails.Token ?? ""); + if (user == null) + return Unauthorized(new { success = false, message = "User not found." }); + if (page < 1 || limit < 1 || limit > 25) + return BadRequest(new { success = false, message = "Invalid page or limit parameters." }); + if (page == 1) + page = 0; + + try + { + int pages = await _databaseService.EnumerateUserPastes(user) / limit; + if (page > pages) + return BadRequest(new { success = false, message = "Page number exceeds available pages." }); + List? pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger); + if (pastes == null || pastes.Count == 0) + return NotFound(new { success = false, message = "No pastes found for this user." }); + var pasteList = new List(); + foreach (var paste in pastes) + { + if (paste == null) + continue; + pasteList.Add(new + { + paste.ID, + paste.UUID, + paste.Title, + paste.Syntax, + paste.Visibility, + paste.Created, + paste.Size, + paste.TrueSize, + paste.AuthorUUID + }); + } + return Ok(new + { + success = true, + pages, + pastes = pasteList + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error retrieving user's pastes"); + return StatusCode(500, new { error = "An error occurred while retrieving the user's pastes." }); + } + } } } diff --git a/SharpbinV2.Server/Models/Paste.cs b/SharpbinV2.Server/Models/Paste.cs index c7c3d35..c1937da 100644 --- a/SharpbinV2.Server/Models/Paste.cs +++ b/SharpbinV2.Server/Models/Paste.cs @@ -2,6 +2,7 @@ { public class Paste { + public int UID { get; set; } public string? UUID { get; set; } public string? ID { get; set; } public int? Visibility { get; set; } diff --git a/SharpbinV2.Server/Program.cs b/SharpbinV2.Server/Program.cs index 6548bf4..5c6cefd 100644 --- a/SharpbinV2.Server/Program.cs +++ b/SharpbinV2.Server/Program.cs @@ -1,8 +1,4 @@ using Microsoft.Data.Sqlite; -using Newtonsoft.Json.Linq; -using System.Text; -using Bcrypt = BCrypt.Net.BCrypt; -using UAParser; using Microsoft.AspNetCore.RateLimiting; using SharpbinV2.Server.Models; using SharpbinV2.Server.Services; @@ -40,7 +36,6 @@ namespace SharpbinV2.Server "toml", "xml" }; - public static JObject Configuration { get; set; } static async Task Main(string[] args) { @@ -136,13 +131,12 @@ namespace SharpbinV2.Server app.MapGet("/", (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); return context.Response.SendFileAsync("wwwroot/index.html"); }).RequireRateLimiting("general"); - app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env) => + app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env, string pasteid) => { - var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; - if (string.IsNullOrEmpty(pasteid)) + if (string.IsNullOrWhiteSpace(pasteid)) { context.Response.StatusCode = 400; context.Response.Redirect("/error?error=400&message=Invalid paste id."); @@ -156,26 +150,26 @@ namespace SharpbinV2.Server switch (Path.GetExtension(filePath)) { case "html": - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); break; case "css": - context.Response.Headers.Add("Content-Type", "text/css"); + context.Response.Headers.Append("Content-Type", "text/css"); break; case "js": - context.Response.Headers.Add("Content-Type", "text/javascript"); + context.Response.Headers.Append("Content-Type", "text/javascript"); break; case "json": - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); break; case "png": - context.Response.Headers.Add("Content-Type", "image/png"); + context.Response.Headers.Append("Content-Type", "image/png"); break; case "jpg": case "jpeg": - context.Response.Headers.Add("Content-Type", "image/jpeg"); + context.Response.Headers.Append("Content-Type", "image/jpeg"); break; case "ico": - context.Response.Headers.Add("Content-Type", "image/x-icon"); + context.Response.Headers.Append("Content-Type", "image/x-icon"); break; } await context.Response.SendFileAsync(filePath); @@ -205,17 +199,17 @@ namespace SharpbinV2.Server { if (!await Database.HasAlreadyViewedFromRqDetails(requestdetails)) { - await Database.AddViewToPaste(null, paste, requestdetails); + await Database.AddViewToPaste(new User { UUID = "0" }, paste, requestdetails); } } context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/paste.html"); }).RequireRateLimiting("general"); app.MapGet("/error", async (HttpContext context) => { context.Response.StatusCode = 400; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/error.html"); }); app.MapGet("/error.html", (HttpContext context) => @@ -239,10 +233,10 @@ namespace SharpbinV2.Server return; } context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/plain"); + context.Response.Headers.Append("Content-Type", "text/plain"); if (paste.FilePath.EndsWith(".gz")) { - context.Response.Headers.Add("Content-Encoding", "gzip"); + context.Response.Headers.Append("Content-Encoding", "gzip"); await context.Response.SendFileAsync(paste.FilePath); } else @@ -257,13 +251,13 @@ namespace SharpbinV2.Server app.MapGet("/archive", async (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/archive.html"); }).RequireRateLimiting("general"); app.MapGet("/dash", async (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/dash.html"); }).RequireRateLimiting("general"); app.MapGet("/dash.html", (HttpContext context) => @@ -273,13 +267,13 @@ namespace SharpbinV2.Server app.MapGet("/login", async (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/login.html"); }).RequireRateLimiting("general"); app.MapGet("/register", async (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/register.html"); }).RequireRateLimiting("general"); app.MapGet("/u/{username}", async (HttpContext context) => @@ -293,10 +287,10 @@ namespace SharpbinV2.Server } string html = File.ReadAllText("wwwroot/user.html"); context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); - context.Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate"); - context.Response.Headers.Add("Pragma", "no-cache"); - context.Response.Headers.Add("Expires", "0"); + context.Response.Headers.Append("Content-Type", "text/html"); + context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate"); + context.Response.Headers.Append("Pragma", "no-cache"); + context.Response.Headers.Append("Expires", "0"); await context.Response.WriteAsync(html); @@ -305,7 +299,7 @@ namespace SharpbinV2.Server app.MapGet("/reset-password", async (HttpContext context) => { context.Response.StatusCode = 200; - context.Response.Headers.Add("Content-Type", "text/html"); + context.Response.Headers.Append("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/reset-password.html"); }).RequireRateLimiting("general"); @@ -314,256 +308,6 @@ namespace SharpbinV2.Server #region API - app.MapPost("/api/accounts/reset-password", async (HttpContext context) => - { - var requestdetails = GetRequestDetails(context); - if (string.IsNullOrEmpty(requestdetails.Token)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "No token provided, not authorized." }); - return; - } - - var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); - if (body == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid Body." }); - return; - } - var json = TryParse(body); - if (json == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid JSON." }); - return; - } - if (!string.IsNullOrEmpty(json["token"]?.ToString()) && !string.IsNullOrEmpty(json["uuid"]?.ToString()) && !string.IsNullOrEmpty(json["url"]?.ToString())) - { - var password = json["password"]?.ToString(); - var uuid = json["uuid"]?.ToString(); - var token = json["token"]?.ToString(); - var url = json["url"]?.ToString(); - - if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(password)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); - return; - } - - var pwreset = await Database.GetPasswordReset(url, uuid, token); - if (pwreset == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token/url/uuid." }); - return; - } - var user = await Database.UserFromUUID(uuid); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid user." }); - return; - } - var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12)); - if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." }); - return; - } - else - { - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." }); - } - return; - } - else // normal password resets from the dashboard - { - var user = await Database.UserFromToken(requestdetails.Token); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." }); - return; - } - var password = json["password"]?.ToString(); - if (string.IsNullOrEmpty(password)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); - return; - } - var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12)); - if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." }); - return; - } - else - { - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." }); - } - } - }).RequireRateLimiting("auth"); - - - app.MapGet("/api/pastes/archive", async (HttpContext context) => - { - var queries = context.Request.Query; - if (!queries.ContainsKey("page") && !queries.ContainsKey("limit")) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); - return; - } - var page = queries.ContainsKey("page") ? Convert.ToInt32(queries["page"]) : 0; - var limit = queries.ContainsKey("limit") ? Convert.ToInt32(queries["limit"]) : 10; - int pages = await Database.EnumeratePastes() / limit; - - if (page < 0 || limit <= 0 || limit > 25) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid page or limit." }); - return; - } - if (page > pages) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Page out of range.", pages }); - return; - } - - using (var connection = new SqliteConnection(MainDatabaseConnection)) - { - await connection.OpenAsync(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT * FROM pastes WHERE Visibility NOT IN (1, 2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; - command.Parameters.AddWithValue("@Limit", limit); - command.Parameters.AddWithValue("@Offset", page * limit); - using (var reader = await command.ExecuteReaderAsync()) - { - if (!reader.HasRows) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "No pastes found." }); - return; - } - var pastes = new List(); - while (await reader.ReadAsync()) - { - pastes.Add(new - { - UUID = reader.GetString(1), - ID = reader.GetString(2), - Visibility = reader.GetInt32(3), - Title = reader.IsDBNull(4) ? null : reader.GetString(4), - AuthorUUID = reader.GetString(5), - Created = reader.GetInt64(7), - Edited = reader.GetInt64(8), - Size = reader.GetInt32(9), - TrueSize = reader.GetInt32(10), - Views = reader.GetInt32(11), - Syntax = reader.IsDBNull(12) ? null : reader.GetString(12) - }); - } - - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, pastes, pages }); - return; - } - } - } - }).RequireRateLimiting("general"); - app.MapGet("/api/pastes/my", async (HttpContext context) => - { - var requestdetails = GetRequestDetails(context); - if (string.IsNullOrEmpty(requestdetails.Token)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." }); - return; - } - - var user = await Database.UserFromToken(requestdetails.Token); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." }); - return; - } - var queries = context.Request.Query; - if (!queries.ContainsKey("page") && !queries.ContainsKey("limit")) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); - return; - } - var page = queries.ContainsKey("page") ? Convert.ToInt32(queries["page"]) : 0; - var limit = queries.ContainsKey("limit") ? Convert.ToInt32(queries["limit"]) : 10; - if (page < 0 || limit <= 0 || limit > 25) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid page or limit." }); - return; - } - int pages = await Database.EnumerateUserPastes(user) / limit; - if (page > pages) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Page out of range.", pages }); - return; - } - using (var connection = new SqliteConnection(MainDatabaseConnection)) - { - await connection.OpenAsync(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; - command.Parameters.AddWithValue("@AuthorUUID", user.UUID); - command.Parameters.AddWithValue("@Limit", limit); - command.Parameters.AddWithValue("@Offset", page * limit); - using (var reader = await command.ExecuteReaderAsync()) - { - if (!reader.HasRows) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, error = true, message = "No pastes found." }); - return; - } - var pastes = new List(); - while (await reader.ReadAsync()) - { - pastes.Add(new Paste - { - UUID = reader.GetString(1), - ID = reader.GetString(2), - Visibility = reader.GetInt32(3), - Title = reader.IsDBNull(4) ? null : reader.GetString(4), - AuthorUUID = reader.GetString(5), - Created = reader.GetInt64(7), - Edited = reader.GetInt64(8), - Size = reader.GetInt32(9), - TrueSize = reader.GetInt32(10), - Views = reader.GetInt32(11), - Syntax = reader.IsDBNull(12) ? null : reader.GetString(12) - }); - } - - context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, pastes, pages }); - return; - } - } - } - - }); - app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) => { var uuid = context.Request.RouteValues["uuid"].ToString() ?? null; @@ -720,66 +464,6 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = true, info }); }).RequireRateLimiting("general"); - app.MapGet("/admin/{useruuid}/reset-password", async (HttpContext context) => - { - var requestdetails = GetRequestDetails(context); - var user = await Database.UserFromToken(requestdetails.Token); - if (user == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." }); - return; - } - if (user.Type != 255) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." }); - return; - } - - var useruuid = context.Request.RouteValues["useruuid"].ToString() ?? null; - if (string.IsNullOrEmpty(useruuid)) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." }); - return; - } - var targetuser = await Database.UserFromUUID(useruuid); - if (targetuser == null) - { - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); - return; - } - string uuid = Guid.NewGuid().ToString(); - string url = GenerateRandomString(32); - string token = GenerateToken(); - using (var connection = new SqliteConnection(MainDatabaseConnection)) - { - await connection.OpenAsync(); - var expiry = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "INSERT INTO passwordresets (UUID, USERUUID, URL, Token,Created, Expirary) VALUES (@UUID, @USERUUID, @URL, @Token,@Created, @Expirary);"; - command.Parameters.AddWithValue("@UUID", uuid); - command.Parameters.AddWithValue("@USERUUID", targetuser.UUID); - command.Parameters.AddWithValue("@URL", url); - command.Parameters.AddWithValue("@Token", token); - command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); - command.Parameters.AddWithValue("@Expirary", expiry); - await command.ExecuteNonQueryAsync(); - } - await connection.CloseAsync(); - } - var resetlink = $"{context.Request.Scheme}://{context.Request.Host}/reset-password?uuid={uuid}&url={url}&token={token}"; - - context.Response.StatusCode = 200; - - context.Response.Headers.Add("Content-Type", "application/json"); - await context.Response.WriteAsJsonAsync(new { success = true, resetlink, uuid, url, token }); - }); - - #endregion app.MapControllers(); @@ -789,40 +473,6 @@ namespace SharpbinV2.Server } #region Helper Functions - static JObject TryParse(string json) - { - try - { - return JObject.Parse(json); - } - catch (Exception ex) - { - return null; - } - } - static JArray TryParseArray(string json) - { - try - { - return JArray.Parse(json); - } - catch (Exception ex) - { - return null; - } - } - static string GenerateToken() - { - string randomstring = GenerateRandomString(32); - string randomguid = Guid.NewGuid().ToString(); - return Convert.ToBase64String(Encoding.UTF8.GetBytes(Bcrypt.HashPassword(randomstring + randomguid, Bcrypt.GenerateSalt(10)))); - } - static string GenerateRandomString(int length) - { - var random = new Random(); - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray()); - } static RequestDetails GetRequestDetails(HttpContext context) { var requestdetails = new RequestDetails(); @@ -852,18 +502,6 @@ namespace SharpbinV2.Server return requestdetails; } - static string FormatBytes(long bytes) - { - string[] sizes = { "B", "KB", "MB", "GB", "TB" }; - double len = bytes; - int order = 0; - while (len >= 1024 && order < sizes.Length - 1) - { - order++; - len = len / 1024; - } - return $"{len:0.##} {sizes[order]}"; - } #endregion static async Task Initialize() { diff --git a/SharpbinV2.Server/Services/DatabaseService.cs b/SharpbinV2.Server/Services/DatabaseService.cs index af905bb..2a80300 100644 --- a/SharpbinV2.Server/Services/DatabaseService.cs +++ b/SharpbinV2.Server/Services/DatabaseService.cs @@ -546,7 +546,7 @@ namespace SharpbinV2.Server.Services { if (!reader.HasRows) return null; - var views = new List(); + var views = new List(); while (await reader.ReadAsync()) { views.Add(new View @@ -569,5 +569,104 @@ namespace SharpbinV2.Server.Services return null; } } + public async Task?> GetPastes(int limit, int page, ILogger logger) + { + if (limit <= 0 || page < 0) + return null; + try + { + using (var connection = new SqliteConnection(_connectionString)) + { + await connection.OpenAsync(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT * FROM pastes WHERE Visibility NOT IN (1,2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; + command.Parameters.AddWithValue("@Limit", limit); + command.Parameters.AddWithValue("@Offset", limit * page); + using (var reader = await command.ExecuteReaderAsync()) + { + if (!reader.HasRows) + return null; + var pastes = new List(); + while (await reader.ReadAsync()) + { + pastes.Add(new Paste + { + UID = reader.GetInt32(0), + UUID = reader.GetString(1), + ID = reader.GetString(2), + Visibility = reader.GetInt32(3), + Title = reader.IsDBNull(4) ? null : reader.GetString(4), + AuthorUUID = reader.GetString(5), + FilePath = reader.GetString(6), + Created = reader.GetInt64(7), + Edited = reader.GetInt64(8), + Size = reader.GetInt32(9), + TrueSize = reader.GetInt32(10), + Views = reader.GetInt32(11), + Syntax = reader.IsDBNull(12) ? null : reader.GetString(12) + }); + } + return pastes; + } + } + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get pastes from database."); + return null; + } + } + public async Task?> GetPastesFromUser(User user, int limit, int page, ILogger logger) + { + if (user == null || limit <= 0 || page < 0) + return null; + try + { + using (var connection = new SqliteConnection(_connectionString)) + { + await connection.OpenAsync(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;"; + command.Parameters.AddWithValue("@AuthorUUID", user.UUID); + command.Parameters.AddWithValue("@Limit", limit); + command.Parameters.AddWithValue("@Offset", limit * page); + using (var reader = await command.ExecuteReaderAsync()) + { + if (!reader.HasRows) + return null; + var pastes = new List(); + while (await reader.ReadAsync()) + { + pastes.Add(new Paste + { + UID = reader.GetInt32(0), + UUID = reader.GetString(1), + ID = reader.GetString(2), + Visibility = reader.GetInt32(3), + Title = reader.IsDBNull(4) ? null : reader.GetString(4), + AuthorUUID = reader.GetString(5), + FilePath = reader.GetString(6), + Created = reader.GetInt64(7), + Edited = reader.GetInt64(8), + Size = reader.GetInt32(9), + TrueSize = reader.GetInt32(10), + Views = reader.GetInt32(11), + Syntax = reader.IsDBNull(12) ? null : reader.GetString(12) + }); + } + return pastes; + } + } + } + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get user pastes from database."); + return null; + } + } } } diff --git a/SharpbinV2.Server/wwwroot/js/archive.js b/SharpbinV2.Server/wwwroot/js/archive.js index c98136e..c4c2003 100644 --- a/SharpbinV2.Server/wwwroot/js/archive.js +++ b/SharpbinV2.Server/wwwroot/js/archive.js @@ -1,5 +1,5 @@ -let pages = 0; -let currentPage = 0; +let pages = 1; +let currentPage = 1; let limit = 25; async function renderArchive(page, limit) { @@ -35,9 +35,9 @@ async function renderArchive(page, limit) { pages = archiveData.pages; currentPage = page; - pagesElement.innerText = `${page + 1}/${pages}`; - previousButton.disabled = page <= 0; - nextButton.disabled = page + 1 >= pages; + pagesElement.innerText = `${page}/${pages}`; + previousButton.disabled = page <= 1; + nextButton.disabled = page >= pages; let archiveListHTML = ""; if (pastes.length === 0) { @@ -70,7 +70,7 @@ document.addEventListener('DOMContentLoaded', async () => { let page = parseInt(queries.get("page")); limit = parseInt(queries.get("limit")); - if (isNaN(page) || page < 0) page = 0; + if (isNaN(page) || page < 1) page = 1; if (isNaN(limit) || limit < 1 || limit > 25) limit = 25; await renderArchive(page, limit); @@ -119,13 +119,13 @@ function formatDate(unix, relative = false) { } function nextPage() { - if (currentPage + 1 >= pages) return; + if (currentPage >= pages) return; currentPage++; updateUrlAndRender(); } function previousPage() { - if (currentPage <= 0) return; + if (currentPage <= 1) return; currentPage--; updateUrlAndRender(); } diff --git a/SharpbinV2.Server/wwwroot/js/dash.js b/SharpbinV2.Server/wwwroot/js/dash.js index c477a72..dcc600f 100644 --- a/SharpbinV2.Server/wwwroot/js/dash.js +++ b/SharpbinV2.Server/wwwroot/js/dash.js @@ -1,5 +1,5 @@ let currentPage = 1; -let totalPages = 0; +let totalPages = 1; let pastesPerPage = 10; let userPastes = []; @@ -63,7 +63,7 @@ function formatDate(date, minutes = false) { async function fetchUserPastes() { try { - const response = await fetch('/api/pastes/my?page=0&limit=15'); + const response = await fetch('/api/pastes/my?page=1&limit=15'); const pastesData = await response.json(); if (pastesData.message === 'No pastes found.' || pastesData.message === 'Page out of range.') {