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 := ` Hosted Files

Hosted Files

")) 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) } }