+ Maximum pad length

+ Configurable maximum pad length
+ Refresh pad
+ Archive pad
+ Archives in local client storage
+ Download pad
This commit is contained in:
Daniel Legt 2022-05-21 16:17:25 +03:00
parent b079c0f637
commit e781daec89
8 changed files with 326 additions and 73 deletions

View File

@ -16,6 +16,28 @@ func GetDomainBase() string {
return domainBase
}
func GetMaximumPadSize() int {
// Lookup if the maximum pad size variable exists.
maxPadSize, exists := os.LookupEnv("MAXIMUM_PAD_SIZE")
// Check if this environment variable has bee nset
if !exists {
// Set the variable ourselves to the default string value
maxPadSize = "524288"
}
// Try and convert the string into an integer
rez, err := strconv.Atoi(maxPadSize)
// Check if the conversion has failed
if err != nil {
// Simply return the default
return 524288
}
// Return the resulting value
return rez
}
func GetCacheMapLimit() int {
cacheMapLimit, domainExists := os.LookupEnv("CACHE_MAP_LIMIT")

View File

@ -1,10 +1,13 @@
package objects
import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/JustKato/FreePad/lib/helper"
)
type Post struct {
@ -73,6 +76,11 @@ func GetPost(fileName string) Post {
func WritePost(p Post) error {
maximumPadSize := helper.GetMaximumPadSize()
if len(p.Content) > maximumPadSize {
return errors.New("The pad is too big, please limit to the maximum of " + fmt.Sprint(maximumPadSize) + " characters")
}
// Get the base storage directory and make sure it exists
storageDir := getStorageDirectory()

View File

@ -23,6 +23,9 @@ func HomeRoutes(router *gin.Engine) {
// Get the post we are looking for.
postName := c.Param("post")
// Get the maximum pad size, so that we may notify the client-side to match server-side
maximumPadSize := helper.GetMaximumPadSize()
// Sanitize the postName
newPostName, err := url.QueryUnescape(postName)
if err == nil {
@ -35,6 +38,7 @@ func HomeRoutes(router *gin.Engine) {
c.HTML(200, "page.html", gin.H{
"title": postName,
"post_content": post.Content,
"maximumPadSize": maximumPadSize,
"last_modified": post.LastModified,
"domain_base": helper.GetDomainBase(),
})

3
static/js/fileSaver.js Normal file
View File

@ -0,0 +1,3 @@
(function(a,b){if("function"==typeof define&&define.amd)define([],b);else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(this,function(){"use strict";function b(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Deprecated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(a,b,c){var d=new XMLHttpRequest;d.open("GET",a),d.responseType="blob",d.onload=function(){g(d.response,b,c)},d.onerror=function(){console.error("could not download file")},d.send()}function d(a){var b=new XMLHttpRequest;b.open("HEAD",a,!1);try{b.send()}catch(a){}return 200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var f="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof global&&global.global===global?global:void 0,a=/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),g=f.saveAs||("object"!=typeof window||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!a?function(b,g,h){var i=f.URL||f.webkitURL,j=document.createElement("a");g=g||b.name||"download",j.download=g,j.rel="noopener","string"==typeof b?(j.href=b,j.origin===location.origin?e(j):d(j.href)?c(b,g,h):e(j,j.target="_blank")):(j.href=i.createObjectURL(b),setTimeout(function(){i.revokeObjectURL(j.href)},4E4),setTimeout(function(){e(j)},0))}:"msSaveOrOpenBlob"in navigator?function(f,g,h){if(g=g||f.name||"download","string"!=typeof f)navigator.msSaveOrOpenBlob(b(f,h),g);else if(d(f))c(f,g,h);else{var i=document.createElement("a");i.href=f,i.target="_blank",setTimeout(function(){e(i)})}}:function(b,d,e,g){if(g=g||open("","_blank"),g&&(g.document.title=g.document.body.innerText="downloading..."),"string"==typeof b)return c(b,d,e);var h="application/octet-stream"===b.type,i=/constructor/i.test(f.HTMLElement)||f.safari,j=/CriOS\/[\d]+/.test(navigator.userAgent);if((j||h&&i||a)&&"undefined"!=typeof FileReader){var k=new FileReader;k.onloadend=function(){var a=k.result;a=j?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),g?g.location.href=a:location=a,g=null},k.readAsDataURL(b)}else{var l=f.URL||f.webkitURL,m=l.createObjectURL(b);g?g.location=m:location.href=m,g=null,setTimeout(function(){l.revokeObjectURL(m)},4E4)}});f.saveAs=g.saveAs=g,"undefined"!=typeof module&&(module.exports=g)});
//# sourceMappingURL=FileSaver.min.js.map

186
static/js/pad-scripts.js Normal file
View File

@ -0,0 +1,186 @@
function sendMyData(el) {
const formData = new FormData();
// Check if the writing watch was sending something already
if ( !!window.writingWatch ) {
// Clear old timeout
clearTimeout(window.writingWatch);
}
if ( el.value.length > maximumPadSize ) {
let err = new Error(`Your Pad is too big! Please keep it limited to ${maximumPadSize} characters!`);
alert(err);
throw err;
}
el.setAttribute(`readonly`, `1`);
formData.set("content", el.value);
updateStatus(`Attempting to save...`, `text-warning`);
fetch(window.location.href.toString(), {
body: formData,
method: "post",
})
.then( resp => {
resp.json()
.then( e => {
document.getElementById(`last_modified_`).value = e.pad.last_modified;
updateStatus(`Succesfully Saved`, `text-success`);
})
.catch( err => {
updateStatus(`Failed to Save`, `text-danger`);
console.error(err);
})
})
.catch( err => {
updateStatus(`Failed to Save`, `text-danger`);
console.error(err);
})
.finally( () => {
el.removeAttribute(`readonly`);
})
}
function toggleWritingWatch(el) {
// Check if the writing watch was sending something already
if ( !!window.writingWatch ) {
// Clear old timeout
clearTimeout(window.writingWatch);
}
// Set a timeout for the action
window.writingWatch = setTimeout( () => {
// Send out the data
sendMyData(el)
}, 750)
}
function updateStatus(txt, cls) {
const loading_status = document.getElementById(`loading_status`)
loading_status.value = txt;
loading_status.classList.remove("text-danger", "text-warning", "text-success", "text-white", "text-primary");
loading_status.classList.add(cls);
}
function getLocalArchives() {
let a = localStorage.getItem("archives");
// Check if we had anything in storage for the archives
if ( a == null ) {
// There were nothing in storage
return [];
}
try {
// Try and parse the json
a = JSON.parse(a);
} catch ( err ) {
// Return null of the fail
return [];
}
return a;
}
function storeArchives(archives) {
// Check if the provided list is an array
if ( !Array.isArray(archives) ) return;
// Set the current archives
localStorage.setItem('archives', JSON.stringify(archives));
}
function renderArchivesSelection() {
// Get the archives selection
const archivesSelection = document.getElementById(`archives-selection`);
const rowTemplate = document.getElementById(`archive-selection-example`);
// Clear any old optiosn
archivesSelection.querySelectorAll(`.dropdown-item:not(#do-archive-button):not(#archive-selection-example)`).forEach( el => {
// Remove the element
el.remove();
})
// Get the current list of available archives
for ( let a of getLocalArchives() ) {
// Clone the template row
const row = rowTemplate.cloneNode(true);
// Remove the id from the row
row.removeAttribute(`id`);
// Append the row to the selection menu
archivesSelection.appendChild(row);
const ts = new Date(a.ts);
// Update the display date
row.querySelector(`.archive-date`).textContent = ts.toLocaleString();
// Add an event listener
row.addEventListener(`click`, e => {
let resp = confirm("Load contents of pad from memory? This will overwrite the current pad for everyone.");
if ( !!resp ) {
document.getElementById(`pad-content`).value = a.content;
}
})
}
}
function saveLocalArchive() {
let resp = confirm("Save a local copy of the current Pad?");
if ( !resp ) {
// Do not
return;
}
// Get all of the previous archives, append this one to them
let myArchives = getLocalArchives();
myArchives.push({
ts: new Date().getTime(),
content: document.getElementById(`pad-content`).value,
});
// Store the archives
storeArchives(myArchives);
// Re-Render the archives selection
renderArchivesSelection();
// Save
alert(`Saved`);
}
document.addEventListener(`DOMContentLoaded`, e => {
{ // Textarea Focusing
const textarea = document.getElementById(`pad-content`);
// Focus
textarea.focus();
// Scroll
textarea.scrollTop = textarea.scrollHeight;
// Move cursor
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
}
{ // Archives
renderArchivesSelection()
}
})

21
static/js/pad.js Normal file
View File

@ -0,0 +1,21 @@
class Pad {
title = '';
content = '';
timestmap = '';
constructor(t, ts) {
this.title = t;
this.content = document.getElementById(`pad-content`).value;
this.timestmap = ts;
}
downloadPadContents() {
// Create a new blob of the contents of the pad
var blob = new Blob([ document.getElementById(`pad-content`).value ], { type: "text/plain;charset=utf-8" });
// Save the blob as
saveAs(blob, `${this.title}.txt`);
}
}

View File

@ -28,10 +28,12 @@
</div>
<script>
function goToPad() {
// Go to the next apd
window.location.href = "/" + document.getElementById(`pad-name`).value;
}
</script>
<div class="why mb-4">

View File

@ -1,11 +1,25 @@
{{ template "inc/header.html" .}}
<style>
#pad-content {
height: 16rem;
}
#archive-selection-example {
display: none;
}
.dropdown-item {
cursor: pointer;
}
</style>
<script>
var maximumPadSize = Number({{.maximumPadSize}});
</script>
<body>
<main id="main-card" class="container rounded mt-5 shadow-sm">
@ -17,7 +31,9 @@
</div>
<textarea name="pad-content" id="pad-content" onchange="sendMyData(this)" onkeydown="updateStatus(`Not Saved`, `text-warning`); toggleWritingWatch(this)" class="form-control">{{.post_content}}</textarea>
<h2 class="mb-4">{{.title}}</h2>
<textarea maxlength="{{.maximumPadSize}}" name="pad-content" id="pad-content" onchange="sendMyData(this)" onkeydown="updateStatus(`Not Saved`, `text-warning`); toggleWritingWatch(this)" class="form-control">{{.post_content}}</textarea>
<div id="pad-status" class="my-4 row">
<div class="col-md-12 col-lg-4 col-xl-4" title="Status">
@ -56,7 +72,57 @@
</div>
<footer class="text-muted py-5 text-center">
<div id="pad-options" class="row">
<div class="col-md-12 col-lg-4 col-xl-4">
<button type="button" class="btn btn-secondary btn-md w-100" title="Refresh the contents of the pad" onclick="window.location.reload()">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-clockwise" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z"></path>
<path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z"></path>
</svg>
Refresh Pad
</button>
</div>
<div class="col-md-12 col-lg-4 col-xl-4 mt-4 mt-lg-0 mt-xl-0">
<button type="button" class="btn btn-secondary btn-md w-100" title="Download the contents into a text file" onclick="window.pad.downloadPadContents();">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cloud-download" viewBox="0 0 16 16">
<path d="M4.406 1.342A5.53 5.53 0 0 1 8 0c2.69 0 4.923 2 5.166 4.579C14.758 4.804 16 6.137 16 7.773 16 9.569 14.502 11 12.687 11H10a.5.5 0 0 1 0-1h2.688C13.979 10 15 8.988 15 7.773c0-1.216-1.02-2.228-2.313-2.228h-.5v-.5C12.188 2.825 10.328 1 8 1a4.53 4.53 0 0 0-2.941 1.1c-.757.652-1.153 1.438-1.153 2.055v.448l-.445.049C2.064 4.805 1 5.952 1 7.318 1 8.785 2.23 10 3.781 10H6a.5.5 0 0 1 0 1H3.781C1.708 11 0 9.366 0 7.318c0-1.763 1.266-3.223 2.942-3.593.143-.863.698-1.723 1.464-2.383z"></path>
<path d="M7.646 15.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 14.293V5.5a.5.5 0 0 0-1 0v8.793l-2.146-2.147a.5.5 0 0 0-.708.708l3 3z"></path>
</svg>
Download Pad
</button>
</div>
<div class="col-md-12 col-lg-4 col-xl-4 mt-4 mt-lg-0 mt-xl-0" title="Archive the current state of the pad">
<div class="btn-group w-100" role="group">
<button type="button" class="btn btn-secondary btn-md w-100 dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-archive" viewBox="0 0 16 16">
<path d="M0 2a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1v7.5a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 1 12.5V5a1 1 0 0 1-1-1V2zm2 3v7.5A1.5 1.5 0 0 0 3.5 14h9a1.5 1.5 0 0 0 1.5-1.5V5H2zm13-3H1v2h14V2zM5 7.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>
</svg>
Archive Pad
</button>
<ul class="dropdown-menu w-100" id="archives-selection">
<li class="dropdown-item" onclick="saveLocalArchive()" id="do-archive-button">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-archive" viewBox="0 0 16 16">
<path d="M0 2a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1v7.5a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 1 12.5V5a1 1 0 0 1-1-1V2zm2 3v7.5A1.5 1.5 0 0 0 3.5 14h9a1.5 1.5 0 0 0 1.5-1.5V5H2zm13-3H1v2h14V2zM5 7.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>
</svg>
<span class="archive-date">
Archive Current
</span>
</li>
<li class="dropdown-item archive-selection" id="archive-selection-example">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-text" viewBox="0 0 16 16">
<path d="M5.5 7a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1h-5zM5 9.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.5-.5z"/>
<path d="M9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.5L9.5 0zm0 1v2A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5z"/>
</svg>
<span class="archive-date">
DATE
</span>
</li>
</ul>
</div>
</div>
</div>
<footer class="text-muted py-5 text-center border-top mt-4">
<p class="mb-1">
FreePad by <a href="https://justkato.me/">©Kato Twofold</a>
</p>
@ -70,75 +136,16 @@
{{ template "inc/theme-toggle.html" .}}
</body>
<script src="/static/js/fileSaver.js"></script>
<script src="/static/js/pad.js"></script>
<script src="/static/js/pad-scripts.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script>
function sendMyData(el) {
const formData = new FormData();
// Check if the writing watch was sending something already
if ( !!window.writingWatch ) {
// Clear old timeout
clearTimeout(window.writingWatch);
}
el.setAttribute(`readonly`, `1`);
formData.set("content", el.value);
updateStatus(`Attempting to save...`, `text-warning`);
fetch(window.location.href.toString(), {
body: formData,
method: "post",
})
.then( resp => {
resp.json()
.then( e => {
document.getElementById(`last_modified_`).value = e.pad.last_modified;
updateStatus(`Succesfully Saved`, `text-success`);
})
.catch( err => {
updateStatus(`Failed to Save`, `text-error`);
console.error(err);
})
})
.catch( err => {
updateStatus(`Failed to Save`, `text-error`);
console.error(err);
})
.finally( () => {
el.removeAttribute(`readonly`);
})
}
function toggleWritingWatch(el) {
// Check if the writing watch was sending something already
if ( !!window.writingWatch ) {
// Clear old timeout
clearTimeout(window.writingWatch);
}
// Set a timeout for the action
window.writingWatch = setTimeout( () => {
// Send out the data
sendMyData(el)
}, 750)
}
function updateStatus(txt, cls) {
const loading_status = document.getElementById(`loading_status`)
loading_status.value = txt;
loading_status.classList.remove("text-danger", "text-warning", "text-success", "text-white", "text-primary");
loading_status.classList.add(cls);
}
document.addEventListener(`DOMContentLoaded`, e => {
document.getElementById(`pad-content`).focus();
})
window.pad = new Pad({{.title}}, {{.last_modified}});
</script>
{{ template "inc/footer.html" .}}