Initial commit: unified dashboard suite state with Khira and Image Manipulator 3-file setup
This commit is contained in:
@@ -0,0 +1,463 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"unified-dashboard/internal/common"
|
||||
mymiddleware "unified-dashboard/internal/middleware"
|
||||
)
|
||||
|
||||
var (
|
||||
sessionPaths = make(map[string]string)
|
||||
sessionStats = make(map[string]map[string]int)
|
||||
relaySessions = make(map[string]chan map[string]interface{})
|
||||
requestEvents = make(map[string]chan []byte)
|
||||
|
||||
tunnelProcess *exec.Cmd
|
||||
tunnelURL string
|
||||
tunnelLock sync.Mutex
|
||||
globalLock sync.Mutex
|
||||
)
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, data any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func main() {
|
||||
common.InitLogger("image-hoster")
|
||||
port := common.EnvOr("PORT", "5005")
|
||||
scriptName := os.Getenv("SCRIPT_NAME")
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(mymiddleware.RequestLogger)
|
||||
r.Use(middleware.Recoverer)
|
||||
if scriptName != "" {
|
||||
r.Use(common.PrefixMiddleware(scriptName))
|
||||
}
|
||||
|
||||
workDir, _ := os.Getwd()
|
||||
webDir := filepath.Join(workDir, "web", "image-hoster")
|
||||
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, filepath.Join(webDir, "index.html"))
|
||||
})
|
||||
r.Get("/radheradhe", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, filepath.Join(webDir, "admin.html"))
|
||||
})
|
||||
r.Get("/radheradhe/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, filepath.Join(webDir, "admin.html"))
|
||||
})
|
||||
|
||||
r.Post("/create_session", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
// Body might be empty
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
sessionID := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
|
||||
globalLock.Lock()
|
||||
if req.Mode == "relay" {
|
||||
relaySessions[sessionID] = make(chan map[string]interface{}, 100)
|
||||
}
|
||||
sessionStats[sessionID] = map[string]int{"requests": 0, "bytes": 0}
|
||||
globalLock.Unlock()
|
||||
|
||||
writeJSON(w, 200, map[string]any{"success": true, "session_id": sessionID})
|
||||
})
|
||||
|
||||
r.Post("/admin_login", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Post("/set_session_path", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
globalLock.Lock()
|
||||
if req.Path == "(Relay Mode)" {
|
||||
// Relay mode: serve files from browser via SSE, NOT from disk
|
||||
if _, exists := relaySessions[req.SessionID]; !exists {
|
||||
relaySessions[req.SessionID] = make(chan map[string]interface{}, 100)
|
||||
}
|
||||
// Remove from sessionPaths so the /files handler uses the relay path
|
||||
delete(sessionPaths, req.SessionID)
|
||||
if _, exists := sessionStats[req.SessionID]; !exists {
|
||||
sessionStats[req.SessionID] = map[string]int{"requests": 0, "bytes": 0}
|
||||
}
|
||||
globalLock.Unlock()
|
||||
writeJSON(w, 200, map[string]any{"success": true, "mode": "relay"})
|
||||
return
|
||||
}
|
||||
|
||||
// Server-side path mapping
|
||||
if req.Path == "" {
|
||||
globalLock.Unlock()
|
||||
writeJSON(w, 400, map[string]string{"error": "Path required"})
|
||||
return
|
||||
}
|
||||
sessionPaths[req.SessionID] = req.Path
|
||||
// If previously in relay mode, remove it
|
||||
delete(relaySessions, req.SessionID)
|
||||
if _, exists := sessionStats[req.SessionID]; !exists {
|
||||
sessionStats[req.SessionID] = map[string]int{"requests": 0, "bytes": 0}
|
||||
}
|
||||
globalLock.Unlock()
|
||||
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Post("/delete_session", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
globalLock.Lock()
|
||||
delete(sessionPaths, req.SessionID)
|
||||
delete(relaySessions, req.SessionID)
|
||||
delete(sessionStats, req.SessionID)
|
||||
globalLock.Unlock()
|
||||
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Get("/stream_events/{session_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
sid := chi.URLParam(r, "session_id")
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok { return }
|
||||
|
||||
globalLock.Lock()
|
||||
ch, exists := relaySessions[sid]
|
||||
globalLock.Unlock()
|
||||
|
||||
if !exists { return }
|
||||
|
||||
for msg := range ch {
|
||||
b, _ := json.Marshal(msg)
|
||||
fmt.Fprintf(w, "data: %s\n\n", b)
|
||||
flusher.Flush()
|
||||
}
|
||||
})
|
||||
|
||||
r.Post("/fulfill_request", func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.FormValue("req_id")
|
||||
globalLock.Lock()
|
||||
ch, exists := requestEvents[reqID]
|
||||
globalLock.Unlock()
|
||||
|
||||
if !exists {
|
||||
writeJSON(w, 404, map[string]string{"error": "Invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err == nil {
|
||||
data, _ := io.ReadAll(file)
|
||||
ch <- data
|
||||
file.Close()
|
||||
} else {
|
||||
ch <- nil
|
||||
}
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Get("/files/{session_id}/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
sid := chi.URLParam(r, "session_id")
|
||||
filename := chi.URLParam(r, "*")
|
||||
|
||||
globalLock.Lock()
|
||||
basePath, localExists := sessionPaths[sid]
|
||||
ch, relayExists := relaySessions[sid]
|
||||
stats := sessionStats[sid]
|
||||
globalLock.Unlock()
|
||||
|
||||
if stats != nil {
|
||||
stats["requests"]++
|
||||
}
|
||||
|
||||
if localExists {
|
||||
fullPath := filepath.Join(basePath, filename)
|
||||
stat, err := os.Stat(fullPath)
|
||||
if err == nil {
|
||||
if stats != nil {
|
||||
stats["bytes"] += int(stat.Size())
|
||||
}
|
||||
if stat.IsDir() {
|
||||
// Return beautiful HTML listing for directories instead of 404
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
|
||||
html := `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Hosted Files</title>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--bg-deep: #050505;
|
||||
--bg-surface: #101015;
|
||||
--primary: #7b2cbf;
|
||||
--secondary: #4cc9f0;
|
||||
--text-main: #ffffff;
|
||||
--text-muted: #a0a0a0;
|
||||
}
|
||||
body {
|
||||
font-family: 'Segoe UI', -apple-system, sans-serif;
|
||||
background: var(--bg-deep);
|
||||
color: var(--text-main);
|
||||
margin: 0;
|
||||
padding: 40px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
.container {
|
||||
width: 100%;
|
||||
max-width: 800px;
|
||||
background: var(--bg-surface);
|
||||
border-radius: 12px;
|
||||
padding: 30px;
|
||||
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
|
||||
border: 1px solid rgba(255,255,255,0.05);
|
||||
}
|
||||
h2 {
|
||||
margin-top: 0;
|
||||
color: var(--secondary);
|
||||
border-bottom: 2px solid rgba(255,255,255,0.1);
|
||||
padding-bottom: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.file-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.file-list li a {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
color: var(--text-main);
|
||||
text-decoration: none;
|
||||
padding: 12px 15px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255,255,255,0.02);
|
||||
transition: all 0.2s;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.file-list li a:hover {
|
||||
background: rgba(76, 201, 240, 0.1);
|
||||
border-color: rgba(76, 201, 240, 0.3);
|
||||
color: var(--secondary);
|
||||
transform: translateX(5px);
|
||||
}
|
||||
.icon {
|
||||
color: var(--primary);
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2><i class="fas fa-folder-open"></i> Hosted Files</h2>
|
||||
<ul class="file-list">`
|
||||
w.Write([]byte(html))
|
||||
|
||||
entries, _ := os.ReadDir(fullPath)
|
||||
if len(entries) == 0 {
|
||||
w.Write([]byte(`<div style="color:var(--text-muted); padding:20px; text-align:center;">This folder is empty.</div>`))
|
||||
} else {
|
||||
for _, e := range entries {
|
||||
icon := "fa-file"
|
||||
if e.IsDir() { icon = "fa-folder" }
|
||||
ext := strings.ToLower(filepath.Ext(e.Name()))
|
||||
if ext == ".jpg" || ext == ".png" || ext == ".gif" || ext == ".webp" { icon = "fa-image" }
|
||||
|
||||
link := fmt.Sprintf("%s/%s", strings.TrimRight(r.URL.Path, "/"), e.Name())
|
||||
w.Write([]byte(fmt.Sprintf(`<li><a href="%s"><i class="fas %s icon"></i> %s</a></li>`, link, icon, e.Name())))
|
||||
}
|
||||
}
|
||||
w.Write([]byte("</ul></div></body></html>"))
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, fullPath)
|
||||
return
|
||||
}
|
||||
} else if relayExists {
|
||||
reqID := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
resCh := make(chan []byte, 1)
|
||||
|
||||
globalLock.Lock()
|
||||
requestEvents[reqID] = resCh
|
||||
globalLock.Unlock()
|
||||
|
||||
ch <- map[string]interface{}{
|
||||
"type": "request_file",
|
||||
"req_id": reqID,
|
||||
"filename": filename,
|
||||
}
|
||||
|
||||
select {
|
||||
case data := <-resCh:
|
||||
globalLock.Lock()
|
||||
delete(requestEvents, reqID)
|
||||
globalLock.Unlock()
|
||||
if data != nil {
|
||||
if stats != nil {
|
||||
stats["bytes"] += len(data)
|
||||
}
|
||||
w.Write(data)
|
||||
return
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
globalLock.Lock()
|
||||
delete(requestEvents, reqID)
|
||||
globalLock.Unlock()
|
||||
}
|
||||
}
|
||||
http.Error(w, "Not found", 404)
|
||||
})
|
||||
|
||||
r.Get("/get_session_files/{session_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
sid := chi.URLParam(r, "session_id")
|
||||
|
||||
globalLock.Lock()
|
||||
_, relayExists := relaySessions[sid]
|
||||
basePath, localExists := sessionPaths[sid]
|
||||
globalLock.Unlock()
|
||||
|
||||
if relayExists {
|
||||
writeJSON(w, 200, map[string]any{"success": true, "mode": "relay", "path_set": true, "current_path": "(Hosted from Browser)"})
|
||||
return
|
||||
}
|
||||
|
||||
if !localExists {
|
||||
writeJSON(w, 200, map[string]any{"success": true, "files": []any{}, "path_set": false})
|
||||
return
|
||||
}
|
||||
|
||||
var filesList []map[string]any
|
||||
filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil || info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
relPath, err := filepath.Rel(basePath, path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
relPath = filepath.ToSlash(relPath)
|
||||
folder := filepath.Dir(relPath)
|
||||
if folder == "." {
|
||||
folder = "(Root)"
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
isCode := ext == ".json" || ext == ".html" || ext == ".htm" || ext == ".css" || ext == ".js"
|
||||
|
||||
filesList = append(filesList, map[string]any{
|
||||
"path": relPath,
|
||||
"folder": folder,
|
||||
"name": info.Name(),
|
||||
"url": fmt.Sprintf("/files/%s/%s", sid, relPath),
|
||||
"is_code": isCode,
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"success": true,
|
||||
"files": filesList,
|
||||
"path_set": true,
|
||||
"current_path": basePath,
|
||||
})
|
||||
})
|
||||
|
||||
r.Post("/browse_folder", func(w http.ResponseWriter, r *http.Request) {
|
||||
cmd := exec.Command("zenity", "--file-selection", "--directory", "--title=Select Image Folder")
|
||||
out, err := cmd.Output()
|
||||
path := strings.TrimSpace(string(out))
|
||||
|
||||
if err == nil && path != "" {
|
||||
writeJSON(w, 200, map[string]any{"success": true, "path": path})
|
||||
return
|
||||
}
|
||||
|
||||
pyCode := `import tkinter as tk; from tkinter import filedialog; root = tk.Tk(); root.withdraw(); root.attributes("-topmost", True); print(filedialog.askdirectory()); root.destroy()`
|
||||
cmd = exec.Command("python3", "-c", pyCode)
|
||||
out, err = cmd.Output()
|
||||
path = strings.TrimSpace(string(out))
|
||||
|
||||
if err == nil && path != "" {
|
||||
writeJSON(w, 200, map[string]any{"success": true, "path": path})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"success": false, "error": "No folder selected"})
|
||||
})
|
||||
|
||||
r.Post("/get_tunnel", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
if req.SessionID == "" {
|
||||
writeJSON(w, 400, map[string]string{"error": "No session ID"})
|
||||
return
|
||||
}
|
||||
|
||||
tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID)
|
||||
writeJSON(w, 200, map[string]any{"success": true, "url": tunnelURL})
|
||||
})
|
||||
|
||||
r.Post("/stop_tunnel", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Post("/regenerate_tunnel", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]bool{"success": true})
|
||||
})
|
||||
|
||||
r.Post("/get_tunnel_status", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID)
|
||||
writeJSON(w, 200, map[string]any{"active": true, "url": tunnelURL})
|
||||
})
|
||||
|
||||
slog.Info("starting image-hoster", "port", port, "pid", os.Getpid())
|
||||
if err := http.ListenAndServe(":"+port, r); err != nil {
|
||||
slog.Error("server failed", "error", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user