Pretty big update, this adds file compression on the server side to preserve space on the disk.

Switched the paste info displaying from server side to client side, which also added a new api to fetch the info.
A new api to check if the user is authorized, (/api/accounts/authenticated)

## Commit Message Details Below Generated by Copilot
Add compression, and install script

Added EncryptByteArray and DecryptByteArray methods to the Encryption class for handling byte array encryption and decryption.
Removed unused namespaces from Program.cs.
Replaced direct file content reading and HTML manipulation with database queries and JSON responses for better error handling and response consistency.
Added JSON error responses for various error conditions.
Implemented content compression and decompression using GZip in Compression.cs to reduce file size and improve performance.
Updated paste creation and retrieval logic to handle compressed and encrypted content.
Added new API endpoints for fetching paste information and checking user authentication status.
Modified HTML templates to dynamically fetch and display paste information and user authentication status using JavaScript.
Added Paste UID property to the Paste class to store unique identifiers for pastes.
Created a new Compression class to handle string compression and decompression using GZip.
Updated the InitializeAsync method to create the pastes.sqlite file if it does not exist.
Enhanced the user interface to show or hide elements based on user authentication status and paste ownership (client side).
Improved error handling and user feedback in the JavaScript code.
Added logic to handle compressed and encrypted content in various parts of the application.
Added a new Bash script (install.sh) to install Sharpbin on a Linux system, which includes fetching the latest release, extracting it, and configuring Cloudflare keys.
This commit is contained in:
whoswhip
2024-10-18 20:12:48 -04:00
parent 65ddb4b722
commit eb21e6d662
7 changed files with 371 additions and 74 deletions
+40
View File
@@ -0,0 +1,40 @@
using System.IO.Compression;
using System.Text;
namespace Sharpbin
{
public class Compression
{
public static byte[] CompressString(string text)
{
byte[] compressedBytes;
using (var ms = new MemoryStream())
{
using (var cs = new GZipStream(ms, CompressionMode.Compress))
{
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
cs.Write(inputBytes, 0, inputBytes.Length);
}
compressedBytes = ms.ToArray();
}
return compressedBytes;
}
public static string DecompressString(byte[] compressedBytes)
{
string decompressedText;
using (var ms = new MemoryStream(compressedBytes))
{
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
{
using (var sr = new StreamReader(cs))
{
decompressedText = sr.ReadToEnd();
}
}
}
return decompressedText;
}
}
}
+49
View File
@@ -31,6 +31,31 @@ namespace Sharpbin
return Convert.ToBase64String(encryptedBytes); return Convert.ToBase64String(encryptedBytes);
} }
public static string EncryptByteArray(byte[] bytes, string password)
{
byte[] encryptedBytes;
using (Aes aes = Aes.Create())
{
aes.KeySize = 256;
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32, ' '));
aes.IV = new byte[16];
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(bytes, 0, bytes.Length);
}
encryptedBytes = ms.ToArray();
}
}
return Convert.ToBase64String(encryptedBytes);
}
public static string DecryptString(string input, string password) public static string DecryptString(string input, string password)
{ {
@@ -59,5 +84,29 @@ namespace Sharpbin
return decryptedText; return decryptedText;
} }
public static byte[] DecryptByteArray(byte[] input, string password)
{
byte[] decryptedBytes;
using (Aes aes = Aes.Create())
{
aes.KeySize = 256;
aes.Key = Encoding.UTF8.GetBytes(password.PadRight(32, ' '));
aes.IV = new byte[16];
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (var ms = new MemoryStream(input))
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
decryptedBytes = new byte[ms.Length];
cs.Read(decryptedBytes, 0, decryptedBytes.Length);
}
}
}
return decryptedBytes;
}
} }
} }
+155 -57
View File
@@ -5,8 +5,6 @@ using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using System.Text; using System.Text;
using Sharpbin; using Sharpbin;
using Microsoft.AspNetCore.ResponseCompression;
using System.Reflection.Metadata;
class Program class Program
{ {
@@ -402,8 +400,6 @@ class Program
context.Response.Redirect("/paste-not-found"); context.Response.Redirect("/paste-not-found");
return; return;
} }
var content = File.ReadAllText($"pastes/{id}.txt");
content = content.Replace("\n", "<br>").Replace("\r", "");
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -452,24 +448,6 @@ class Program
user.LastLoginDate = userReader.GetString(5); user.LastLoginDate = userReader.GetString(5);
user.Type = userReader.GetInt32(6); user.Type = userReader.GetInt32(6);
} }
if (paste.Uploader.Contains("Anonymous"))
{
user.Username = "Anonymous";
}
else
{
user.Username = $"<a class=\"user-a\" href=\"/u/{user.Username}\">{user.Username}</a>";
}
if (paste.Title == "" || string.IsNullOrEmpty(paste.Title))
{
paste.Title = $"Untitled {reader.GetString(0)}";
title = $"Untitled {reader.GetString(0)}";
}
if (paste.Title.Length > 40)
{
title = paste.Title.Substring(0, 40) + "...";
}
var html = File.ReadAllText("assets/paste.html"); var html = File.ReadAllText("assets/paste.html");
if (paste.Visibility == "Private") if (paste.Visibility == "Private")
@@ -477,33 +455,7 @@ class Program
html = File.ReadAllText("assets/privatepaste.html"); html = File.ReadAllText("assets/privatepaste.html");
html = html.Replace("{password}", ""); html = html.Replace("{password}", "");
} }
html = html.Replace("{pastetitleattribute}", paste.Title);
html = html.Replace("{pastetitle}", title);
html = html.Replace("{content}", content);
html = html.Replace("{pasteid}", paste.Id); html = html.Replace("{pasteid}", paste.Id);
html = html.Replace("{username}", user.Username);
html = html.Replace("{creationdate}", paste.UnixDate.ToString());
html = html.Replace("{pastesize}", ConvertToBytes(paste.Size));
if (paste.Uploader == loggedInUser.UUID || loggedInUser.Type == 255)
{
html = html.Replace("{deletebutton}", "<button id=\"delete-button\" class=\"button\">delete</button>");
html = html.Replace("{deletescript}", " document.getElementById(\"delete-button\").addEventListener(\"click\", function () {\r\n alert(\"Deletion cannot be undone. Are you sure you want to delete this paste?\");\r\n var requestUrl = \"/api/pastes/delete\";\r\n fetch(requestUrl, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: JSON.stringify({\r\n id: \"" + paste.Id + "\"\r\n })\r\n })\r\n .then(response => response.json())\r\n .then(obj => {\r\n const result = JSON.parse(obj);\r\n if (result.message != null) {\r\n window.location.href = `/`;\r\n }\r\n })\r\n });");
}
else
{
html = html.Replace("{deletebutton}", "");
html = html.Replace("{deletescript}", "");
}
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>");
}
context.Response.ContentType = "text/html"; context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html); await context.Response.WriteAsync(html);
@@ -518,6 +470,10 @@ class Program
if (!File.Exists(filePath)) if (!File.Exists(filePath))
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var json = new JObject
{
["error"] = "Paste not found"
};
return; return;
} }
if (id.Length == 24) if (id.Length == 24)
@@ -526,6 +482,10 @@ class Program
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
{ {
context.Response.StatusCode = 401; context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Password required"
};
return; return;
} }
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
@@ -539,6 +499,10 @@ class Program
if (!reader.HasRows) if (!reader.HasRows)
{ {
context.Response.StatusCode = 404; context.Response.StatusCode = 404;
var json = new JObject
{
["error"] = "Paste not found"
};
return; return;
} }
var paste = new PrivatePaste var paste = new PrivatePaste
@@ -555,11 +519,29 @@ class Program
if (hashedPassword != paste.Password && paste.Visibility != "Private") if (hashedPassword != paste.Password && paste.Visibility != "Private")
{ {
context.Response.StatusCode = 401; context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Invalid password"
};
return; return;
} }
string text = Encryption.DecryptString(await File.ReadAllTextAsync(filePath), password); try
{
string decompressedEncryptedContent = Compression.DecompressString(await File.ReadAllBytesAsync(filePath));
string text = Encryption.DecryptString(decompressedEncryptedContent, password);
context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(text); await context.Response.WriteAsync(text);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
context.Response.StatusCode = 401;
var json = new JObject
{
["error"] = "Invalid password or Failed to decompress text"
};
return;
}
return; return;
} }
} }
@@ -569,11 +551,26 @@ class Program
context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/plain";
context.Response.ContentLength = fileSize; context.Response.ContentLength = fileSize;
try
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{ {
await fileStream.CopyToAsync(context.Response.Body); var compressedContent = await File.ReadAllBytesAsync($"pastes/{id}.txt");
var content = Compression.DecompressString(compressedContent);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
await stream.CopyToAsync(context.Response.Body);
} }
}
catch
{
var text = await File.ReadAllTextAsync(filePath);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
{
await stream.CopyToAsync(context.Response.Body);
}
return;
}
}).RequireRateLimiting("fixed-bigger"); }).RequireRateLimiting("fixed-bigger");
app.MapGet("/pastes", async (HttpContext context) => app.MapGet("/pastes", async (HttpContext context) =>
@@ -1878,6 +1875,69 @@ class Program
} }
}).RequireRateLimiting("fixed"); }).RequireRateLimiting("fixed");
app.MapGet("/api/pastes/info", async (HttpContext context) =>
{
var query = context.Request.Query;
var id = query["id"].ToString();
if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request" }.ToString());
return;
}
if (!File.Exists($"pastes/{id}.txt"))
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Paste not found" }.ToString());
return;
}
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM pastes WHERE ID = @ID";
command.Parameters.AddWithValue("@ID", id);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Paste not found" }.ToString());
return;
}
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),
UID = long.Parse(reader.GetString(0)),
Uploader = reader.GetString(6)
};
var filelength = new FileInfo($"pastes/{id}.txt").Length;
JObject responseJson = new JObject();
responseJson["title"] = paste.Title;
responseJson["id"] = paste.Id;
responseJson["uid"] = paste.UID;
responseJson["size"] = ConvertToBytes(paste.Size);
responseJson["compressedSize"] = ConvertToBytes(filelength.ToString());
responseJson["date"] = paste.UnixDate;
responseJson["visibility"] = paste.Visibility;
responseJson["uploader"] = paste.Uploader;
Console.WriteLine(responseJson);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(responseJson.ToString());
}
}).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) => app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) =>
{ {
var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
@@ -1948,9 +2008,10 @@ class Program
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid password" }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid password" }.ToString());
return; return;
} }
} }
string decryptedText = Encryption.DecryptString(File.ReadAllText($"pastes/{pasteId}.txt"), password); string decompressedEncryptedText = Compression.DecompressString(File.ReadAllBytes($"pastes/{pasteId}.txt"));
string decryptedText = Encryption.DecryptString(decompressedEncryptedText, password);
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString()); await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString());
@@ -2225,6 +2286,39 @@ class Program
} }
} }
})).RequireRateLimiting("fixed"); })).RequireRateLimiting("fixed");
app.MapGet("/api/accounts/authenticated", (async (HttpContext context) =>
{
var token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token))
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
var user = await GetLoggedInUserAsync(token);
if (user == null)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
var responseJson = new JObject();
responseJson["message"] = "Authenticated";
responseJson["username"] = user.Username;
responseJson["uid"] = user.UID;
responseJson["uuid"] = user.UUID;
responseJson["type"] = accountType[user.Type];
responseJson["state"] = accountState[user.State];
responseJson["creationDate"] = DateTimeOffset.FromUnixTimeSeconds(long.Parse(user.CreationDate)).ToString().Split("+")[0].TrimEnd();
responseJson["lastLoginDate"] = DateTimeOffset.FromUnixTimeSeconds(long.Parse(user.LastLoginDate)).ToString().Split("+")[0].TrimEnd();
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(responseJson.ToString());
}));
#endregion #endregion
@@ -2243,7 +2337,8 @@ class Program
Id = GenerateRandomString(12), Id = GenerateRandomString(12),
Uploader = UUID Uploader = UUID
}; };
await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", paste.Content); var compressedText = Compression.CompressString(paste.Content);
await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2261,7 +2356,8 @@ class Program
} }
public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID) public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID)
{ {
string encryptedText = Encryption.EncryptString($"{content}", password); string encryptedText = Encryption.EncryptString(content, password);
var compressedEncryptedText = Compression.CompressString(encryptedText);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt); string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var paste = new PrivatePaste var paste = new PrivatePaste
{ {
@@ -2273,7 +2369,7 @@ class Program
Password = passwordHash Password = passwordHash
}; };
await File.WriteAllTextAsync($"pastes/{paste.Id}.txt", encryptedText); await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedEncryptedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2464,6 +2560,7 @@ class Program
{ {
if (!File.Exists("pastes.sqlite")) if (!File.Exists("pastes.sqlite"))
{ {
File.Create("pastes.sqlite").Close();
using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{ {
await connection.OpenAsync(); await connection.OpenAsync();
@@ -2542,6 +2639,7 @@ public class Paste
public long? UnixDate { get; set; } public long? UnixDate { get; set; }
public string? Visibility { get; set; } public string? Visibility { get; set; }
public string? Id { get; set; } public string? Id { get; set; }
public long? UID { get; set; }
public string? Uploader { get; set; } public string? Uploader { get; set; }
} }
public class PrivatePaste : Paste public class PrivatePaste : Paste
+2 -2
View File
@@ -49,7 +49,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="pastes.sqlite"> <Content Include="pastes.sqlite">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
</ItemGroup> </ItemGroup>
@@ -90,7 +90,7 @@
<ItemGroup> <ItemGroup>
<Content Update="config.json"> <Content Update="config.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>
</ItemGroup> </ItemGroup>
+48 -7
View File
@@ -4,7 +4,6 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{pastetitle}</title>
</head> </head>
<body> <body>
@@ -12,7 +11,9 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
<div class="nav-hamburger-menu"> <div class="nav-hamburger-menu">
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list" <svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="currentColor" class="bi bi-list"
@@ -24,13 +25,15 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
</div> </div>
<div class="container-wrapper"> <div class="container-wrapper">
<div class="paste-container"> <div class="paste-container">
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1> <h1 id="paste-title" ></h1>
<h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3> <h3 class="uploader-text"><a id="uploader-username" ></a> <a id="creationdate"></a> <a id="paste-size"></a></h3>
<div class="paste-wrapper"> <div class="paste-wrapper">
<p id="text"></p> <p id="text"></p>
</div> </div>
@@ -40,21 +43,60 @@
</a> </a>
<button id="copy-button" class="button">copy</button> <button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button> <button id="download-button" class="button">download</button>
{deletebutton} <button id="delete-button" class="button" style="display: none;">delete</button>
</div> </div>
</div> </div>
</div> </div>
</body> </body>
<script> <script>
info = "";
function localizeDateTime(unixTimestamp) { function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); const date = new Date(unixTimestamp * 1000);
return date.toLocaleString(); return date.toLocaleString();
} }
function authenticated() {
fetch('/api/accounts/authenticated')
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username) {
document.getElementById('delete-button').style.display = 'block';
}
document.getElementById('login-signup-btn').style.display = 'none';
document.getElementById('dash-btn').style.display = 'block';
}
});
}
function fetchInfo() {
fetch('/api/pastes/info?id={pasteid}')
.then(response => response.json())
.then(data => {
const json = JSON.parse(data);
info = json;
document.getElementById('uploader-username').innerText = json.uploader;
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').title = json.title;
if (json.title == "") {
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
document.title = `Untitled ${json.uid}`;
}
if (json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
document.getElementById('uploader-username').innerText = 'Anonymous';
} else {
document.getElementById('uploader-username').href = `/u/${json.uploader}`;
}
});
}
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {
const creationdateElement = document.getElementById('creationdate'); const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim(); const creationdateText = creationdateElement.innerText.trim();
const textElement = document.getElementById('text'); const textElement = document.getElementById('text');
fetchInfo();
authenticated();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
textElement.innerText = "Loading..."; textElement.innerText = "Loading...";
@@ -109,7 +151,6 @@
element.click(); element.click();
document.body.removeChild(element); document.body.removeChild(element);
}); });
{ deletescript }
</script> </script>
+51 -5
View File
@@ -12,7 +12,9 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
<div class="nav-hamburger-menu"> <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;">
@@ -23,13 +25,15 @@
<a href="/">home</a> <a href="/">home</a>
<a href="/pastes">recent pastes</a> <a href="/pastes">recent pastes</a>
<a href="/archive">archive</a> <a href="/archive">archive</a>
{html} <a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<a href="dash" id="dash-btn" style="display: none;">dashboard</a>
</div> </div>
</div> </div>
<div class="container-wrapper"> <div class="container-wrapper">
<div class="paste-container"> <div class="paste-container">
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1> <h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1>
<h3 class="uploader-text">{username} <a id="creationdate">{creationdate}</a> {pastesize}</h3> <h3 class="uploader-text"><a id="uploader-username" ></a> <a id="creationdate"></a> <a id="paste-size"></a></h3>
<div class="paste-wrapper"> <div class="paste-wrapper">
<p id="text"></p> <p id="text"></p>
</div> </div>
@@ -39,7 +43,7 @@
</a> </a>
<button id="copy-button" class="button">copy</button> <button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button> <button id="download-button" class="button">download</button>
{deletebutton} <button id="delete-button" class="button" style="display: none;">delete</button>
</div> </div>
</div> </div>
<div class="passwordDiv"> <div class="passwordDiv">
@@ -55,6 +59,46 @@
</div> </div>
</body> </body>
<script> <script>
info = "";
function authenticated() {
fetch('/api/accounts/authenticated')
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username) {
document.getElementById('delete-button').style.display = 'block';
}
document.getElementById('login-signup-btn').style.display = 'none';
document.getElementById('dash-btn').style.display = 'block';
}
});
}
function fetchInfo() {
fetch('/api/pastes/info?id={pasteid}')
.then(response => response.json())
.then(data => {
const json = JSON.parse(data);
info = json;
document.getElementById('uploader-username').innerText = json.uploader;
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').title = json.title;
if (json.title == "") {
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
document.title = `Untitled ${json.uid}`;
}
if (json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
document.getElementById('uploader-username').innerText = 'Anonymous';
} else {
document.getElementById('uploader-username').href = `/u/${json.uploader}`;
}
});
}
document.getElementById("submitPassword").addEventListener("click", function () { document.getElementById("submitPassword").addEventListener("click", function () {
var password = document.getElementById("password").value; var password = document.getElementById("password").value;
fetch(`/api/pastes/password/{pasteid}`, { fetch(`/api/pastes/password/{pasteid}`, {
@@ -74,7 +118,7 @@
textElement.innerText = result.content; textElement.innerText = result.content;
document.querySelector(".passwordDiv").style.display = "none"; document.querySelector(".passwordDiv").style.display = "none";
const viewRawButton = document.getElementById('view-raw-a'); const viewRawButton = document.getElementById('view-raw-a');
viewRawButton.href = `/raw/{pasteid}?password=${password}`; viewRawButton.href = `/raw/{pasteid}?password=` + password;
} }
else { else {
notification(`Error: ${result.error}`); notification(`Error: ${result.error}`);
@@ -89,6 +133,8 @@
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
const creationdateElement = document.getElementById('creationdate'); const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim(); const creationdateText = creationdateElement.innerText.trim();
fetchInfo();
authenticated();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
var mobile = window.mobileCheck(); var mobile = window.mobileCheck();
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
############################################
#### Sharpbin Linux installer ####
############################################
##
## This is a semi completed script to install Sharpbin on Linux, however it does not set it as a system daemon/service, cause idk how to do that lol
##
sudo mkdir -p /usr/local/bin/Sharpbin
cd /usr/local/bin/Sharpbin
curl -s "https://api.github.com/repos/whoswhip/Sharpbin/releases/latest" | jq -r '.assets[] | select(.name | test("sharpbin-linux.tar$")) | .browser_download_url' | xargs -I {} curl -L -o sharpbin-linux.tar {}
tar -xvf sharpbin-linux.tar
chmod +x Sharpbin
echo "Enter your cloudflare sitekey: "
read sitekey
echo "Enter your cloudflare secretkey: "
read secretkey
echo "{ \"CF_TurnstileSiteKey\": \"$sitekey\", \"CF_TurnstileSecret\": \"$secretkey\" }" > config.json