mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
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.
This commit is contained in:
+109
-91
@@ -632,87 +632,10 @@ class Program
|
||||
{
|
||||
var html = File.ReadAllText("assets/archives.html");
|
||||
var page = context.Request?.Query["page"].ToString();
|
||||
|
||||
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
|
||||
if (loggedIn)
|
||||
{
|
||||
html = html.Replace("{html}", "<a href=\"/dash\">dashboard</a>");
|
||||
}
|
||||
else
|
||||
{
|
||||
html = html.Replace("{html}", "<a href=\"/login\">login</a> <a href=\"/sign-up\">sign up</a>");
|
||||
}
|
||||
|
||||
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 += $"<a title=\"{paste.Title}\" href=\"/{paste.Id}\"><li>{title} {difference} {ConvertToBytes(paste.Size)}</li></a>";
|
||||
}
|
||||
|
||||
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 = "<h2>No pastes found</h1>";
|
||||
html = html.Replace("</style>", "");
|
||||
html = html.Replace("</html>", "");
|
||||
html += ".buttons-wrapper{\r\n display: none !important;\r\n}";
|
||||
html += "</style>\n</html>";
|
||||
}
|
||||
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<int>() ?? 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<Paste> CreatePaste(string content, string title, string visibility, string UUID)
|
||||
public static async Task<Paste> 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);
|
||||
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();
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
|
||||
namespace Sharpbin
|
||||
|
||||
@@ -13,10 +13,13 @@
|
||||
<a href="/">home</a>
|
||||
<a href="/pastes">recent pastes</a>
|
||||
<a href="/archive">archive</a>
|
||||
{html}
|
||||
<a href="login" id="login-signup-btn" style="display: none;" >login</a>
|
||||
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
|
||||
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
|
||||
</div>
|
||||
<div class="nav-hamburger-menu">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list" viewBox="0 0 16 16" id="hamburger-button" style="cursor: pointer;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list"
|
||||
viewBox="0 0 16 16" id="hamburger-button" style="cursor: pointer;">
|
||||
<path fill-rule="evenodd"
|
||||
d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5" />
|
||||
</svg>
|
||||
@@ -24,7 +27,9 @@
|
||||
<a href="/">home</a>
|
||||
<a href="/pastes">recent pastes</a>
|
||||
<a href="/archive">archive</a>
|
||||
{html}
|
||||
<a href="login" id="login-signup-btn" style="display: none;" >login</a>
|
||||
<a href="sign-up" id="login-signup-btn" style="display: none;">sign up</a>
|
||||
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container-wrapper">
|
||||
@@ -32,18 +37,73 @@
|
||||
<h1>paste archive</h1>
|
||||
<input type="text" placeholder="search" class="text-input" oninput="search()">
|
||||
<div class="pastes-wrapper">
|
||||
{pastes}
|
||||
Loading...
|
||||
</div>
|
||||
<div class="buttons-wrapper">
|
||||
<a class="arrow-button" href="/archive?page={backpagenum}"><</a>
|
||||
<p>{currentpagenum}/{totalpages}</p>
|
||||
<a class="arrow-button" href="/archive?page={pagenum}">></a>
|
||||
<a class="arrow-button" id="back-page"><</a>
|
||||
<p id="page-count"></p>
|
||||
<a class="arrow-button" id="next-page">></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script>
|
||||
let searchTimeout;
|
||||
let pagenum = 1;
|
||||
|
||||
function authenticate() {
|
||||
fetch('/api/accounts/authenticate')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.message == "Authenticated") {
|
||||
document.querySelectorAll("#login-signup-btn").forEach(element => {
|
||||
element.style.display = 'none';
|
||||
});
|
||||
document.getElementById('dash-btn').style.display = 'block';
|
||||
}else{
|
||||
document.querySelectorAll("#login-signup-btn").forEach(element => {
|
||||
element.style.display = 'block';
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getPastes() {
|
||||
fetch(`/api/pastes/get`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
page: pagenum
|
||||
})
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const pastesWrapper = document.querySelector('.pastes-wrapper');
|
||||
const pageCount = document.getElementById('page-count');
|
||||
pastesWrapper.innerHTML = '';
|
||||
pageCount.innerHTML = `${pagenum}/${data.pages}`;
|
||||
if (data.pastes.length === 0) {
|
||||
pastesWrapper.innerHTML = '<h1>no pastes found</h1>';
|
||||
return;
|
||||
}
|
||||
data.pastes.forEach(paste => {
|
||||
title = paste.title.length > 30 ? paste.title.substring(0, 30) + '...' : paste.title;
|
||||
pastesWrapper.innerHTML += `<a href="/${paste.id}" title="${paste.title}"><li>${title} ${paste.date} ${paste.size}</li></a>`;
|
||||
});
|
||||
});
|
||||
}
|
||||
document.getElementById('back-page').addEventListener('click', function () {
|
||||
if (pagenum > 1) {
|
||||
pagenum--;
|
||||
getPastes();
|
||||
}
|
||||
});
|
||||
document.getElementById('next-page').addEventListener('click', function () {
|
||||
pagenum++;
|
||||
getPastes();
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
var mobile = window.mobileCheck();
|
||||
@@ -51,6 +111,8 @@
|
||||
document.querySelector('.nav-div').style.display = 'none';
|
||||
document.querySelector('.nav-hamburger-menu').style.display = 'flex';
|
||||
}
|
||||
authenticate();
|
||||
getPastes();
|
||||
});
|
||||
|
||||
document.getElementById("hamburger-button").addEventListener("click", function () {
|
||||
|
||||
@@ -308,6 +308,8 @@
|
||||
border: #2a2a2a00 2px solid;
|
||||
cursor: pointer;
|
||||
font-size: 1.2em;
|
||||
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
|
||||
@@ -92,11 +92,12 @@
|
||||
.then(response => response.json())
|
||||
.then(json => {
|
||||
info = json;
|
||||
title = json.title.length > 40 ? json.title.substring(0, 40) + '...' : json.title;
|
||||
document.getElementById('uploader-username').innerText = json.uploader || 'Anonymous';
|
||||
document.getElementById('creationdate').innerText = localizeDateTime(json.date);
|
||||
document.getElementById('paste-size').innerText = json.size;
|
||||
document.getElementById('paste-size').title = `Compressed Size: ${json.compressedSize}`;
|
||||
document.getElementById('paste-title').innerText = json.title;
|
||||
document.getElementById('paste-title').innerText = title;
|
||||
document.getElementById('paste-title').title = json.title;
|
||||
if (json.title == "") {
|
||||
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
|
||||
|
||||
Reference in New Issue
Block a user