Refactor for async operations and add new features

Updated Compression.cs to support asynchronous operations, including new methods for decompressing byte arrays and checking compression status.
Enhanced Logging.cs with asynchronous logging methods.
Refactored Program.cs to replace synchronous calls with asynchronous ones, added a new endpoint for editing pastes, and implemented rate limiting.
Removed outdated logging configuration.
This commit is contained in:
whoswhip
2024-10-19 00:05:59 -04:00
parent c28b9b92b1
commit bdcc3a1dc6
5 changed files with 403 additions and 117 deletions
+26 -4
View File
@@ -1,11 +1,12 @@
using System.IO.Compression;
using System.Text;
using System.Threading.Tasks;
namespace Sharpbin
{
public class Compression
{
public static byte[] CompressString(string text)
public static async Task<byte[]> CompressString(string text)
{
byte[] compressedBytes;
using (var ms = new MemoryStream())
@@ -13,13 +14,14 @@ namespace Sharpbin
using (var cs = new GZipStream(ms, CompressionMode.Compress))
{
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
cs.Write(inputBytes, 0, inputBytes.Length);
await cs.WriteAsync(inputBytes, 0, inputBytes.Length);
}
compressedBytes = ms.ToArray();
}
return compressedBytes;
}
public static string DecompressString(byte[] compressedBytes)
public static async Task<string> DecompressByteArrayToString(byte[] compressedBytes)
{
string decompressedText;
using (var ms = new MemoryStream(compressedBytes))
@@ -28,13 +30,33 @@ namespace Sharpbin
{
using (var sr = new StreamReader(cs))
{
decompressedText = sr.ReadToEnd();
decompressedText = await sr.ReadToEndAsync();
}
}
}
return decompressedText;
}
public static async Task<byte[]> DecompressByteArray(byte[] compressedBytes)
{
byte[] decompressedBytes;
using (var ms = new MemoryStream(compressedBytes))
{
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
{
using (var msDecompressed = new MemoryStream())
{
await cs.CopyToAsync(msDecompressed);
decompressedBytes = msDecompressed.ToArray();
}
}
}
return decompressedBytes;
}
public static bool IsCompressed(byte[] data)
{
return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;
}
}
}
+26 -2
View File
@@ -1,8 +1,9 @@
namespace Sharpbin
using Org.BouncyCastle.Asn1.Cms;
namespace Sharpbin
{
public class Logging
{
public static string Api_CreateMessage = "";
public static async Task<Log> LogRequestAsync(HttpContext context)
{
Log log = new Log();
@@ -14,6 +15,29 @@
log.IP = context.Request.Headers["X-Forwarded-For"].ToString() ?? context.Connection.RemoteIpAddress.ToString();
return log;
}
public static async Task LogError(string message)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"[ERROR - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[ERROR - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
public static async Task LogInfo(string message)
{
Console.WriteLine($"[INFO - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[INFO - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
public static async Task LogWarning(string message)
{
Console.BackgroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine($"[WARNING - {DateTime.Now}] {message}");
await File.AppendAllTextAsync("logs.log", $"[WARNING - {DateTime.Now}] {message}\n");
Console.ResetColor();
}
}
public class Log
{
+141 -46
View File
@@ -528,14 +528,14 @@ class Program
}
try
{
string decompressedEncryptedContent = Compression.DecompressString(await File.ReadAllBytesAsync(filePath));
string decompressedEncryptedContent = await Compression.DecompressByteArrayToString(await File.ReadAllBytesAsync(filePath));
string text = Encryption.DecryptString(decompressedEncryptedContent, password);
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(text);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
await Logging.LogError(e.Message);
context.Response.StatusCode = 401;
var json = new JObject
{
@@ -552,26 +552,15 @@ class Program
context.Response.ContentType = "text/plain";
context.Response.ContentLength = fileSize;
try
var _content = await File.ReadAllBytesAsync(filePath);
if (Compression.IsCompressed(_content))
{
var compressedContent = await File.ReadAllBytesAsync($"pastes/{id}.txt");
var content = Compression.DecompressString(compressedContent);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
_content = await Compression.DecompressByteArray(_content);
}
using (var stream = new MemoryStream(_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");
app.MapGet("/pastes", async (HttpContext context) =>
@@ -1126,8 +1115,7 @@ class Program
punishedUsersCommand.Parameters.AddWithValue("@Punisher", loggedInUser.UUID);
await punishedUsersCommand.ExecuteNonQueryAsync();
}
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}\n");
await Logging.LogInfo($"Account {user.Username}({user.UUID}) has been banned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User banned" }.ToString());
@@ -1184,8 +1172,7 @@ class Program
return;
}
var user = await UnbanUUIDAsync(uuid);
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}\n");
await Logging.LogInfo($"Account {user.Username}({user.UUID}) has been unbanned by {loggedInUser.Username}({loggedInUser.UUID}) for {reason}");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "User unbanned" }.ToString());
@@ -1281,8 +1268,7 @@ class Program
deleteLoginsCommand.Parameters.AddWithValue("@UUID", uuid);
await deleteLoginsCommand.ExecuteNonQueryAsync();
}
Console.WriteLine($"[{DateTime.Now}] Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})");
await File.AppendAllTextAsync("logs.log", $"[{DateTime.Now}] Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})\n");
await Logging.LogInfo($"Account {user.Username}({user.UUID}) has had their password changed by {loggedInUser.Username}({loggedInUser.UUID})");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Password changed", ["password"] = newPassword }.ToString());
@@ -1481,7 +1467,7 @@ class Program
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(usersJson.ToString());
}
});
}).RequireRateLimiting("fixed-bigger"); ;
#endregion
@@ -1595,8 +1581,7 @@ class Program
_responseJson["pasteVisibility"] = privatePaste.Visibility;
Log _log = await Logging.LogRequestAsync(context);
Console.WriteLine($"[{_time}] Private Paste created, {ConvertToBytes(privatePaste.Size ?? string.Empty)}, {privatePaste.Id} by {uploaderUUID}");
await File.AppendAllTextAsync("logs.log", $"[{_time}] {privatePaste.Id} {_log.IP} {_log.Method} {_log.Path} {_log.UserAgent} {_log.Referer} {_log.Body} {uploaderUUID}\n");
await Logging.LogInfo($"Private Paste created, {ConvertToBytes(privatePaste.Size ?? string.Empty)}, {privatePaste.Id} by {uploaderUUID}");
await context.Response.WriteAsJsonAsync(_responseJson.ToString());
return;
}
@@ -1627,13 +1612,101 @@ class Program
Log log = await Logging.LogRequestAsync(context);
Console.WriteLine($"[{time}] Paste created, {ConvertToBytes(paste.Size ?? string.Empty)}, {paste.Id} by {uploaderUUID}");
await File.AppendAllTextAsync("logs.log", $"[{time}] {paste.Id} {log.IP} {log.Method} {log.Path} {log.UserAgent} {log.Referer} {log.Body} {uploaderUUID}\n");
await Logging.LogInfo($"Paste created, {ConvertToBytes(paste.Size ?? string.Empty)}, {paste.Id} by {uploaderUUID}");
await context.Response.WriteAsJsonAsync(responseJson.ToString());
return;
}).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/edit", async (HttpContext context) =>
{
var token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
var user = await GetLoggedInUserAsync(token);
if (user.UUID == null || user.UID == null)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Unauthorized" }.ToString());
return;
}
if (user.State != 0)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "User is banned/suspended" }.ToString());
return;
}
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
try
{
JObject.Parse(requestBody);
}
catch
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid JSON" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
var id = SanitizeInput(data["id"]?.ToString() ?? "");
var content = SanitizeInput(data["text"]?.ToString() ?? "");
if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(content) || string.IsNullOrWhiteSpace(content))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.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),
};
if (paste.Visibility == "Private")
{
context.Response.StatusCode = 501;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Editing private pastes has not been implemented." }.ToString());
return;
}
var compressedContent = await Compression.CompressString(content);
await File.WriteAllBytesAsync($"pastes/{id}.txt", compressedContent);
await Logging.LogInfo($"{user.Username}({user.UUID}) edited their paste {paste.Id}");
}
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Paste edited" }.ToString());
});
app.MapPost("/api/pastes/delete", async (HttpContext context) =>
{
string token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"];
@@ -1715,8 +1788,7 @@ class Program
deleteCommand.Parameters.AddWithValue("@ID", id);
await deleteCommand.ExecuteNonQueryAsync();
File.Delete($"pastes/{id}.txt");
Console.WriteLine($"[{log.Now}] Paste {id} deleted by {user.Username}({user.UUID})");
await File.AppendAllTextAsync("logs.log", $"[{log.Now}] PASTE DELETED {id} {log.IP} {log.Method} {log.Path} {log.UserAgent} {log.Referer} {log.Body} {user.UUID}\n");
await Logging.LogInfo($"Paste {id} deleted by {user.Username}({user.UUID})");
context.Response.StatusCode = 200;
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Paste deleted" }.ToString());
}
@@ -1922,6 +1994,7 @@ class Program
Uploader = reader.GetString(6)
};
var filelength = new FileInfo($"pastes/{id}.txt").Length;
var user = await GetUserFromUUID(paste.Uploader);
JObject responseJson = new JObject();
responseJson["title"] = paste.Title;
@@ -1931,12 +2004,11 @@ class Program
responseJson["compressedSize"] = ConvertToBytes(filelength.ToString());
responseJson["date"] = paste.UnixDate;
responseJson["visibility"] = paste.Visibility;
responseJson["uploader"] = paste.Uploader;
Console.WriteLine(responseJson);
responseJson["uploader"] = user.Username;
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(responseJson.ToString());
await context.Response.WriteAsync(responseJson.ToString());
}
}).RequireRateLimiting("fixed");
app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) =>
@@ -2010,13 +2082,13 @@ class Program
return;
}
}
string decompressedEncryptedText = Compression.DecompressString(File.ReadAllBytes($"pastes/{pasteId}.txt"));
string decompressedEncryptedText = await Compression.DecompressByteArrayToString(File.ReadAllBytes($"pastes/{pasteId}.txt"));
string decryptedText = Encryption.DecryptString(decompressedEncryptedText, password);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new JObject { ["content"] = decryptedText }.ToString());
});
}).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/create", async (HttpContext context) =>
{
@@ -2153,8 +2225,7 @@ class Program
context.Response.Cookies.Append("token", token, cookie);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
Console.WriteLine($"[{DateTime.Now}] Account {username} has been created");
File.AppendAllText("logs.log", $"[{DateTime.Now}] Account {username} has been created by {log.IP}\n");
await Logging.LogInfo($"Account {username} has been created");
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Account created" }.ToString());
@@ -2274,8 +2345,7 @@ class Program
context.Response.Cookies.Append("token", token, cookie);
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
Console.WriteLine($"[{DateTime.Now}] Account {username} has logged in");
File.AppendAllText("logs.log", $"[{DateTime.Now}] Account {username} has logged in from {log.IP}\n");
await Logging.LogInfo($"Account {username} has logged in");
await context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Logged in" }.ToString());
return;
}
@@ -2326,8 +2396,8 @@ class Program
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(responseJson);
}));
await context.Response.WriteAsync(responseJson.ToString());
})).RequireRateLimiting("fixed"); ;
#endregion
@@ -2346,7 +2416,7 @@ class Program
Id = GenerateRandomString(12),
Uploader = UUID
};
var compressedText = Compression.CompressString(paste.Content);
var compressedText = await Compression.CompressString(paste.Content);
await File.WriteAllBytesAsync($"pastes/{paste.Id}.txt", compressedText);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
@@ -2366,7 +2436,7 @@ class Program
public static async Task<PrivatePaste> CreatePrivatePaste(string title, string content, string password, string UUID)
{
string encryptedText = Encryption.EncryptString(content, password);
var compressedEncryptedText = Compression.CompressString(encryptedText);
var compressedEncryptedText = await Compression.CompressString(encryptedText);
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
var paste = new PrivatePaste
{
@@ -2532,6 +2602,33 @@ class Program
};
}
}
public static async Task<User> GetUserFromUUID(string UUID)
{
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users WHERE UUID = @UUID";
command.Parameters.AddWithValue("@UUID", UUID);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
return new User();
}
return new User
{
UID = reader.GetString(0),
UUID = reader.GetString(1),
Username = reader.GetString(2),
PasswordHash = reader.GetString(3),
CreationDate = reader.GetString(4),
LastLoginDate = reader.GetString(5),
Type = reader.GetInt32(6),
State = reader.GetInt32(7)
};
}
}
public static async Task<User> UnbanUUIDAsync(string UUID)
{
User user = new User();
@@ -2601,8 +2698,6 @@ class Program
config["Salt"] = salt;
config["SmallerSalt"] = smallerSalt;
File.WriteAllText("config.json", config.ToString());
Logging.Api_CreateMessage = config["API_CreateMessage"]?.ToString() ?? "";
}
else
{
+109 -26
View File
@@ -11,8 +11,8 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
<a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<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">
@@ -25,15 +25,15 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
<a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<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">
<div class="paste-container">
<h1 id="paste-title"></h1>
<h3 class="uploader-text"><a id="uploader-username"></a> <a id="creationdate"></a> <a id="paste-size"></a>
<h3 class="uploader-text"><a id="uploader-username" class="user-a"></a> <a id="creationdate"></a> <a id="paste-size"></a>
</h3>
<div class="paste-wrapper">
<p id="text"></p>
@@ -45,15 +45,14 @@
<button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button>
<button id="delete-button" class="button" style="display: none;">delete</button>
<button id="edit-button" class="button" style="display: none;">edit</button>
</div>
</div>
</div>
<div class="notifcations-wrapper" id="notifications"></div>
<div class="input-wrapper" id="input-wrapper">
<div class="input-wrapper-container">
<h2>
Are you sure you want to delete this paste?
</h2>
<h2 id="input-message"></h2>
<div>
<button id="yes-button" class="button">Yes</button>
<button id="no-button" class="button">No</button>
@@ -63,6 +62,7 @@
</body>
<script>
info = "";
editing = false;
function localizeDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000);
return date.toLocaleString();
@@ -72,21 +72,27 @@
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username) {
if (info.uploader == data.username || data.type == "Admin") {
document.getElementById('delete-button').style.display = 'block';
document.getElementById('edit-button').style.display = 'block';
}
document.getElementById('login-signup-btn').style.display = 'none';
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 fetchInfo() {
fetch('/api/pastes/info?id={pasteid}')
.then(response => response.json())
.then(data => {
const json = JSON.parse(data);
.then(json => {
info = json;
document.getElementById('uploader-username').innerText = json.uploader;
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}`;
@@ -96,21 +102,34 @@
document.getElementById('paste-title').innerText = `Untitled ${json.uid}`;
document.title = `Untitled ${json.uid}`;
}
if (json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
if (json.uploader && json.uploader.startsWith("Anonymous") && json.uploader.length == 46) {
document.getElementById('uploader-username').innerText = 'Anonymous';
} else {
} else if (json.uploader) {
document.getElementById('uploader-username').href = `/u/${json.uploader}`;
}
});
})
.catch(error => console.error('Error fetching paste info:', error));
}
document.getElementById("edit-button").addEventListener("click", function () {
if (editing) {
createInput('Are you sure you want to save this edit?');
document.getElementById('yes-button').addEventListener("click", finalizeEdit);
} else {
editing = true;
var editButton = document.getElementById('edit-button');
editButton.innerText = 'save';
var text = document.getElementById('text');
var innertext = text.innerText;
text.innerHTML = `<textarea class="textarea" id="edit-textarea" style="width: 100%; height: ${text.clientHeight}px;">${innertext}</textarea>`;
}
});
document.addEventListener("DOMContentLoaded", function () {
fetchInfo();
authenticated();
const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim();
const textElement = document.getElementById('text');
fetchInfo();
authenticated();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
textElement.innerText = "Loading...";
fetch(`/raw/{pasteid}`)
@@ -165,12 +184,9 @@
document.body.removeChild(element);
});
document.getElementById("delete-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'flex';
});
createInput('Are you sure you want to delete this paste?');
document.getElementById("yes-button").addEventListener("click", function () {
var requestUrl = "/api/pastes/delete";
fetch(requestUrl, {
fetch(`/api/pastes/delete?id={pasteid}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -183,11 +199,20 @@
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
window.location.href = `/`;
createNotification(`Success: ${result.message}`);
setTimeout(() => {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
window.location.href = '/';
}, 2000);
} else {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
createNotification(`Error: ${result.error}`);
}
});
});
});
document.getElementById("no-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
@@ -219,7 +244,45 @@
notificationDiv.remove();
}, 4900);
}
function createInput(message) {
const inputWrapper = document.getElementById('input-wrapper');
const inputMessage = document.getElementById('input-message');
inputMessage.innerText = message;
inputWrapper.style.display = 'flex';
}
function finalizeEdit() {
var textarea = document.getElementById('edit-textarea');
var text = textarea.value;
fetch(`/api/pastes/edit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}',
text: text
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('edit-button').innerText = "edit";
createNotification(`Success: ${result.message}`);
document.getElementById('text').innerText = text;
document.getElementById('edit-textarea').remove();
editing = false;
} else {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('edit-button').innerText = "edit";
createNotification(`Error: ${result.error}`);
}
});
}
</script>
@@ -227,6 +290,19 @@
<style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap');
.textarea{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: 500;
max-width: 100%;
min-width: 100%;
background-color: #1d1d1d;
color: white;
border: none;
}
.textarea:focus{
outline: none;
}
.input-wrapper{
z-index: 100;
display: none;
@@ -343,12 +419,13 @@
font-weight: 600;
}
.user-a {
.user-a:any-link {
color: rgb(190, 190, 190);
text-decoration: none;
text-decoration: underline;
}
.nav-div {
top: 0;
margin-top: 10px;
@@ -366,6 +443,7 @@
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
z-index: 999999;
}
.nav-hamburger-menu {
@@ -500,5 +578,10 @@
margin-bottom: 10px;
justify-content: center;
align-items: center;
z-index: 102;
position: absolute;
}
.notifcations-wrapper{
z-index: 101;
}
</style>
+84 -22
View File
@@ -12,8 +12,8 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
<a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<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">
@@ -26,15 +26,15 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
<a href="login" id="login-signup-btn">login</a>
<a href="sign-up" id="login-signup-btn">sign up</a>
<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">
<div class="paste-container">
<h1 id="paste-title" title="{pastetitleattribute}">{pastetitle}</h1>
<h3 class="uploader-text"><a id="uploader-username"></a> <a id="creationdate"></a> <a id="paste-size"></a>
<h3 class="uploader-text"><a id="uploader-username" class="user-a"></a> <a id="creationdate"></a> <a id="paste-size"></a>
</h3>
<div class="paste-wrapper">
<p id="text"></p>
@@ -46,6 +46,7 @@
<button id="copy-button" class="button">copy</button>
<button id="download-button" class="button">download</button>
<button id="delete-button" class="button" style="display: none;">delete</button>
<button id="edit-button" class="button" style="display: none;">edit</button>
</div>
</div>
<div class="passwordDiv">
@@ -62,9 +63,7 @@
</div>
<div class="input-wrapper" id="input-wrapper">
<div class="input-wrapper-container">
<h2>
Are you sure you want to delete this paste?
</h2>
<h2 id="input-message"></h2>
<div>
<button id="yes-button" class="button">Yes</button>
<button id="no-button" class="button">No</button>
@@ -73,19 +72,25 @@
</div>
</body>
<script>
info = "";
editing = false;
function authenticated() {
fetch('/api/accounts/authenticated')
.then(response => response.json())
.then(data => {
if (data.message == "Authenticated") {
if (info.uploader == data.username) {
if (info.uploader == data.username || data.type == "Admin") {
document.getElementById('delete-button').style.display = 'block';
//document.getElementById('edit-button').style.display = 'block';
}
document.getElementById('login-signup-btn').style.display = 'none';
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';
});
}
});
}
@@ -112,7 +117,21 @@
}
});
}
document.getElementById("edit-button").addEventListener("click", function () {
if (editing) {
createInput('Are you sure you want to save this edit?');
document.getElementById('yes-button').removeEventListener("click", deletePaste);
document.getElementById('yes-button').addEventListener("click", finalizeEdit);
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
} else {
editing = true;
var editButton = document.getElementById('edit-button');
editButton.innerText = 'save';
var text = document.getElementById('text');
var innertext = text.innerText;
text.innerHTML = `<textarea class="textarea" id="edit-textarea" style="width: 100%; height: ${text.clientHeight}px;">${innertext}</textarea>`;
}
});
document.getElementById("submitPassword").addEventListener("click", function () {
var password = document.getElementById("password").value;
fetch(`/api/pastes/password/{pasteid}`, {
@@ -145,11 +164,11 @@
}
document.addEventListener("DOMContentLoaded", function () {
const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim();
fetchInfo();
authenticated();
const creationdateElement = document.getElementById('creationdate');
const creationdateText = creationdateElement.innerText.trim();
creationdateElement.innerText = localizeDateTime(parseInt(creationdateText));
var mobile = window.mobileCheck();
if (mobile) {
@@ -183,12 +202,13 @@
document.body.removeChild(element);
});
document.getElementById("delete-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'flex';
createInput('Are you sure you want to delete this paste?');
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
document.getElementById('yes-button').addEventListener("click", deletePaste);
document.getElementById('yes-button').removeEventListener("click", deletePaste);
});
document.getElementById("yes-button").addEventListener("click", function () {
var requestUrl = "/api/pastes/delete";
fetch(requestUrl, {
function deletePaste() {
fetch(`/api/pastes/delete?id={pasteid}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -201,15 +221,47 @@
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
window.location.href = `/`;
createNotification(`Success: ${result.message}`);
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
createNotification(`Error: ${result.error}`);
}
});
}
function finalizeEdit() {
var textarea = document.getElementById('edit-textarea');
var text = textarea.value;
fetch(`/api/pastes/edit`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: '{pasteid}',
text: text
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
createNotification(`Success: ${result.message}`);
document.getElementById('text').innerText = text;
document.getElementById('edit-textarea').remove();
editing = false;
} else {
createNotification(`Error: ${result.error}`);
}
});
}
document.getElementById("no-button").addEventListener("click", function () {
const inputWrapper = document.getElementById('input-wrapper');
inputWrapper.style.display = 'none';
document.getElementById('yes-button').removeEventListener("click", finalizeEdit);
document.getElementById('yes-button').removeEventListener("click", deletePaste);
});
function notification(message) {
const notification = document.getElementById('notification');
@@ -228,7 +280,12 @@
}, 4900);
}
function createInput(message) {
const inputWrapper = document.getElementById('input-wrapper');
const inputMessage = document.getElementById('input-message');
inputMessage.innerText = message;
inputWrapper.style.display = 'flex';
}
</script>
@@ -441,6 +498,7 @@
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
z-index: 999999;
}
.nav-hamburger-menu {
@@ -576,6 +634,10 @@
margin-bottom: 10px;
justify-content: center;
align-items: center;
z-index: 102;
position: absolute;
}
.notifcations-wrapper{
z-index: 101;
}
</style>