Compare commits
10 Commits
f7579670cc
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 4909845c61 | |||
| e8a375796d | |||
| 113b6a6d66 | |||
| 68bc0ff636 | |||
| e0c1c7e4dd | |||
| 4b8c75f1f1 | |||
| 46fbc4fd35 | |||
| 8d94b58bd8 | |||
| bee5e4ce20 | |||
| 4d7c0a0f69 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
static
|
||||
result
|
||||
.direnv
|
||||
|
||||
|
||||
BIN
android-chrome-192x192.png
Normal file
BIN
android-chrome-192x192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
BIN
android-chrome-512x512.png
Normal file
BIN
android-chrome-512x512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 230 KiB |
BIN
apple-touch-icon.png
Normal file
BIN
apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
BIN
favicon-16x16.png
Normal file
BIN
favicon-16x16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 838 B |
BIN
favicon-32x32.png
Normal file
BIN
favicon-32x32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
favicon.ico
Normal file
BIN
favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
27
flake.nix
27
flake.nix
@@ -6,8 +6,10 @@
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { nixpkgs, flake-utils, ... }@inputs:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
outputs =
|
||||
{ nixpkgs, flake-utils, ... }@inputs:
|
||||
flake-utils.lib.eachDefaultSystem (
|
||||
system:
|
||||
let
|
||||
pkgs = import nixpkgs { inherit system; };
|
||||
in
|
||||
@@ -15,7 +17,7 @@
|
||||
packages = rec {
|
||||
slenpaste = pkgs.buildGoModule {
|
||||
pname = "slenpaste";
|
||||
version = "0.1.3";
|
||||
version = "0.2.2";
|
||||
src = ./.;
|
||||
goPackagePath = "github.com/slendidev/slenpaste";
|
||||
vendorHash = "sha256-MUvodL6K71SCfxu51T/Ka2/w32Kz+IXem1bYqXQLSaU=";
|
||||
@@ -24,10 +26,20 @@
|
||||
};
|
||||
|
||||
devShells.default = pkgs.mkShell {
|
||||
buildInputs = [ pkgs.go pkgs.gopls ];
|
||||
buildInputs = [
|
||||
pkgs.go
|
||||
pkgs.gopls
|
||||
];
|
||||
};
|
||||
|
||||
nixosModules.slenpaste = { lib, pkgs, config, ... }: {
|
||||
nixosModules.slenpaste =
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
config,
|
||||
...
|
||||
}:
|
||||
{
|
||||
# module function
|
||||
options.services.slenpaste.enable = lib.mkEnableOption "Enable slenpaste service";
|
||||
options.services.slenpaste.domain = lib.mkOption {
|
||||
@@ -72,8 +84,9 @@
|
||||
-domain "${config.services.slenpaste.domain}" \
|
||||
-listen "${config.services.slenpaste.listen}" \
|
||||
-expire "${config.services.slenpaste.expireDur}" \
|
||||
${lib.optionalString config.services.slenpaste.expireOnView "-expire-on-view=false"}
|
||||
${lib.optionalString config.services.slenpaste.https "-https"}
|
||||
${lib.optionalString config.services.slenpaste.expireOnView "-expire-on-view=false"} \
|
||||
${lib.optionalString config.services.slenpaste.https "-https"} \
|
||||
|
||||
'';
|
||||
Restart = "on-failure";
|
||||
};
|
||||
|
||||
283
main.go
283
main.go
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -27,9 +29,17 @@ var (
|
||||
useHTTPS bool
|
||||
)
|
||||
|
||||
//go:embed android-chrome-192x192.png android-chrome-512x512.png apple-touch-icon.png favicon-16x16.png favicon-32x32.png favicon.ico site.webmanifest
|
||||
var assetsFS embed.FS
|
||||
|
||||
type meta struct {
|
||||
Expiry time.Time `json:"expiry"`
|
||||
ExpireOnView bool `json:"expire_on_view"`
|
||||
FileName string `json:"file_name,omitempty"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
_ = mime.AddExtensionType(".webmanifest", "application/manifest+json")
|
||||
}
|
||||
|
||||
func getLimiter(ip string) *rate.Limiter {
|
||||
@@ -68,34 +78,205 @@ func randomID(n int) string {
|
||||
}
|
||||
|
||||
func indexHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Type", "text/html")
|
||||
fmt.Fprintf(w, `<html><body><pre>Welcome to slenpaste!
|
||||
w.Header().Add("Content-Type", "text/html; charset=utf-8")
|
||||
scheme := "http"
|
||||
if useHTTPS {
|
||||
scheme = "https"
|
||||
}
|
||||
d := fmt.Sprintf("%s://%s", scheme, domain)
|
||||
|
||||
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>slenpaste</title>
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<link rel="manifest" href="/site.webmanifest">
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
<style>
|
||||
body { font-family: system-ui, sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
|
||||
pre { background: #f6f6f6; padding: .75rem 1rem; border-radius: .5rem; overflow: auto; }
|
||||
fieldset { border: 1px solid #ddd; border-radius: .5rem; padding: .5rem .75rem; }
|
||||
#dropzone {
|
||||
border: 2px dashed #bbb; border-radius: .75rem; padding: 1.25rem; text-align: center;
|
||||
user-select: none;
|
||||
}
|
||||
#dropzone.dragover { border-color: #333; background: #fafafa; }
|
||||
#result { margin-top: .75rem; }
|
||||
#result a { font-weight: 600; }
|
||||
.controls { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; }
|
||||
.inline { display: inline-flex; gap: .5rem; align-items: center; }
|
||||
textarea { width: 100%%; height: 180px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.small { color: #666; font-size: .9rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>slenpaste</h1>
|
||||
<pre>Welcome!
|
||||
|
||||
Upload a file:
|
||||
curl -F 'file=@yourfile.txt' -F 'expiry=1h' http://%s/
|
||||
curl -F 'file=@yourfile.txt' -F 'expiry=1h' %s/
|
||||
|
||||
Upload from stdin (no file param, expire after 5m):
|
||||
curl --data-binary @- http://%s/?expiry=5m < yourfile.txt
|
||||
curl --data-binary @- %s/?expiry=5m < yourfile.txt
|
||||
|
||||
Upload from stdin and expire on first view:
|
||||
cat yourfile.txt | curl --data-binary @- "http://%s/?expiry=view"
|
||||
|
||||
cat yourfile.txt | curl --data-binary @- "%s/?expiry=view"
|
||||
</pre>
|
||||
<form enctype="multipart/form-data" method="post">
|
||||
<input type="file" name="file">
|
||||
|
||||
<fieldset style="margin-top: 1rem">
|
||||
<legend>Expiry:</legend>
|
||||
<a href="https://git.slendi.dev/Slendi/slenpaste.koplugin">Download the new KOReader plugin!</a>
|
||||
<form id="form" enctype="multipart/form-data" method="post" style="margin-top: 13px;">
|
||||
<input type="file" name="file" id="fileInput">
|
||||
<div class="controls" style="margin-top: .75rem">
|
||||
<fieldset>
|
||||
<legend>Expiry</legend>
|
||||
<label><input type="radio" name="expiry" value="0" checked> Never</label>
|
||||
<label><input type="radio" name="expiry" value="5m"> 5 minutes</label>
|
||||
<label><input type="radio" name="expiry" value="1h"> 1 hour</label>
|
||||
<label><input type="radio" name="expiry" value="24h"> 1 day</label>
|
||||
<label><input type="radio" name="expiry" value="view"> Expire on first view</label>
|
||||
</fieldset><br/>
|
||||
|
||||
<input type="submit" value="Upload">
|
||||
</form>
|
||||
</body></html>`, domain, domain, domain)
|
||||
</fieldset>
|
||||
<div class="inline">
|
||||
<label for="fname">Filename (optional):</label>
|
||||
<input type="text" id="fname" placeholder="example.txt">
|
||||
</div>
|
||||
<input type="submit" value="Upload file">
|
||||
</div>
|
||||
</form>
|
||||
<h2 style="margin-top:1.5rem">No file? Type your text in here!</h2>
|
||||
<p class="small">Type or paste text and upload as a .txt.</p>
|
||||
<textarea id="textArea" placeholder="Type or paste here..."></textarea>
|
||||
<div class="controls" style="margin-top:.5rem">
|
||||
<button id="uploadTextBtn" type="button">Upload text</button>
|
||||
<label class="inline small"><input type="checkbox" id="textAsMd"> Save as .md</label>
|
||||
</div>
|
||||
<h2 style="margin-top:1.5rem">Paste or drop images</h2>
|
||||
<div id="dropzone" tabindex="0">
|
||||
Paste an image (Ctrl/Cmd+V) or drag & drop files here
|
||||
<div class="small">Images are uploaded as files. Other files dropped here work too.</div>
|
||||
</div>
|
||||
<div id="result"></div>
|
||||
<script>
|
||||
(function() {
|
||||
"use strict";
|
||||
const form = document.getElementById("form");
|
||||
const fileInput = document.getElementById("fileInput");
|
||||
const fname = document.getElementById("fname");
|
||||
const textArea = document.getElementById("textArea");
|
||||
const uploadTextBtn = document.getElementById("uploadTextBtn");
|
||||
const textAsMd = document.getElementById("textAsMd");
|
||||
const dropzone = document.getElementById("dropzone");
|
||||
const result = document.getElementById("result");
|
||||
function getExpiry() {
|
||||
const checked = form.querySelector('input[name="expiry"]:checked');
|
||||
return checked ? checked.value : "0";
|
||||
}
|
||||
function setBusy(b) {
|
||||
if (b) {
|
||||
result.textContent = "Uploading...";
|
||||
}
|
||||
}
|
||||
function showLink(url) {
|
||||
result.innerHTML = 'URL: <a href="' + url + '" target="_blank" rel="noopener">' + url + '</a>';
|
||||
try {
|
||||
navigator.clipboard.writeText(url);
|
||||
result.innerHTML += ' <span class="small">(copied)</span>';
|
||||
} catch(e) {}
|
||||
}
|
||||
async function uploadFormData(fd, expiry) {
|
||||
setBusy(true);
|
||||
const res = await fetch("/?expiry=" + encodeURIComponent(expiry), {
|
||||
method: "POST",
|
||||
body: fd
|
||||
});
|
||||
if (!res.ok) {
|
||||
const t = await res.text();
|
||||
result.textContent = "Error: " + t;
|
||||
return;
|
||||
}
|
||||
const url = (await res.text()).trim();
|
||||
showLink(url);
|
||||
}
|
||||
async function uploadBlobAsFile(blob, filename, expiry) {
|
||||
const fd = new FormData();
|
||||
const file = new File([blob], filename, { type: blob.type || "application/octet-stream" });
|
||||
fd.append("file", file);
|
||||
return uploadFormData(fd, expiry);
|
||||
}
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
if (!fileInput.files || fileInput.files.length === 0) {
|
||||
result.textContent = "Choose a file first.";
|
||||
return;
|
||||
}
|
||||
const expiry = getExpiry();
|
||||
let file = fileInput.files[0];
|
||||
if (fname.value.trim()) {
|
||||
file = new File([file], fname.value.trim(), { type: file.type });
|
||||
}
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
await uploadFormData(fd, expiry);
|
||||
fileInput.value = "";
|
||||
fname.value = "";
|
||||
});
|
||||
uploadTextBtn.addEventListener("click", async () => {
|
||||
const text = textArea.value;
|
||||
if (!text) {
|
||||
result.textContent = "Nothing to upload.";
|
||||
return;
|
||||
}
|
||||
const expiry = getExpiry();
|
||||
const name = (fname.value.trim() || (textAsMd.checked ? "text.md" : "text.txt"));
|
||||
await uploadBlobAsFile(new Blob([text], { type: "text/plain" }), name, expiry);
|
||||
fname.value = "";
|
||||
});
|
||||
;["dragenter","dragover"].forEach(ev => {
|
||||
dropzone.addEventListener(ev, (e) => {
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
dropzone.classList.add("dragover");
|
||||
});
|
||||
});
|
||||
;["dragleave","drop"].forEach(ev => {
|
||||
dropzone.addEventListener(ev, (e) => {
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
dropzone.classList.remove("dragover");
|
||||
});
|
||||
});
|
||||
dropzone.addEventListener("drop", async (e) => {
|
||||
const expiry = getExpiry();
|
||||
const files = Array.from(e.dataTransfer.files || []);
|
||||
if (files.length === 0) return;
|
||||
const fd = new FormData();
|
||||
for (const f of files) {
|
||||
fd.set("file", f);
|
||||
await uploadFormData(fd, expiry);
|
||||
}
|
||||
});
|
||||
window.addEventListener("paste", async (e) => {
|
||||
const items = e.clipboardData && e.clipboardData.items ? Array.from(e.clipboardData.items) : [];
|
||||
if (!items.length) return;
|
||||
const expiry = getExpiry();
|
||||
let handled = false;
|
||||
for (const it of items) {
|
||||
if (it.kind === "file") {
|
||||
const blob = it.getAsFile();
|
||||
if (!blob) continue;
|
||||
const ext = (blob.type && blob.type.startsWith("image/")) ? blob.type.split("/")[1] : "bin";
|
||||
const name = fname.value.trim() || ("pasted." + ext);
|
||||
await uploadBlobAsFile(blob, name, expiry);
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
if (handled) e.preventDefault();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`, d, d, d)
|
||||
}
|
||||
|
||||
func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -106,6 +287,7 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var reader io.Reader
|
||||
var ext string
|
||||
var fileName string
|
||||
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
@@ -114,6 +296,7 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
defer file.Close()
|
||||
reader = file
|
||||
ext = filepath.Ext(header.Filename)
|
||||
fileName = filepath.Base(header.Filename)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,7 +332,7 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
os.Remove(path)
|
||||
_ = os.Remove(path)
|
||||
http.Error(w, "Empty upload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -166,7 +349,10 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
m.Expiry = time.Now().Add(d)
|
||||
}
|
||||
}
|
||||
if !m.Expiry.IsZero() || m.ExpireOnView {
|
||||
if fileName != "" {
|
||||
m.FileName = fileName
|
||||
}
|
||||
if !m.Expiry.IsZero() || m.ExpireOnView || m.FileName != "" {
|
||||
metaBytes, _ := json.Marshal(m)
|
||||
_ = os.WriteFile(path+".json", metaBytes, 0644)
|
||||
}
|
||||
@@ -178,6 +364,20 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "%s://%s/%s\n", scheme, domain, filename)
|
||||
}
|
||||
|
||||
func contentDispositionInlineFilename(name string) string {
|
||||
q := strconv.QuoteToASCII(name)
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(name); i++ {
|
||||
c := name[i]
|
||||
if (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '-' || c == '_' {
|
||||
b.WriteByte(c)
|
||||
} else {
|
||||
fmt.Fprintf(&b, "%%%02X", c)
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(`inline; filename=%s; filename*=UTF-8''%s`, q, b.String())
|
||||
}
|
||||
|
||||
func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if id == "" {
|
||||
@@ -191,8 +391,8 @@ func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var m meta
|
||||
if err := json.Unmarshal(data, &m); err == nil {
|
||||
if !m.Expiry.IsZero() && time.Now().After(m.Expiry) {
|
||||
os.Remove(path)
|
||||
os.Remove(metaPath)
|
||||
_ = os.Remove(path)
|
||||
_ = os.Remove(metaPath)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
@@ -200,6 +400,9 @@ func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
defer os.Remove(path)
|
||||
defer os.Remove(metaPath)
|
||||
}
|
||||
if m.FileName != "" {
|
||||
w.Header().Set("Content-Disposition", contentDispositionInlineFilename(m.FileName))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +413,6 @@ func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// set correct content type based on extension
|
||||
ext := filepath.Ext(id)
|
||||
mimeType := mime.TypeByExtension(ext)
|
||||
if mimeType == "" {
|
||||
@@ -218,7 +420,26 @@ func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
|
||||
io.Copy(w, f)
|
||||
_, _ = io.Copy(w, f)
|
||||
}
|
||||
|
||||
func serveEmbedded(embeddedName, contentType string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
b, err := assetsFS.ReadFile(embeddedName)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if contentType == "" {
|
||||
if ct := mime.TypeByExtension(filepath.Ext(embeddedName)); ct != "" {
|
||||
contentType = ct
|
||||
}
|
||||
}
|
||||
if contentType != "" {
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
}
|
||||
http.ServeContent(w, r, embeddedName, time.Time{}, strings.NewReader(string(b)))
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -230,14 +451,24 @@ func main() {
|
||||
flag.BoolVar(&useHTTPS, "https", false, "use https:// in generated URLs")
|
||||
flag.Parse()
|
||||
|
||||
http.HandleFunc("/", rateLimitMiddleware(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Uploads + index
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
uploadHandler(w, r)
|
||||
rateLimitMiddleware(uploadHandler)(w, r)
|
||||
} else {
|
||||
viewHandler(w, r)
|
||||
}
|
||||
}))
|
||||
})
|
||||
|
||||
// Embedded favicon/PWA assets
|
||||
http.HandleFunc("/favicon.ico", serveEmbedded("favicon.ico", "image/x-icon"))
|
||||
http.HandleFunc("/apple-touch-icon.png", serveEmbedded("apple-touch-icon.png", "image/png"))
|
||||
http.HandleFunc("/favicon-16x16.png", serveEmbedded("favicon-16x16.png", "image/png"))
|
||||
http.HandleFunc("/favicon-32x32.png", serveEmbedded("favicon-32x32.png", "image/png"))
|
||||
http.HandleFunc("/android-chrome-192x192.png", serveEmbedded("android-chrome-192x192.png", "image/png"))
|
||||
http.HandleFunc("/android-chrome-512x512.png", serveEmbedded("android-chrome-512x512.png", "image/png"))
|
||||
http.HandleFunc("/site.webmanifest", serveEmbedded("site.webmanifest", "application/manifest+json"))
|
||||
|
||||
fmt.Printf("slenpaste running at http://%s, storing in %s\n", listenAddr, staticDir)
|
||||
http.ListenAndServe(listenAddr, nil)
|
||||
_ = http.ListenAndServe(listenAddr, nil)
|
||||
}
|
||||
|
||||
1
site.webmanifest
Normal file
1
site.webmanifest
Normal file
@@ -0,0 +1 @@
|
||||
{"name":"slenpaste","short_name":"slenpaste","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
|
||||
Reference in New Issue
Block a user