refactored code, added HTML template for rich embeds
This commit is contained in:
parent
2fdaba0d5d
commit
881619dfac
1 changed files with 271 additions and 141 deletions
412
main.go
412
main.go
|
@ -1,36 +1,41 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"mime"
|
"mime"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
"github.com/msteinert/pam"
|
||||||
"github.com/msteinert/pam"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Listen string
|
Listen string
|
||||||
StorageDir string
|
StorageDir string
|
||||||
BaseURL string
|
BaseURL string
|
||||||
MaxFileSize int64
|
MaxFileSize int64
|
||||||
ExpireHours int
|
ExpireHours int
|
||||||
IndexHTML string
|
IndexHTML string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImagePageData struct {
|
||||||
|
Title string
|
||||||
|
ImageURL string
|
||||||
|
BaseURL string
|
||||||
|
Description string
|
||||||
|
FullImageURL string
|
||||||
}
|
}
|
||||||
|
|
||||||
var config Config
|
var config Config
|
||||||
|
|
||||||
var indexHTML string
|
var indexHTML string
|
||||||
|
var imagePageTemplate string
|
||||||
|
|
||||||
func loadIndexHTML() {
|
func loadIndexHTML() {
|
||||||
content, err := os.ReadFile(config.IndexHTML)
|
content, err := os.ReadFile(config.IndexHTML)
|
||||||
|
@ -38,141 +43,266 @@ func loadIndexHTML() {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
indexHTML = string(content)
|
indexHTML = string(content)
|
||||||
|
|
||||||
|
// HTML template for rendering images
|
||||||
|
imagePageTemplate = `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="theme-color" content="#6BABDA">
|
||||||
|
<title>{{.Title}}</title>
|
||||||
|
|
||||||
|
<!-- Open Graph meta tags -->
|
||||||
|
<meta property="og:title" content="{{.Title}}">
|
||||||
|
<meta property="og:type" content="image">
|
||||||
|
<meta property="og:image" content="{{.FullImageURL}}">
|
||||||
|
<meta property="og:url" content="{{.FullImageURL}}">
|
||||||
|
<meta property="og:description" content="{{.Description}}">
|
||||||
|
|
||||||
|
<!-- Twitter Card meta tags for better image display -->
|
||||||
|
<meta name="twitter:card" content="summary_large_image">
|
||||||
|
<meta name="twitter:title" content="{{.Title}}">
|
||||||
|
<meta name="twitter:description" content="{{.Description}}">
|
||||||
|
<meta name="twitter:image" content="{{.FullImageURL}}">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: monospace;
|
||||||
|
margin: 0;
|
||||||
|
padding: 20px;
|
||||||
|
text-align: center;
|
||||||
|
background-color: #111111;
|
||||||
|
color: #6BABDA;
|
||||||
|
}
|
||||||
|
img {
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
border: 1px solid #6babda;
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
max-width: 90%;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
color: #8CC7E7;
|
||||||
|
text-decoration: none;
|
||||||
|
border-bottom: 1px dotted #8CC7E7;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
border-bottom: 1px solid #8CC7E7;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>{{.Title}}</h1>
|
||||||
|
<img src="{{.ImageURL}}?raw=true" alt="{{.Title}}"><br>
|
||||||
|
<a href="{{.ImageURL}}?download=true">Download Image</a>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
flag.StringVar(&config.Listen, "listen", ":8080", "Address to listen on")
|
flag.StringVar(&config.Listen, "listen", ":8080", "Address to listen on")
|
||||||
flag.StringVar(&config.StorageDir, "storage", "/tmp/share", "Directory to store uploaded files")
|
flag.StringVar(&config.StorageDir, "storage", "/tmp/share", "Directory to store uploaded files")
|
||||||
flag.StringVar(&config.BaseURL, "baseurl", "http://localhost:8080", "Base URL for generated file links")
|
flag.StringVar(&config.BaseURL, "baseurl", "http://localhost:8080", "Base URL for generated file links")
|
||||||
flag.Int64Var(&config.MaxFileSize, "maxsize", 10*1024*1024, "Maximum allowed file size in bytes")
|
flag.Int64Var(&config.MaxFileSize, "maxsize", 10*1024*1024, "Maximum allowed file size in bytes")
|
||||||
flag.IntVar(&config.ExpireHours, "expire", 24, "Number of hours before files are deleted")
|
flag.IntVar(&config.ExpireHours, "expire", 24, "Number of hours before files are deleted")
|
||||||
flag.StringVar(&config.IndexHTML, "index", "index.html", "Path to html file to serve as index")
|
flag.StringVar(&config.IndexHTML, "index", "index.html", "Path to html file to serve as index")
|
||||||
}
|
}
|
||||||
|
|
||||||
func authenticateUser(username, password string) bool {
|
func authenticateUser(username, password string) bool {
|
||||||
t, err := pam.StartFunc("system-auth", username, func(s pam.Style, msg string) (string, error) {
|
t, err := pam.StartFunc("system-auth", username, func(s pam.Style, msg string) (string, error) {
|
||||||
switch s {
|
switch s {
|
||||||
case pam.PromptEchoOff:
|
case pam.PromptEchoOff:
|
||||||
return password, nil
|
return password, nil
|
||||||
}
|
}
|
||||||
return "", fmt.Errorf("unsupported PAM style")
|
return "", fmt.Errorf("unsupported PAM style")
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
err = t.Authenticate(0)
|
err = t.Authenticate(0)
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateRandomFilename() (string, error) {
|
func generateRandomFilename() (string, error) {
|
||||||
bytes := make([]byte, 16)
|
bytes := make([]byte, 16)
|
||||||
if _, err := rand.Read(bytes); err != nil {
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return hex.EncodeToString(bytes), nil
|
return hex.EncodeToString(bytes), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func cleanupOldFiles() {
|
func cleanupOldFiles() {
|
||||||
ticker := time.NewTicker(1 * time.Hour)
|
ticker := time.NewTicker(1 * time.Hour)
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
err := filepath.Walk(config.StorageDir, func(path string, info os.FileInfo, err error) error {
|
err := filepath.Walk(config.StorageDir, func(path string, info os.FileInfo, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !info.IsDir() && now.Sub(info.ModTime()) > time.Duration(config.ExpireHours)*time.Hour {
|
if !info.IsDir() && now.Sub(info.ModTime()) > time.Duration(config.ExpireHours)*time.Hour {
|
||||||
os.Remove(path)
|
os.Remove(path)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Cleanup error: %v", err)
|
log.Printf("Cleanup error: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isImageFile(filePath string) bool {
|
||||||
|
file, err := os.Open(filePath)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error opening file for MIME detection: %v", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
buffer := make([]byte, 512)
|
||||||
|
_, err = file.Read(buffer)
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
log.Printf("Error reading file for MIME detection: %v", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = file.Seek(0, 0)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error seeking file after MIME detection: %v", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
contentType := http.DetectContentType(buffer)
|
||||||
|
log.Printf("Detected content type for %s: %s", filePath, contentType)
|
||||||
|
|
||||||
|
return strings.HasPrefix(contentType, "image/")
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPut {
|
if r.Method != http.MethodPut {
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
username, password, ok := r.BasicAuth()
|
||||||
username, password, ok := r.BasicAuth()
|
if !ok || !authenticateUser(username, password) {
|
||||||
if !ok || !authenticateUser(username, password) {
|
w.Header().Set("WWW-Authenticate", `Basic realm="Upload"`)
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="Upload"`)
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
return
|
||||||
return
|
}
|
||||||
}
|
if r.ContentLength > config.MaxFileSize {
|
||||||
|
http.Error(w, "File too large", http.StatusRequestEntityTooLarge)
|
||||||
if r.ContentLength > config.MaxFileSize {
|
return
|
||||||
http.Error(w, "File too large", http.StatusRequestEntityTooLarge)
|
}
|
||||||
return
|
ext := path.Ext(r.URL.Path)
|
||||||
}
|
if ext == "" {
|
||||||
|
contentType := r.Header.Get("Content-Type")
|
||||||
ext := path.Ext(r.URL.Path)
|
exts, _ := mime.ExtensionsByType(contentType)
|
||||||
if ext == "" {
|
if len(exts) > 0 {
|
||||||
contentType := r.Header.Get("Content-Type")
|
ext = exts[0]
|
||||||
exts, _ := mime.ExtensionsByType(contentType)
|
}
|
||||||
if len(exts) > 0 {
|
}
|
||||||
ext = exts[0]
|
randomName, err := generateRandomFilename()
|
||||||
}
|
if err != nil {
|
||||||
}
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
randomName, err := generateRandomFilename()
|
}
|
||||||
if err != nil {
|
filename := randomName + ext
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
filepath := path.Join(config.StorageDir, filename)
|
||||||
return
|
f, err := os.Create(filepath)
|
||||||
}
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
filename := randomName + ext
|
return
|
||||||
filepath := path.Join(config.StorageDir, filename)
|
}
|
||||||
|
defer f.Close()
|
||||||
f, err := os.Create(filepath)
|
_, err = io.Copy(f, r.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
os.Remove(filepath)
|
||||||
return
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
}
|
return
|
||||||
defer f.Close()
|
}
|
||||||
|
fileURL := strings.TrimRight(config.BaseURL, "/") + "/" + filename
|
||||||
_, err = io.Copy(f, r.Body)
|
fmt.Fprintf(w, "%s\n", fileURL)
|
||||||
if err != nil {
|
|
||||||
os.Remove(filepath)
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fileURL := strings.TrimRight(config.BaseURL, "/") + "/" + filename
|
|
||||||
fmt.Fprintf(w, "%s\n", fileURL)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleIndex(w http.ResponseWriter, r *http.Request) {
|
func handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.URL.Path != "/" {
|
if r.URL.Path == "/" {
|
||||||
http.ServeFile(w, r, path.Join(config.StorageDir, r.URL.Path))
|
tmpl, err := template.New("index").Parse(indexHTML)
|
||||||
return
|
if err != nil {
|
||||||
}
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
tmpl, err := template.New("index").Parse(indexHTML)
|
}
|
||||||
if err != nil {
|
tmpl.Execute(w, config)
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
return
|
||||||
return
|
}
|
||||||
}
|
|
||||||
|
requestPath := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
tmpl.Execute(w, config)
|
filePath := path.Join(config.StorageDir, requestPath)
|
||||||
|
|
||||||
|
log.Printf("Requested path: %s, File path: %s", r.URL.Path, filePath)
|
||||||
|
|
||||||
|
fileInfo, err := os.Stat(filePath)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("File not found: %s, Error: %v", filePath, err)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.URL.Query().Get("raw") == "true" || r.URL.Query().Get("download") == "true" {
|
||||||
|
if r.URL.Query().Get("download") == "true" {
|
||||||
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(requestPath)))
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Serving file directly: %s", filePath)
|
||||||
|
http.ServeFile(w, r, filePath)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isImageFile(filePath) {
|
||||||
|
log.Printf("File is not an image, serving directly: %s", filePath)
|
||||||
|
http.ServeFile(w, r, filePath)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl, err := template.New("imagePage").Parse(imagePageTemplate)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Template parsing error: %v", err)
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
baseURL := strings.TrimRight(config.BaseURL, "/")
|
||||||
|
|
||||||
|
data := ImagePageData{
|
||||||
|
Title: "Filename: " + filepath.Base(requestPath),
|
||||||
|
ImageURL: r.URL.Path, // Use the original request path for the image URL
|
||||||
|
BaseURL: baseURL,
|
||||||
|
Description: fmt.Sprintf("Image shared on %s, size: %d bytes", fileInfo.ModTime().Format("Jan 2, 2006"), fileInfo.Size()),
|
||||||
|
FullImageURL: baseURL + r.URL.Path + "?raw=true", // Full URL for the image with raw parameter
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Serving image template with data: %+v", data)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
tmpl.Execute(w, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
loadIndexHTML()
|
loadIndexHTML()
|
||||||
|
if err := os.MkdirAll(config.StorageDir, 0700); err != nil {
|
||||||
if err := os.MkdirAll(config.StorageDir, 0700); err != nil {
|
log.Fatalf("Failed to create storage directory: %v", err)
|
||||||
log.Fatalf("Failed to create storage directory: %v", err)
|
}
|
||||||
}
|
go cleanupOldFiles()
|
||||||
|
http.HandleFunc("/", handleIndex)
|
||||||
go cleanupOldFiles()
|
http.HandleFunc("/upload", handleUpload)
|
||||||
|
log.Printf("Starting server on %s", config.Listen)
|
||||||
http.HandleFunc("/", handleIndex)
|
log.Printf("Storage directory: %s", config.StorageDir)
|
||||||
http.HandleFunc("/upload", handleUpload)
|
log.Printf("Base URL: %s", config.BaseURL)
|
||||||
|
log.Fatal(http.ListenAndServe(config.Listen, nil))
|
||||||
log.Printf("Starting server on %s", config.Listen)
|
|
||||||
log.Fatal(http.ListenAndServe(config.Listen, nil))
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue