Compare commits
9 Commits
csrf-token
...
ccb4ff7ecb
| Author | SHA1 | Date | |
|---|---|---|---|
| ccb4ff7ecb | |||
|
|
ba06fb0c7c | ||
|
|
d9de02f08d | ||
| e2d8bd344d | |||
| 82eb9de5f1 | |||
| 5bcca61d59 | |||
|
|
db5c2558f8 | ||
|
|
09d919ca27 | ||
|
|
50fa003842 |
@@ -1,7 +1,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
"ResendIt/internal/auth"
|
"ResendIt/internal/auth"
|
||||||
|
"ResendIt/internal/config"
|
||||||
"ResendIt/internal/db"
|
"ResendIt/internal/db"
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
"ResendIt/internal/user"
|
"ResendIt/internal/user"
|
||||||
@@ -14,6 +16,7 @@ import (
|
|||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
@@ -30,7 +33,7 @@ func main() {
|
|||||||
panic(fmt.Errorf("failed to connect database: %w", err))
|
panic(fmt.Errorf("failed to connect database: %w", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{})
|
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{}, &config.ConfigEntry{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error migrating database: %v\n", err)
|
fmt.Printf("Error migrating database: %v\n", err)
|
||||||
return
|
return
|
||||||
@@ -67,19 +70,33 @@ func main() {
|
|||||||
userService := user.NewService(userRepo)
|
userService := user.NewService(userRepo)
|
||||||
userHandler := user.NewHandler(userService)
|
userHandler := user.NewHandler(userService)
|
||||||
|
|
||||||
|
configRepo := config.NewRepository(dbCon)
|
||||||
|
configService := config.NewService(configRepo)
|
||||||
|
|
||||||
fileRepo := file.NewRepository(dbCon)
|
fileRepo := file.NewRepository(dbCon)
|
||||||
fileService := file.NewService(fileRepo, "./uploads")
|
fileService := file.NewService(fileRepo, "./uploads")
|
||||||
fileHandler := file.NewHandler(fileService)
|
fileHandler := file.NewHandler(fileService, configService)
|
||||||
|
|
||||||
createAdminUser(userService)
|
createAdminUser(userService)
|
||||||
|
|
||||||
apiRoute := r.Group("/api")
|
apiRoute := r.Group("/api")
|
||||||
|
// General API rate limiting to reduce abuse/spam.
|
||||||
|
apiRoute.Use(middleware.RateLimitByIPDynamic(
|
||||||
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst)
|
||||||
|
},
|
||||||
|
5*time.Minute,
|
||||||
|
))
|
||||||
|
|
||||||
auth.RegisterRoutes(apiRoute, authHandler)
|
auth.RegisterRoutes(apiRoute, authHandler, configService)
|
||||||
user.RegisterRoutes(apiRoute, userHandler)
|
user.RegisterRoutes(apiRoute, userHandler)
|
||||||
file.RegisterRoutes(apiRoute, fileHandler)
|
file.RegisterRoutes(apiRoute, fileHandler)
|
||||||
|
|
||||||
webHandler := web.NewHandler(fileService)
|
webHandler := web.NewHandler(fileService, configService)
|
||||||
web.RegisterRoutes(r, webHandler, userService)
|
web.RegisterRoutes(r, webHandler, userService)
|
||||||
|
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
|
|||||||
140
internal/api/middleware/ratelimit.go
Normal file
140
internal/api/middleware/ratelimit.go
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tokenBucket struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
rate float64 // tokens per second
|
||||||
|
burst float64 // max tokens
|
||||||
|
tokens float64
|
||||||
|
last time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTokenBucket(max int, per time.Duration, burst int) *tokenBucket {
|
||||||
|
if burst <= 0 {
|
||||||
|
burst = max
|
||||||
|
}
|
||||||
|
rate := float64(max) / per.Seconds()
|
||||||
|
b := float64(burst)
|
||||||
|
now := time.Now()
|
||||||
|
return &tokenBucket{rate: rate, burst: b, tokens: b, last: now}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *tokenBucket) allow() bool {
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
delta := now.Sub(b.last).Seconds()
|
||||||
|
b.last = now
|
||||||
|
|
||||||
|
b.tokens += delta * b.rate
|
||||||
|
if b.tokens > b.burst {
|
||||||
|
b.tokens = b.burst
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.tokens < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.tokens -= 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type ipClient struct {
|
||||||
|
bucket *tokenBucket
|
||||||
|
max int
|
||||||
|
burst int
|
||||||
|
lastSeen time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIP returns a Gin middleware that rate limits requests per client IP.
|
||||||
|
//
|
||||||
|
// max: max requests per time window (per)
|
||||||
|
// per: the time window duration
|
||||||
|
// burst: optional burst capacity (defaults to max if <=0)
|
||||||
|
// ttl: how long to keep idle IP buckets around
|
||||||
|
func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin.HandlerFunc {
|
||||||
|
return RateLimitByIPDynamic(func() int { return max }, per, func() int { return burst }, ttl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIPDynamic is like RateLimitByIP but reads max/burst dynamically.
|
||||||
|
// This allows changing limits at runtime (e.g. from an admin config page).
|
||||||
|
func RateLimitByIPDynamic(maxFn func() int, per time.Duration, burstFn func() int, ttl time.Duration) gin.HandlerFunc {
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
clients = make(map[string]*ipClient)
|
||||||
|
)
|
||||||
|
|
||||||
|
// opportunistic cleanup (runs at most once per minute)
|
||||||
|
var (
|
||||||
|
cleanupMu sync.Mutex
|
||||||
|
lastCleanup time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
cleanup := func(now time.Time) {
|
||||||
|
cleanupMu.Lock()
|
||||||
|
defer cleanupMu.Unlock()
|
||||||
|
if !lastCleanup.IsZero() && now.Sub(lastCleanup) < time.Minute {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastCleanup = now
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
for ip, c := range clients {
|
||||||
|
if now.Sub(c.lastSeen) > ttl {
|
||||||
|
delete(clients, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getClient := func(ip string, now time.Time, max int, burst int) *ipClient {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
c, ok := clients[ip]
|
||||||
|
if !ok {
|
||||||
|
c = &ipClient{bucket: newTokenBucket(max, per, burst), max: max, burst: burst, lastSeen: now}
|
||||||
|
clients[ip] = c
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
c.lastSeen = now
|
||||||
|
// If settings changed, reset the bucket.
|
||||||
|
if c.max != max || c.burst != burst {
|
||||||
|
c.bucket = newTokenBucket(max, per, burst)
|
||||||
|
c.max = max
|
||||||
|
c.burst = burst
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
now := time.Now()
|
||||||
|
cleanup(now)
|
||||||
|
|
||||||
|
ip := c.ClientIP()
|
||||||
|
max := maxFn()
|
||||||
|
if max <= 0 {
|
||||||
|
max = 1
|
||||||
|
}
|
||||||
|
burst := burstFn()
|
||||||
|
if burst <= 0 {
|
||||||
|
burst = max
|
||||||
|
}
|
||||||
|
client := getClient(ip, now, max, burst)
|
||||||
|
|
||||||
|
if !client.bucket.allow() {
|
||||||
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||||
|
"error": "rate limit exceeded",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,14 +2,30 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/api/middleware"
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterRoutes(r *gin.RouterGroup, h *Handler, cfg ConfigService) {
|
||||||
auth := r.Group("/auth")
|
auth := r.Group("/auth")
|
||||||
|
|
||||||
auth.POST("/login", h.Login)
|
// Stricter rate limit on login to reduce brute-force / log spam.
|
||||||
|
auth.POST("/login", middleware.RateLimitByIPDynamic(
|
||||||
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst)
|
||||||
|
},
|
||||||
|
15*time.Minute,
|
||||||
|
), h.Login)
|
||||||
|
|
||||||
protected := auth.Group("/")
|
protected := auth.Group("/")
|
||||||
protected.Use(middleware.AuthMiddleware())
|
protected.Use(middleware.AuthMiddleware())
|
||||||
|
|||||||
23
internal/config/defaults.go
Normal file
23
internal/config/defaults.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
const (
|
||||||
|
KeyUploadMaxFileSizeBytes = "upload.max_file_size_bytes"
|
||||||
|
KeyUploadMultiMaxFiles = "upload.multi.max_files"
|
||||||
|
KeyUploadMaxHours = "upload.max_hours"
|
||||||
|
KeyRateLimitLoginPerMinute = "ratelimit.login.per_minute"
|
||||||
|
KeyRateLimitApiPerMinute = "ratelimit.api.per_minute"
|
||||||
|
KeyRateLimitApiBurst = "ratelimit.api.burst"
|
||||||
|
KeyRateLimitLoginBurst = "ratelimit.login.burst"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Defaults (used when DB does not have an override)
|
||||||
|
const (
|
||||||
|
DefaultUploadMaxFileSizeBytes int64 = 10 << 30 // 10 GiB (matches MaxMultipartMemory intent)
|
||||||
|
DefaultUploadMultiMaxFiles = 50
|
||||||
|
DefaultUploadMaxHours = 24 * 7 // 7 days
|
||||||
|
|
||||||
|
DefaultRateLimitLoginPerMinute = 5
|
||||||
|
DefaultRateLimitLoginBurst = 10
|
||||||
|
DefaultRateLimitApiPerMinute = 60
|
||||||
|
DefaultRateLimitApiBurst = 30
|
||||||
|
)
|
||||||
21
internal/config/model.go
Normal file
21
internal/config/model.go
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ConfigEntry stores runtime-tunable configuration in the database.
|
||||||
|
// Values are stored as strings but helpers exist for ints/bools/durations.
|
||||||
|
//
|
||||||
|
// NOTE: keep keys stable; they are effectively part of the public admin surface.
|
||||||
|
//
|
||||||
|
// Example keys:
|
||||||
|
// - upload.max_file_size_bytes
|
||||||
|
// - upload.multi.max_files
|
||||||
|
// - upload.max_hours
|
||||||
|
// - ratelimit.login.per_minute
|
||||||
|
// - ratelimit.api.per_minute
|
||||||
|
//
|
||||||
|
type ConfigEntry struct {
|
||||||
|
Key string `gorm:"primaryKey;size:128"`
|
||||||
|
Value string `gorm:"size:2048"`
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
40
internal/config/repository.go
Normal file
40
internal/config/repository.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "gorm.io/gorm"
|
||||||
|
|
||||||
|
type Repository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(db *gorm.DB) *Repository {
|
||||||
|
return &Repository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Get(key string) (*ConfigEntry, error) {
|
||||||
|
var e ConfigEntry
|
||||||
|
if err := r.db.First(&e, "key = ?", key).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Upsert(key, value string) error {
|
||||||
|
// Prefer a simple approach that works across sqlite/postgres/mysql.
|
||||||
|
// Try update first, then insert if nothing updated.
|
||||||
|
res := r.db.Model(&ConfigEntry{}).Where("key = ?", key).Update("value", value)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return r.db.Create(&ConfigEntry{Key: key, Value: value}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) List() ([]ConfigEntry, error) {
|
||||||
|
var entries []ConfigEntry
|
||||||
|
if err := r.db.Order("key asc").Find(&entries).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
125
internal/config/service.go
Normal file
125
internal/config/service.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
repo *Repository
|
||||||
|
|
||||||
|
// Small in-memory cache to avoid hitting the DB on every request.
|
||||||
|
// Updated on SetString; lazy-filled on first Get.
|
||||||
|
mu sync.RWMutex
|
||||||
|
cache map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(r *Repository) *Service {
|
||||||
|
return &Service{repo: r, cache: make(map[string]string)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) List() ([]ConfigEntry, error) {
|
||||||
|
entries, err := s.repo.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// refresh cache snapshot
|
||||||
|
s.mu.Lock()
|
||||||
|
for _, e := range entries {
|
||||||
|
s.cache[e.Key] = e.Value
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SetString(key, value string) error {
|
||||||
|
if err := s.repo.Upsert(key, value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = value
|
||||||
|
s.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetStringDefault(key, def string) string {
|
||||||
|
s.mu.RLock()
|
||||||
|
v, ok := s.cache[key]
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if ok {
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
e, err := s.repo.Get(key)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = e.Value
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if e.Value == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return e.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetIntDefault(key string, def int) int {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetInt64Default(key string, def int64) int64 {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetBoolDefault(key string, def bool) bool {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
b, err := strconv.ParseBool(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetDurationSecondsDefault(key string, def time.Duration) time.Duration {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"ResendIt/internal/util"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -11,11 +13,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
service *Service
|
service *Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(s *Service) *Handler {
|
// ConfigService is the small interface we need from the config package.
|
||||||
return &Handler{service: s}
|
// Keeping it as an interface avoids import cycles and keeps file.Handler easy to test.
|
||||||
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(s *Service, cfg ConfigService) *Handler {
|
||||||
|
return &Handler{service: s, configService: cfg}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Upload(c *gin.Context) {
|
func (h *Handler) Upload(c *gin.Context) {
|
||||||
@@ -31,6 +41,12 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
if file.Size > maxSize {
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
f, err := file.Open()
|
f, err := file.Open()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
||||||
@@ -45,6 +61,10 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
if err != nil || hours <= 0 {
|
if err != nil || hours <= 0 {
|
||||||
hours = 24 // default
|
hours = 24 // default
|
||||||
}
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
|
|
||||||
duration := time.Duration(hours) * time.Hour
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
@@ -77,27 +97,12 @@ func (h *Handler) View(c *gin.Context) {
|
|||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, record.Filename))
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
c.File(record.Path)
|
c.File(record.Path)
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeFilename(name string) string {
|
|
||||||
// keep it simple: drop control chars and quotes
|
|
||||||
out := make([]rune, 0, len(name))
|
|
||||||
for _, r := range name {
|
|
||||||
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, r)
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
return "file"
|
|
||||||
}
|
|
||||||
return string(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func isXSSRisk(filename string) bool {
|
func isXSSRisk(filename string) bool {
|
||||||
ext := filepath.Ext(filename)
|
ext := filepath.Ext(filename)
|
||||||
switch ext {
|
switch ext {
|
||||||
@@ -116,8 +121,8 @@ func (h *Handler) Download(c *gin.Context) {
|
|||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, record.Filename))
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
//c.Header("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; script-src 'none'; style-src 'none';")
|
//c.Header("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; script-src 'none'; style-src 'none';")
|
||||||
//c.Header("Content-Type", "application/octet-stream")
|
//c.Header("Content-Type", "application/octet-stream")
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
|||||||
files := r.Group("/files")
|
files := r.Group("/files")
|
||||||
|
|
||||||
files.POST("/upload", h.Upload)
|
files.POST("/upload", h.Upload)
|
||||||
|
files.POST("/upload-multi", h.UploadMulti)
|
||||||
//files.GET("/download/:id", h.Download)
|
//files.GET("/download/:id", h.Download)
|
||||||
|
|
||||||
files.GET("/view/:id", h.View)
|
files.GET("/view/:id", h.View)
|
||||||
|
|||||||
78
internal/file/upload_multi.go
Normal file
78
internal/file/upload_multi.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UploadMulti accepts up to 10 files, zips them server-side, and returns a single download/view key.
|
||||||
|
func (h *Handler) UploadMulti(c *gin.Context) {
|
||||||
|
if err := c.Request.ParseMultipartForm(0); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
form, err := c.MultipartForm()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid multipart form"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
files := form.File["files"]
|
||||||
|
if len(files) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxFiles := h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles)
|
||||||
|
if len(files) > maxFiles {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
var total int64
|
||||||
|
for _, fh := range files {
|
||||||
|
if fh.Size > maxSize {
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
total += fh.Size
|
||||||
|
if total > maxSize {
|
||||||
|
// crude guard against huge bundles; you can add a separate config later.
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "bundle too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
once := c.PostForm("once") == "true"
|
||||||
|
|
||||||
|
durationStr := c.PostForm("duration")
|
||||||
|
hours, err := strconv.Atoi(durationStr)
|
||||||
|
if err != nil || hours <= 0 {
|
||||||
|
hours = 24
|
||||||
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
|
record, err := h.service.UploadBundle(files, once, duration)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"id": record.ID,
|
||||||
|
"deletion_id": record.DeletionID,
|
||||||
|
"filename": record.Filename,
|
||||||
|
"size": record.Size,
|
||||||
|
"expires_at": record.ExpiresAt,
|
||||||
|
"view_key": record.ViewID,
|
||||||
|
})
|
||||||
|
}
|
||||||
159
internal/file/zip.go
Normal file
159
internal/file/zip.go
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/util"
|
||||||
|
"archive/zip"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func safeZipName(name string) string {
|
||||||
|
name = filepath.Base(name)
|
||||||
|
name = strings.ReplaceAll(name, "\\", "_")
|
||||||
|
name = strings.ReplaceAll(name, "/", "_")
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" || name == "." {
|
||||||
|
return "file"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func dedupeName(name string, seen map[string]int) string {
|
||||||
|
if _, ok := seen[name]; !ok {
|
||||||
|
seen[name] = 1
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
seen[name]++
|
||||||
|
ext := filepath.Ext(name)
|
||||||
|
base := strings.TrimSuffix(name, ext)
|
||||||
|
return fmt.Sprintf("%s (%d)%s", base, seen[name], ext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cuteZipName(fileCount int) string {
|
||||||
|
adjective := util.RandomAdjective()
|
||||||
|
verb := util.RandomVerb()
|
||||||
|
thing := util.RandomThing()
|
||||||
|
return fmt.Sprintf("%d%s%s%s.zip", fileCount, adjective, verb, thing)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadBundle zips multiple uploaded files into a single .zip stored on disk and tracked as one FileRecord.
|
||||||
|
func (s *Service) UploadBundle(files []*multipart.FileHeader, deleteAfterDownload bool, expiresAfter time.Duration) (*FileRecord, error) {
|
||||||
|
if len(files) == 0 {
|
||||||
|
return nil, errors.New("no files")
|
||||||
|
}
|
||||||
|
if len(files) > 50 {
|
||||||
|
return nil, errors.New("too many files (max 50)")
|
||||||
|
}
|
||||||
|
|
||||||
|
folderID := uuid.NewString()
|
||||||
|
folderPath := filepath.Join(s.storageDir, folderID)
|
||||||
|
if err := os.MkdirAll(folderPath, os.ModePerm); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
zipDiskName := uuid.NewString() + ".zip"
|
||||||
|
zipPath := filepath.Join(folderPath, zipDiskName)
|
||||||
|
|
||||||
|
out, err := os.Create(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = out.Close()
|
||||||
|
if err != nil {
|
||||||
|
_ = os.Remove(zipPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
zw := zip.NewWriter(out)
|
||||||
|
defer func() { _ = zw.Close() }()
|
||||||
|
|
||||||
|
seen := map[string]int{}
|
||||||
|
for _, fh := range files {
|
||||||
|
rc, openErr := fh.Open()
|
||||||
|
if openErr != nil {
|
||||||
|
err = openErr
|
||||||
|
return nil, openErr
|
||||||
|
}
|
||||||
|
|
||||||
|
name := dedupeName(safeZipName(fh.Filename), seen)
|
||||||
|
h, _ := zip.FileInfoHeader(dummyFileInfo{name: name, size: fh.Size, mod: time.Now()})
|
||||||
|
h.Name = name
|
||||||
|
h.Method = zip.Deflate
|
||||||
|
|
||||||
|
w, createErr := zw.CreateHeader(h)
|
||||||
|
if createErr != nil {
|
||||||
|
_ = rc.Close()
|
||||||
|
err = createErr
|
||||||
|
return nil, createErr
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, copyErr := io.Copy(w, rc); copyErr != nil {
|
||||||
|
_ = rc.Close()
|
||||||
|
err = copyErr
|
||||||
|
return nil, copyErr
|
||||||
|
}
|
||||||
|
_ = rc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
if closeErr := zw.Close(); closeErr != nil {
|
||||||
|
err = closeErr
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
if closeErr := out.Close(); closeErr != nil {
|
||||||
|
err = closeErr
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
zipDisplayName := cuteZipName(len(files))
|
||||||
|
|
||||||
|
f := &FileRecord{
|
||||||
|
ID: folderID,
|
||||||
|
DeletionID: uuid.NewString(),
|
||||||
|
ViewID: uuid.NewString(),
|
||||||
|
Filename: zipDisplayName,
|
||||||
|
Path: zipPath,
|
||||||
|
Size: fileSize(zipPath),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
ExpiresAt: time.Now().Add(expiresAfter),
|
||||||
|
DeleteAfterDownload: deleteAfterDownload,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.repo.Create(f); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileSize(path string) int64 {
|
||||||
|
st, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return st.Size()
|
||||||
|
}
|
||||||
|
|
||||||
|
// dummyFileInfo provides minimal os.FileInfo for zip headers.
|
||||||
|
// This avoids relying on the underlying uploaded file having a real modtime.
|
||||||
|
// (zip.Writer can work without this too, but headers look nicer.)
|
||||||
|
type dummyFileInfo struct {
|
||||||
|
name string
|
||||||
|
size int64
|
||||||
|
mod time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d dummyFileInfo) Name() string { return d.name }
|
||||||
|
func (d dummyFileInfo) Size() int64 { return d.size }
|
||||||
|
func (d dummyFileInfo) Mode() os.FileMode { return 0o644 }
|
||||||
|
func (d dummyFileInfo) ModTime() time.Time { return d.mod }
|
||||||
|
func (d dummyFileInfo) IsDir() bool { return false }
|
||||||
|
func (d dummyFileInfo) Sys() any { return nil }
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
func HumanSize(size int64) string {
|
func HumanSize(size int64) string {
|
||||||
const unit = 1024
|
const unit = 1024
|
||||||
@@ -17,3 +20,24 @@ func HumanSize(size int64) string {
|
|||||||
"KMGTPE"[exp],
|
"KMGTPE"[exp],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SafeFilename(name string) string {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
|
||||||
|
out := make([]rune, 0, len(name))
|
||||||
|
for _, r := range name {
|
||||||
|
// block control chars (incl CR/LF/TAB), DEL, quotes, backslash
|
||||||
|
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return "file"
|
||||||
|
}
|
||||||
|
// optional: cap length
|
||||||
|
if len(out) > 200 {
|
||||||
|
out = out[:200]
|
||||||
|
}
|
||||||
|
return string(out)
|
||||||
|
}
|
||||||
|
|||||||
47
internal/util/worldlist.go
Normal file
47
internal/util/worldlist.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import "math/rand"
|
||||||
|
|
||||||
|
var Adjectives = []string{
|
||||||
|
"Cool", "Super", "Hot", "Spicy", "Sneaky", "Sleepy", "Tiny", "Mega", "Cosmic", "Silly",
|
||||||
|
"Cursed", "Blessed", "Wiggly", "Giga", "Chonky", "Shiny", "Angry", "Happy", "Soft", "Turbo",
|
||||||
|
"Zany", "Snappy", "Fluffy", "Cranky", "Glitchy", "Bubbly", "Frosty", "Electric", "Jolly", "Mystic",
|
||||||
|
"Weird", "Chunky", "Psycho", "Cheesy", "Smelly", "Slippery", "Fiery", "Wacky", "Vivid", "Hyper",
|
||||||
|
"Soggy", "Grumpy", "Luminous", "Spooky", "Funky", "Twisted", "Nifty", "Prickly", "Velvet", "Epic",
|
||||||
|
"Glorious", "Majestic", "Quirky", "Radiant", "Sneaky", "Bouncy", "Mysterious", "Noodle", "Raging", "Zesty",
|
||||||
|
"Shimmering", "Fabled", "Plush", "Snazzy", "Stormy", "Gleaming", "Vibrant", "Odd", "Tasty", "Whimsical",
|
||||||
|
"Feral", "Clever", "Jumpy", "Dizzy", "Wicked", "Chilly", "Hasty", "Bizarre", "Snug", "Cheerful",
|
||||||
|
}
|
||||||
|
|
||||||
|
var Things = []string{
|
||||||
|
"Potato", "Griefers", "Raccoons", "Pigeons", "Wizards", "Ninjas", "Pickles", "Dragons", "Goblins", "Burgers",
|
||||||
|
"Pancakes", "Hamsters", "Bananas", "Comets", "Robots", "Cats", "Kiwis", "Frogs", "Cupcakes", "Sprites",
|
||||||
|
"Monsters", "Aliens", "Slimes", "Tacos", "Unicorns", "Ghosts", "Snails", "Vampires", "Donuts", "Owls",
|
||||||
|
"Zombies", "Mermaids", "Beavers", "Octopuses", "Chickens", "Penguins", "Mushrooms", "Felines", "Llamas", "Waffles",
|
||||||
|
"Baboons", "Dragettes", "Pixies", "Sharks", "Elephants", "Squirrels", "Gnomes", "Wombats", "Cacti", "Puppets",
|
||||||
|
"Koalas", "Moose", "Yeti", "Bats", "Crabs", "Otters", "Trolls", "Geckos", "Parrots", "Snakes",
|
||||||
|
"Sloths", "Clowns", "Jellyfish", "Froggies", "Dragoneers", "Nuggets", "Sprites", "Critters", "Knights", "Squids",
|
||||||
|
"Tigers", "Foxes", "Penguinos", "Burglebugs", "Clouds", "Fireflies", "Shrooms", "Mice", "Wizards", "Berries",
|
||||||
|
}
|
||||||
|
|
||||||
|
var Verbs = []string{
|
||||||
|
"Zoom", "Bonk", "Yeet", "Vibe", "Hack", "Spark", "Bounce", "Nibble", "Smuggle", "Cook",
|
||||||
|
"Flick", "Slap", "Whack", "Zap", "Blast", "Slam", "Twist", "Flip", "Slide", "Crash",
|
||||||
|
"Pop", "Fling", "Snatch", "Boing", "Sizzle", "Clap", "Roar", "Sniff", "Swoop", "Blink",
|
||||||
|
"Dodge", "Smash", "Roll", "Twirl", "Snore", "Drip", "Slurp", "Chomp", "Shuffle", "Juggle",
|
||||||
|
"Bounce", "Whirl", "Gush", "Spit", "Frolic", "Honk", "Wiggle", "Crackle", "Pounce", "Sprinkle",
|
||||||
|
"Slam", "Zoomerang", "Flop", "Squish", "Boop", "Whiz", "Flipflop", "Snip", "Glide", "Zapzap",
|
||||||
|
"Bop", "Wobble", "Fumble", "Twinkle", "Splash", "Dribble", "Clobber", "Whackadoo", "Bounceback", "Snizzle",
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomAdjective() string {
|
||||||
|
return Adjectives[rand.Intn(len(Adjectives))]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomThing() string {
|
||||||
|
return Things[rand.Intn(len(Things))]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomVerb() string {
|
||||||
|
return Verbs[rand.Intn(len(Verbs))]
|
||||||
|
}
|
||||||
151
internal/web/config.go
Normal file
151
internal/web/config.go
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConfigPageData struct {
|
||||||
|
Success bool
|
||||||
|
Error string
|
||||||
|
|
||||||
|
UploadMaxFileSizeMB int64
|
||||||
|
UploadMultiMaxFiles int
|
||||||
|
UploadMaxHours int
|
||||||
|
|
||||||
|
RateLimitLoginPerMinute int
|
||||||
|
RateLimitLoginBurst int
|
||||||
|
RateLimitApiPerMinute int
|
||||||
|
RateLimitApiBurst int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigPage renders a modular admin config screen.
|
||||||
|
func (h *Handler) ConfigPage(c *gin.Context) {
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
maxBytes := cfg.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Success: c.Query("saved") == "1",
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: cfg.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: cfg.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: cfg.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: cfg.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
}
|
||||||
|
|
||||||
|
c.HTML(http.StatusOK, "config.html", data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) ConfigSave(c *gin.Context) {
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
// Parse + validate.
|
||||||
|
parseInt := func(name string, min, max int) (int, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
parseInt64 := func(name string, min int64, max int64) (int64, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
maxMB, err := parseInt64("upload_max_file_size_mb", 1, 1024*1024)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max file size")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxFiles, err := parseInt("upload_multi_max_files", 1, 500)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max files")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxHours, err := parseInt("upload_max_hours", 1, 24*365)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max hours")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limits: stored, but not applied dynamically yet.
|
||||||
|
loginPerMin, err := parseInt("ratelimit_login_per_minute", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid login rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loginBurst, err := parseInt("ratelimit_login_burst", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid login burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiPerMin, err := parseInt("ratelimit_api_per_minute", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid api rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiBurst, err := parseInt("ratelimit_api_burst", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid api burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist.
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxFileSizeBytes, strconv.FormatInt(maxMB*1024*1024, 10)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMultiMaxFiles, strconv.Itoa(maxFiles)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxHours, strconv.Itoa(maxHours)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginPerMinute, strconv.Itoa(loginPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginBurst, strconv.Itoa(loginBurst))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiPerMinute, strconv.Itoa(apiPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiBurst, strconv.Itoa(apiBurst))
|
||||||
|
|
||||||
|
c.Redirect(http.StatusFound, "/config?saved=1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) renderConfigError(c *gin.Context, msg string) {
|
||||||
|
maxBytes := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Error: msg,
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: h.configService.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: h.configService.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: h.configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: h.configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
}
|
||||||
|
c.HTML(http.StatusBadRequest, "config.html", data)
|
||||||
|
}
|
||||||
@@ -2,18 +2,28 @@ package web
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
fileService *file.Service
|
fileService *file.Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(fileService *file.Service) *Handler {
|
// ConfigService is the small interface needed by the web layer.
|
||||||
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
SetString(key, value string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(fileService *file.Service, cfg ConfigService) *Handler {
|
||||||
return &Handler{
|
return &Handler{
|
||||||
fileService: fileService,
|
fileService: fileService,
|
||||||
|
configService: cfg,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,10 +80,35 @@ func (h *Handler) AdminPage(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only check files on the current page.
|
||||||
|
// Status meanings:
|
||||||
|
// - green: file exists on disk
|
||||||
|
// - red: file missing
|
||||||
|
// - rainbow: stat error (something unexpected)
|
||||||
|
type AdminFileView struct {
|
||||||
|
file.FileRecord
|
||||||
|
ActualStatus string
|
||||||
|
}
|
||||||
|
|
||||||
|
adminFiles := make([]AdminFileView, 0, len(files))
|
||||||
|
for _, f := range files {
|
||||||
|
status := "red"
|
||||||
|
if f.Path != "" {
|
||||||
|
if _, err := os.Stat(f.Path); err == nil {
|
||||||
|
status = "green"
|
||||||
|
} else if os.IsNotExist(err) {
|
||||||
|
status = "red"
|
||||||
|
} else {
|
||||||
|
status = "rainbow"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
adminFiles = append(adminFiles, AdminFileView{FileRecord: f, ActualStatus: status})
|
||||||
|
}
|
||||||
|
|
||||||
totalPages := (totalCount + limit - 1) / limit
|
totalPages := (totalCount + limit - 1) / limit
|
||||||
|
|
||||||
c.HTML(200, "admin.html", gin.H{
|
c.HTML(200, "admin.html", gin.H{
|
||||||
"Files": files,
|
"Files": adminFiles,
|
||||||
"Page": page,
|
"Page": page,
|
||||||
"TotalPages": totalPages,
|
"TotalPages": totalPages,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ func RegisterRoutes(r *gin.Engine, h *Handler, userService *user.Service) {
|
|||||||
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
||||||
|
|
||||||
adminRoutes.GET("/admin", h.AdminPage)
|
adminRoutes.GET("/admin", h.AdminPage)
|
||||||
|
adminRoutes.GET("/config", h.ConfigPage)
|
||||||
|
adminRoutes.POST("/config", h.ConfigSave)
|
||||||
adminRoutes.GET("/logout", h.Logout)
|
adminRoutes.GET("/logout", h.Logout)
|
||||||
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,24 @@
|
|||||||
td { border: 1px solid #000; padding: 10px; font-size: 13px; font-weight: 500; }
|
td { border: 1px solid #000; padding: 10px; font-size: 13px; font-weight: 500; }
|
||||||
tr:hover { background: #ffff00; }
|
tr:hover { background: #ffff00; }
|
||||||
|
|
||||||
|
/* Actual file status dot */
|
||||||
|
.dot { width: 12px; height: 12px; border: 2px solid #000; display: inline-block; }
|
||||||
|
.dot-green { background: #00ff00; }
|
||||||
|
.dot-red { background: #ff0000; }
|
||||||
|
.dot-rainbow {
|
||||||
|
animation: rainbow 0.8s linear infinite;
|
||||||
|
background: red;
|
||||||
|
}
|
||||||
|
@keyframes rainbow {
|
||||||
|
0% { background: #ff0000; }
|
||||||
|
16% { background: #ff9900; }
|
||||||
|
33% { background: #ffff00; }
|
||||||
|
50% { background: #00ff00; }
|
||||||
|
66% { background: #00ccff; }
|
||||||
|
83% { background: #9900ff; }
|
||||||
|
100% { background: #ff0000; }
|
||||||
|
}
|
||||||
|
|
||||||
/* Harsh Status Tags */
|
/* Harsh Status Tags */
|
||||||
.status-tag { font-weight: 900; font-size: 11px; padding: 3px 6px; border: 2px solid #000; display: inline-block; text-transform: uppercase; }
|
.status-tag { font-weight: 900; font-size: 11px; padding: 3px 6px; border: 2px solid #000; display: inline-block; text-transform: uppercase; }
|
||||||
.status-deleted { background: #000; color: #ff0000; }
|
.status-deleted { background: #000; color: #ff0000; }
|
||||||
@@ -95,6 +113,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col items-end gap-2">
|
<div class="flex flex-col items-end gap-2">
|
||||||
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
||||||
|
<a href="/config" class="nav-link">CONFIG_MODULE</a>
|
||||||
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -109,12 +128,13 @@
|
|||||||
<th>Hits</th>
|
<th>Hits</th>
|
||||||
<th>Burn</th>
|
<th>Burn</th>
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
|
<th>Actual</th>
|
||||||
<th>System_Actions</th>
|
<th>System_Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{{if not .Files}}
|
{{if not .Files}}
|
||||||
<tr><td colspan="7" class="text-center py-10 font-bold uppercase italic">Zero files in buffer</td></tr>
|
<tr><td colspan="8" class="text-center py-10 font-bold uppercase italic">Zero files in buffer</td></tr>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{range .Files}}
|
{{range .Files}}
|
||||||
<tr>
|
<tr>
|
||||||
@@ -147,6 +167,16 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
|
<td class="text-center">
|
||||||
|
{{if eq .ActualStatus "green"}}
|
||||||
|
<span class="dot dot-green" title="File exists"></span>
|
||||||
|
{{else if eq .ActualStatus "red"}}
|
||||||
|
<span class="dot dot-red" title="File missing"></span>
|
||||||
|
{{else}}
|
||||||
|
<span class="dot dot-rainbow" title="Stat error"></span>
|
||||||
|
{{end}}
|
||||||
|
</td>
|
||||||
|
|
||||||
<td>
|
<td>
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
{{if not .Deleted}}
|
{{if not .Deleted}}
|
||||||
|
|||||||
213
templates/config.html
Normal file
213
templates/config.html
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Config Module</title>
|
||||||
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* { border-radius: 0 !important; }
|
||||||
|
body {
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
background: #fff;
|
||||||
|
color: #000;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.box { border: 3px solid #000; background: #fff; padding: 20px; }
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
border-bottom: 3px solid #000;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 300px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
border: 2px solid #000;
|
||||||
|
padding: 6px 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
font-size: 11px;
|
||||||
|
font-style: italic;
|
||||||
|
margin-top: 4px;
|
||||||
|
border-left: 4px solid #000;
|
||||||
|
padding-left: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button, .button {
|
||||||
|
border: 2px solid #000;
|
||||||
|
background: #fff;
|
||||||
|
padding: 6px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover, .button:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ok {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #00ff00;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.err {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="max-w-4xl mx-auto">
|
||||||
|
|
||||||
|
<!-- HEADER -->
|
||||||
|
<header class="mb-6 border-b-8 border-black pb-4 flex justify-between items-start">
|
||||||
|
<h1 class="text-4xl font-black uppercase tracking-tighter leading-none">
|
||||||
|
Config_Settings
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div class="flex flex-col items-end gap-2">
|
||||||
|
<a href="/admin" class="nav-link">Admin_Panel</a>
|
||||||
|
<a href="/config" class="nav-link">Reload_Config</a>
|
||||||
|
<a href="/logout" class="nav-link text-red-600">Logout</a>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- STATUS -->
|
||||||
|
{{if .Success}}
|
||||||
|
<div class="ok mb-4">CONFIG_SAVED_SUCCESSFULLY</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .Error}}
|
||||||
|
<div class="err mb-4">{{.Error}}</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
<form method="POST" action="/config">
|
||||||
|
|
||||||
|
<!-- UPLOAD SETTINGS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Upload_Control</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_File_Size_MB</label>
|
||||||
|
<div>
|
||||||
|
<input type="number" min="1" name="upload_max_file_size_mb" value="{{.UploadMaxFileSizeMB}}">
|
||||||
|
<div class="hint">Hard limit enforced by upload endpoints</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Multi_Upload_Limit</label>
|
||||||
|
<div>
|
||||||
|
<input type="number" min="1" name="upload_multi_max_files" value="{{.UploadMultiMaxFiles}}">
|
||||||
|
<div class="hint">Max files per multi-upload request</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_Expiry_Hours</label>
|
||||||
|
<div>
|
||||||
|
<input type="number" min="1" name="upload_max_hours" value="{{.UploadMaxHours}}">
|
||||||
|
<div class="hint">User duration capped to this value</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RATE LIMITS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Rate_Limits_(Static)</div>
|
||||||
|
|
||||||
|
<div class="hint mb-4">
|
||||||
|
Changes require server restart to take effect
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_per_minute" value="{{.RateLimitLoginPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_burst" value="{{.RateLimitLoginBurst}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_per_minute" value="{{.RateLimitApiPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_burst" value="{{.RateLimitApiBurst}}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ACTIONS -->
|
||||||
|
<div class="flex justify-between items-center border-t-8 border-black pt-4">
|
||||||
|
<button type="submit">Commit_Config</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/change-password" class="fixed bottom-1 left-1 text-[10px] underline">
|
||||||
|
CHANGE_PASSWORD
|
||||||
|
</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -102,7 +102,7 @@
|
|||||||
|
|
||||||
<div id="upload-ui">
|
<div id="upload-ui">
|
||||||
<div id="drop-zone" class="drop-zone mb-4">
|
<div id="drop-zone" class="drop-zone mb-4">
|
||||||
<input type="file" id="fileInput" class="hidden">
|
<input type="file" id="fileInput" class="hidden" multiple>
|
||||||
|
|
||||||
<div id="dz-content">
|
<div id="dz-content">
|
||||||
<span id="dz-text" class="text-sm">Click to select or drop file</span>
|
<span id="dz-text" class="text-sm">Click to select or drop file</span>
|
||||||
@@ -232,20 +232,36 @@
|
|||||||
|
|
||||||
input.onchange = () => {
|
input.onchange = () => {
|
||||||
if (input.files.length) {
|
if (input.files.length) {
|
||||||
showFile(input.files[0]);
|
showFiles(input.files);
|
||||||
uploadBtn.disabled = false;
|
uploadBtn.disabled = false;
|
||||||
} else {
|
} else {
|
||||||
uploadBtn.disabled = true;
|
uploadBtn.disabled = true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function showFile(file) {
|
function showFiles(fileList) {
|
||||||
|
const files = Array.from(fileList || []);
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
const total = files.reduce((acc, f) => acc + f.size, 0);
|
||||||
|
|
||||||
|
if (files.length === 1) {
|
||||||
|
document.getElementById('dz-text').innerText =
|
||||||
|
`${files[0].name} (${formatBytes(files[0].size)})`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById('dz-text').innerText =
|
document.getElementById('dz-text').innerText =
|
||||||
`${file.name} (${formatBytes(file.size)})`;
|
`${files.length} FILES (${formatBytes(total)}) — will be zipped`;
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadBtn.onclick = () => {
|
uploadBtn.onclick = () => {
|
||||||
if (input.files.length) handleUpload(input.files[0]);
|
if (!input.files.length) return;
|
||||||
|
if (input.files.length === 1) {
|
||||||
|
handleUploadSingle(input.files[0]);
|
||||||
|
} else {
|
||||||
|
handleUploadMulti(input.files);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
cancelBtn.onclick = (e) => {
|
cancelBtn.onclick = (e) => {
|
||||||
@@ -257,7 +273,15 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleUpload(file) {
|
function commonFormData() {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("once", document.getElementById("once").checked ? "true" : "false");
|
||||||
|
const hours = parseInt(document.getElementById("duration").value, 10);
|
||||||
|
fd.append("duration", hours);
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startUploadUI() {
|
||||||
uploadBtn.disabled = true;
|
uploadBtn.disabled = true;
|
||||||
uploadBtn.innerText = "UPLOADING...";
|
uploadBtn.innerText = "UPLOADING...";
|
||||||
cancelBtn.classList.remove('hidden');
|
cancelBtn.classList.remove('hidden');
|
||||||
@@ -265,16 +289,9 @@
|
|||||||
progressContainer.classList.remove("hidden");
|
progressContainer.classList.remove("hidden");
|
||||||
progressText.classList.remove("hidden");
|
progressText.classList.remove("hidden");
|
||||||
statsText.classList.remove("hidden");
|
statsText.classList.remove("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
const fd = new FormData();
|
function setupXHRHandlers(xhr) {
|
||||||
fd.append("file", file);
|
|
||||||
fd.append("once", document.getElementById("once").checked ? "true" : "false");
|
|
||||||
const hours = parseInt(document.getElementById("duration").value, 10);
|
|
||||||
fd.append("duration", hours);
|
|
||||||
|
|
||||||
const xhr = new XMLHttpRequest();
|
|
||||||
currentXhr = xhr;
|
|
||||||
|
|
||||||
let startTime = Date.now();
|
let startTime = Date.now();
|
||||||
|
|
||||||
xhr.upload.onprogress = (e) => {
|
xhr.upload.onprogress = (e) => {
|
||||||
@@ -301,7 +318,6 @@
|
|||||||
const data = JSON.parse(xhr.responseText);
|
const data = JSON.parse(xhr.responseText);
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
|
|
||||||
// Redirect using view key
|
|
||||||
window.location.href = "/f/" + data.view_key;
|
window.location.href = "/f/" + data.view_key;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -319,11 +335,38 @@
|
|||||||
location.reload();
|
location.reload();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUploadSingle(file) {
|
||||||
|
startUploadUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
setupXHRHandlers(xhr);
|
||||||
|
|
||||||
xhr.open("POST", "/api/files/upload");
|
xhr.open("POST", "/api/files/upload");
|
||||||
xhr.send(fd);
|
xhr.send(fd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleUploadMulti(fileList) {
|
||||||
|
startUploadUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
Array.from(fileList).forEach(f => fd.append("files", f));
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
setupXHRHandlers(xhr);
|
||||||
|
|
||||||
|
xhr.open("POST", "/api/files/upload-multi");
|
||||||
|
xhr.send(fd);
|
||||||
|
}
|
||||||
|
|
||||||
function copy(id) {
|
function copy(id) {
|
||||||
const el = document.getElementById(id);
|
const el = document.getElementById(id);
|
||||||
el.select();
|
el.select();
|
||||||
|
|||||||
Reference in New Issue
Block a user