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