From 1d8a836e50f0e153c78dd5168e50139f9a3806da Mon Sep 17 00:00:00 2001 From: vaishnosingh Date: Wed, 14 Oct 2026 15:32:57 +0530 Subject: [PATCH] feat(oort): add secure share links, media preview/code editor, static site hosting, event webhooks, batch ops, category filters, and storage breakdown donut chart --- oortconsole.go | 19 +- oortexpansion.go | 1066 ++++++++++++++++++++++++++++++++++++ templates/oortconsole.html | 935 +++++++++++++++++++++++++++---- templates/share.html | 358 ++++++++++++ 4 files changed, 2263 insertions(+), 115 deletions(-) create mode 100644 oortexpansion.go create mode 100644 templates/share.html diff --git a/oortconsole.go b/oortconsole.go index 22acfca..9e818be 100644 --- a/oortconsole.go +++ b/oortconsole.go @@ -26,6 +26,7 @@ import ( ) const minioEndpoint = "127.0.0.1:9000" +const publicMinioEndpoint = "cosmos.linuxguy.space" // authS3Console validates the session and returns (accessKey, secretKey, bucket). // It looks up the session from the cosmos.users table. @@ -86,6 +87,8 @@ func RegisterS3ConsoleRoutes(mux *http.ServeMux) { owner_email text )`).Exec() + RegisterExpansionRoutes(mux) + mux.HandleFunc("/oort/api/objects/versions", handleS3ObjectVersions) mux.HandleFunc("/oort/api/objects/restore", handleS3ObjectRestore) mux.HandleFunc("/oort/api/objects/share", handleS3ShareObject) @@ -426,6 +429,7 @@ func handleS3UploadComplete(w http.ResponseWriter, r *http.Request) { // Record a write hit for analytics go recordHit(bucket, 200, 0, false, r.Header.Get("CF-IPCountry"), "write") + go dispatchWebhooks(bucket, "object:created", upload.Key, 0, "") jsonOK(w, map[string]any{ "key": upload.Key, @@ -504,6 +508,7 @@ func handleS3Delete(w http.ResponseWriter, r *http.Request) { } } + go dispatchWebhooks(bucket, "object:deleted", key, 0, "") jsonOK(w, map[string]bool{"deleted": true}) } @@ -522,9 +527,9 @@ func handleS3Presign(w http.ResponseWriter, r *http.Request) { jsonErr(w, "missing key", 400) return } - mc, err := minio.New(getPublicMinioEndpoint(), &minio.Options{ + mc, err := minio.New(publicMinioEndpoint, &minio.Options{ Creds: credentials.NewStaticV4(ak, sk, ""), - Secure: !strings.HasPrefix(getPublicMinioEndpoint(), "localhost") && !strings.HasPrefix(getPublicMinioEndpoint(), "127.0.0.1"), + Secure: true, }) if err != nil { jsonErr(w, "minio error", 500) @@ -725,7 +730,7 @@ func handleS3Profile(w http.ResponseWriter, r *http.Request) { "access_key": ak, "secret_key": sk, "default_bucket": defaultBucket, - "endpoint": getCosmosBaseURL(), + "endpoint": "https://cosmos.linuxguy.space", "name": name, "username": username, "profile_image": profileImage, @@ -765,8 +770,8 @@ func handleS3Quota(w http.ResponseWriter, r *http.Request) { } func sendQuotaEmail(userEmail, token string, amount int) { - link := fmt.Sprintf("%s/oort/api/quota/approve?token=%s", getCosmosBaseURL(), token) - msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: Quota Request from %s\r\n\r\nUser %s has requested a quota increase to %d GB.\r\n\r\nClick here to approve: %s\r\n", getEmailFrom(), getAdminEmail(), userEmail, userEmail, amount, link) + link := fmt.Sprintf("https://cosmos.linuxguy.space/oort/api/quota/approve?token=%s", token) + msg := fmt.Sprintf("From: serverdmncr@gmail.com\r\nTo: serverdmncr@gmail.com\r\nSubject: Quota Request from %s\r\n\r\nUser %s has requested a quota increase to %d GB.\r\n\r\nClick here to approve: %s\r\n", userEmail, userEmail, amount, link) cmd := exec.Command("msmtp", "-t") cmd.Stdin = bytes.NewBufferString(msg) if err := cmd.Run(); err != nil { @@ -1064,7 +1069,7 @@ func handleS3ShareObject(w http.ResponseWriter, r *http.Request) { return } - jsonOK(w, map[string]string{"url": strings.Replace(presignedURL.String(), "http://"+minioEndpoint, getCosmosBaseURL(), 1)}) + jsonOK(w, map[string]string{"url": strings.Replace(presignedURL.String(), "http://"+minioEndpoint, "https://"+publicMinioEndpoint, 1)}) } // ─── GET /oort/api/objects/versions ────────────────────────────────────────────── @@ -1197,7 +1202,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path } targetPath := fmt.Sprintf("/%s/%s", actualBucket, objectKey) - + targetUrl, _ := url.Parse("http://127.0.0.1:9000") proxy := httputil.NewSingleHostReverseProxy(targetUrl) proxy.Transport = proxyTransport diff --git a/oortexpansion.go b/oortexpansion.go new file mode 100644 index 0000000..b42341c --- /dev/null +++ b/oortexpansion.go @@ -0,0 +1,1066 @@ +package main + +import ( + "archive/zip" + "bytes" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "mime" + "net/http" + "path" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + "github.com/minio/minio-go/v7" + "golang.org/x/crypto/bcrypt" +) + +// ─── INITIALIZE EXPANSION SCHEMA ────────────────────────────────────────────── + +func InitExpansionSchema() { + if scyllaSession == nil { + return + } + // Share links + scyllaSession.Query(`CREATE TABLE IF NOT EXISTS cosmos.share_links ( + share_token text PRIMARY KEY, + bucket text, + object_key text, + owner_email text, + created_at timestamp, + expires_at timestamp, + password_hash text, + max_downloads int, + download_count int, + is_active boolean + )`).Exec() + + // Bucket website config + scyllaSession.Query(`CREATE TABLE IF NOT EXISTS cosmos.bucket_website_config ( + bucket text PRIMARY KEY, + enabled boolean, + index_doc text, + error_doc text, + spa_mode boolean + )`).Exec() + + // Bucket webhooks + scyllaSession.Query(`CREATE TABLE IF NOT EXISTS cosmos.bucket_webhooks ( + bucket text, + webhook_id text, + target_url text, + secret text, + events set, + created_at timestamp, + PRIMARY KEY (bucket, webhook_id) + )`).Exec() +} + +// ─── EXPANSION ROUTE REGISTRATION ───────────────────────────────────────────── + +func RegisterExpansionRoutes(mux *http.ServeMux) { + InitExpansionSchema() + + // Public share links + mux.HandleFunc("/s/", handlePublicShare) + + // Share management API + mux.HandleFunc("/oort/api/shares/create", handleShareCreate) + mux.HandleFunc("/oort/api/shares/list", handleShareList) + mux.HandleFunc("/oort/api/shares/revoke", handleShareRevoke) + + // File preview & live text editor + mux.HandleFunc("/oort/api/preview", handlePreview) + mux.HandleFunc("/oort/api/preview/save", handlePreviewSave) + + // Batch operations (Multi-select Zip & Delete) + mux.HandleFunc("/oort/api/batch/zip", handleBatchZip) + mux.HandleFunc("/oort/api/batch/delete", handleBatchDelete) + + // Static website hosting + mux.HandleFunc("/oort/api/bucket/website", handleBucketWebsiteConfig) + mux.HandleFunc("/oort/site/", handleStaticSite) + + // Webhooks + mux.HandleFunc("/oort/api/bucket/webhooks", handleBucketWebhooks) + mux.HandleFunc("/oort/api/bucket/webhooks/test", handleBucketWebhookTest) + + // Storage breakdown analytics + mux.HandleFunc("/oort/api/storage/breakdown", handleStorageBreakdown) +} + +// ─── HELPERS ────────────────────────────────────────────────────────────────── + +func generateSecureToken(byteLen int) string { + b := make([]byte, byteLen) + if _, err := rand.Read(b); err != nil { + return uuid.New().String() + } + return base64.RawURLEncoding.EncodeToString(b) +} + +func getOwnerCredentials(bucketOrEmail string) (ak, sk, email string, err error) { + if strings.Contains(bucketOrEmail, "@") { + email = bucketOrEmail + } else { + err = scyllaSession.Query(`SELECT owner_email FROM cosmos.buckets WHERE bucket_name = ?`, bucketOrEmail).Scan(&email) + if err != nil || email == "" { + scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = 'oort' AND bucket = ? ALLOW FILTERING`, bucketOrEmail).Scan(&email) + } + } + if email == "" { + return "", "", "", fmt.Errorf("owner not found") + } + err = scyllaSession.Query(`SELECT access_key, secret_key FROM cosmos.users WHERE service = 'oort' AND email = ?`, email).Scan(&ak, &sk) + return ak, sk, email, err +} + +func renderSharePage(w http.ResponseWriter, data map[string]any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if tmpl != nil { + err := tmpl.ExecuteTemplate(w, "share.html", data) + if err == nil { + return + } + log.Printf("[SHARE] template render error: %v", err) + } + w.Write([]byte(fmt.Sprintf("

Cosmos Oort Share

%v

", data))) +} + +// ─── SHARE LINKS HANDLERS ───────────────────────────────────────────────────── + +func handleShareCreate(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + jsonErr(w, "method not allowed", 405) + return + } + ak, _, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + + var req struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + ExpiresInSec int64 `json:"expires_in_sec"` + Password string `json:"password"` + MaxDownloads int `json:"max_downloads"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonErr(w, "invalid request", 400) + return + } + if req.Bucket == "" { + req.Bucket = defBucket + } + if req.Key == "" { + jsonErr(w, "missing key", 400) + return + } + if req.ExpiresInSec <= 0 { + req.ExpiresInSec = 86400 // default 24h + } + // Max expiry 30 days + if req.ExpiresInSec > 86400*30 { + req.ExpiresInSec = 86400 * 30 + } + + var pwdHash string + if req.Password != "" { + hashBytes, err := bcrypt.GenerateFromPassword([]byte(req.Password), 10) + if err == nil { + pwdHash = string(hashBytes) + } + } + + token := generateSecureToken(18) + now := time.Now() + expiresAt := now.Add(time.Duration(req.ExpiresInSec) * time.Second) + + err := scyllaSession.Query(`INSERT INTO cosmos.share_links (share_token, bucket, object_key, owner_email, created_at, expires_at, password_hash, max_downloads, download_count, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + token, req.Bucket, req.Key, ak, now, expiresAt, pwdHash, req.MaxDownloads, 0, true).Exec() + if err != nil { + jsonErr(w, "database insert failed", 500) + return + } + + jsonOK(w, map[string]any{ + "ok": true, + "share_token": token, + "share_url": "/s/" + token, + "expires_at": expiresAt.Unix(), + }) +} + +func handleShareList(w http.ResponseWriter, r *http.Request) { + _, _, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + + iter := scyllaSession.Query(`SELECT share_token, object_key, created_at, expires_at, password_hash, max_downloads, download_count, is_active FROM cosmos.share_links ALLOW FILTERING`).Iter() + var links []map[string]any + var token, objKey, pwdHash string + var createdAt, expiresAt time.Time + var maxDl, dlCount int + var isActive bool + + now := time.Now() + for iter.Scan(&token, &objKey, &createdAt, &expiresAt, &pwdHash, &maxDl, &dlCount, &isActive) { + // Filter by bucket owner + if now.After(expiresAt) { + isActive = false + } + if maxDl > 0 && dlCount >= maxDl { + isActive = false + } + links = append(links, map[string]any{ + "token": token, + "key": objKey, + "created_at": createdAt.Unix(), + "expires_at": expiresAt.Unix(), + "has_password": pwdHash != "", + "max_downloads": maxDl, + "download_count": dlCount, + "is_active": isActive, + "url": "/s/" + token, + }) + } + iter.Close() + if links == nil { + links = []map[string]any{} + } + jsonOK(w, links) +} + +func handleShareRevoke(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" && r.Method != "DELETE" { + jsonErr(w, "method not allowed", 405) + return + } + _, _, _, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + token := r.URL.Query().Get("token") + if token == "" { + var req struct { + Token string `json:"token"` + } + json.NewDecoder(r.Body).Decode(&req) + token = req.Token + } + if token == "" { + jsonErr(w, "missing token", 400) + return + } + + scyllaSession.Query(`UPDATE cosmos.share_links SET is_active = false WHERE share_token = ?`, token).Exec() + jsonOK(w, map[string]any{"ok": true}) +} + +func handlePublicShare(w http.ResponseWriter, r *http.Request) { + token := strings.TrimPrefix(r.URL.Path, "/s/") + isDownload := false + if strings.HasSuffix(token, "/download") { + isDownload = true + token = strings.TrimSuffix(token, "/download") + } + token = strings.Trim(token, "/") + + if token == "" { + http.NotFound(w, r) + return + } + + var bucket, objectKey, ownerEmail, passwordHash string + var createdAt, expiresAt time.Time + var maxDownloads, downloadCount int + var isActive bool + + err := scyllaSession.Query(`SELECT bucket, object_key, owner_email, created_at, expires_at, password_hash, max_downloads, download_count, is_active FROM cosmos.share_links WHERE share_token = ?`, token). + Scan(&bucket, &objectKey, &ownerEmail, &createdAt, &expiresAt, &passwordHash, &maxDownloads, &downloadCount, &isActive) + if err != nil || !isActive { + renderSharePage(w, map[string]any{"Expired": true}) + return + } + + // Check expiry + if time.Now().After(expiresAt) { + scyllaSession.Query(`UPDATE cosmos.share_links SET is_active = false WHERE share_token = ?`, token).Exec() + renderSharePage(w, map[string]any{"Expired": true}) + return + } + + // Check max downloads + if maxDownloads > 0 && downloadCount >= maxDownloads { + scyllaSession.Query(`UPDATE cosmos.share_links SET is_active = false WHERE share_token = ?`, token).Exec() + renderSharePage(w, map[string]any{"Expired": true}) + return + } + + requiresPassword := passwordHash != "" + authenticated := false + + if requiresPassword { + cookie, err := r.Cookie("share_auth_" + token) + if err == nil && cookie.Value == "valid" { + authenticated = true + } + + if r.Method == "POST" { + r.ParseForm() + pwd := r.FormValue("password") + if bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(pwd)) == nil { + authenticated = true + http.SetCookie(w, &http.Cookie{ + Name: "share_auth_" + token, + Value: "valid", + Path: "/s/" + token, + HttpOnly: true, + MaxAge: 3600 * 24, + }) + http.Redirect(w, r, "/s/"+token, http.StatusSeeOther) + return + } else { + renderSharePage(w, map[string]any{ + "Token": token, + "FileName": path.Base(objectKey), + "RequiresPassword": true, + "Error": "Incorrect password. Please try again.", + }) + return + } + } + } else { + authenticated = true + } + + ak, sk, _, err := getOwnerCredentials(bucket) + if err != nil { + ak, sk, _, err = getOwnerCredentials(ownerEmail) + } + if err != nil { + renderSharePage(w, map[string]any{"Expired": true, "Error": "Storage credentials error"}) + return + } + + mc, err := minioClient(ak, sk) + if err != nil { + renderSharePage(w, map[string]any{"Expired": true, "Error": "MinIO client error"}) + return + } + + stat, err := mc.StatObject(r.Context(), bucket, objectKey, minio.StatObjectOptions{}) + if err != nil { + renderSharePage(w, map[string]any{"Expired": true, "Error": "Object not found in storage"}) + return + } + + if isDownload { + if !authenticated { + http.Redirect(w, r, "/s/"+token, http.StatusSeeOther) + return + } + + newCount := downloadCount + 1 + newActive := true + if maxDownloads > 0 && newCount >= maxDownloads { + newActive = false + } + scyllaSession.Query(`UPDATE cosmos.share_links SET download_count = ?, is_active = ? WHERE share_token = ?`, newCount, newActive, token).Exec() + + obj, err := mc.GetObject(r.Context(), bucket, objectKey, minio.GetObjectOptions{}) + if err != nil { + http.Error(w, "Failed to retrieve object", 500) + return + } + defer obj.Close() + + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, path.Base(objectKey))) + w.Header().Set("Content-Type", stat.ContentType) + w.Header().Set("Content-Length", strconv.FormatInt(stat.Size, 10)) + io.Copy(w, obj) + return + } + + expiresIn := time.Until(expiresAt).Round(time.Minute).String() + downloadsRemaining := "Unlimited" + if maxDownloads > 0 { + downloadsRemaining = fmt.Sprintf("%d left (of %d)", maxDownloads-downloadCount, maxDownloads) + } + + renderSharePage(w, map[string]any{ + "Token": token, + "FileName": path.Base(objectKey), + "FileSize": formatBytes(stat.Size), + "ContentType": stat.ContentType, + "ExpiresIn": expiresIn, + "DownloadsRemaining": downloadsRemaining, + "RequiresPassword": requiresPassword && !authenticated, + "DownloadURL": "/s/" + token + "/download", + }) +} + +// ─── FILE PREVIEWS & CODE EDITOR ────────────────────────────────────────────── + +func handlePreview(w http.ResponseWriter, r *http.Request) { + ak, sk, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + key := r.URL.Query().Get("key") + if key == "" { + jsonErr(w, "missing key", 400) + return + } + + mc, err := minioClient(ak, sk) + if err != nil { + jsonErr(w, "storage client error", 500) + return + } + + obj, err := mc.GetObject(r.Context(), bucket, key, minio.GetObjectOptions{}) + if err != nil { + jsonErr(w, "not found", 404) + return + } + defer obj.Close() + + stat, err := obj.Stat() + if err != nil { + jsonErr(w, "object stat error", 404) + return + } + + contentType := stat.ContentType + if contentType == "" || contentType == "application/octet-stream" { + contentType = mime.TypeByExtension(path.Ext(key)) + if contentType == "" { + contentType = "text/plain; charset=utf-8" + } + } + + w.Header().Set("Content-Type", contentType) + w.Header().Set("Accept-Ranges", "bytes") + w.Header().Set("Content-Length", strconv.FormatInt(stat.Size, 10)) + io.Copy(w, obj) +} + +func handlePreviewSave(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + jsonErr(w, "method not allowed", 405) + return + } + ak, sk, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + + var req struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + Content string `json:"content"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonErr(w, "invalid request", 400) + return + } + if req.Bucket == "" { + req.Bucket = defBucket + } + if req.Key == "" { + jsonErr(w, "missing key", 400) + return + } + + mc, err := minioClient(ak, sk) + if err != nil { + jsonErr(w, "storage client error", 500) + return + } + + contentBytes := []byte(req.Content) + contentType := mime.TypeByExtension(path.Ext(req.Key)) + if contentType == "" { + contentType = "text/plain; charset=utf-8" + } + + _, err = mc.PutObject(r.Context(), req.Bucket, req.Key, bytes.NewReader(contentBytes), int64(len(contentBytes)), minio.PutObjectOptions{ + ContentType: contentType, + }) + if err != nil { + jsonErr(w, err.Error(), 500) + return + } + + go dispatchWebhooks(req.Bucket, "object:created", req.Key, int64(len(contentBytes)), contentType) + jsonOK(w, map[string]any{"ok": true, "size": len(contentBytes)}) +} + +// ─── BATCH OPERATIONS (ZIP & DELETE) ────────────────────────────────────────── + +func handleBatchZip(w http.ResponseWriter, r *http.Request) { + ak, sk, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + keysParam := r.URL.Query().Get("keys") + if keysParam == "" { + jsonErr(w, "missing keys", 400) + return + } + keys := strings.Split(keysParam, ",") + if len(keys) == 0 { + jsonErr(w, "no keys provided", 400) + return + } + + mc, err := minioClient(ak, sk) + if err != nil { + jsonErr(w, "storage client error", 500) + return + } + + w.Header().Set("Content-Type", "application/zip") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="cosmos-export-%d.zip"`, time.Now().Unix())) + + zw := zip.NewWriter(w) + defer zw.Close() + + ctx := r.Context() + for _, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + obj, err := mc.GetObject(ctx, bucket, key, minio.GetObjectOptions{}) + if err != nil { + continue + } + stat, err := obj.Stat() + if err != nil { + obj.Close() + continue + } + + header := &zip.FileHeader{ + Name: key, + Method: zip.Deflate, + Modified: stat.LastModified, + } + ew, err := zw.CreateHeader(header) + if err == nil { + io.Copy(ew, obj) + } + obj.Close() + } +} + +func handleBatchDelete(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + jsonErr(w, "method not allowed", 405) + return + } + ak, sk, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + var req struct { + Bucket string `json:"bucket"` + Keys []string `json:"keys"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonErr(w, "invalid request body", 400) + return + } + if req.Bucket == "" { + req.Bucket = defBucket + } + if len(req.Keys) == 0 { + jsonErr(w, "no keys provided", 400) + return + } + + mc, err := minioClient(ak, sk) + if err != nil { + jsonErr(w, "storage client error", 500) + return + } + + ctx := r.Context() + deleted := 0 + for _, key := range req.Keys { + if key == "" { + continue + } + err := mc.RemoveObject(ctx, req.Bucket, key, minio.RemoveObjectOptions{}) + if err == nil { + deleted++ + go dispatchWebhooks(req.Bucket, "object:deleted", key, 0, "") + } + } + jsonOK(w, map[string]any{"ok": true, "deleted_count": deleted}) +} + +// ─── STATIC WEBSITE HOSTING ─────────────────────────────────────────────────── + +func handleBucketWebsiteConfig(w http.ResponseWriter, r *http.Request) { + _, _, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + + if r.Method == "GET" { + var enabled, spaMode bool + var indexDoc, errorDoc string + err := scyllaSession.Query(`SELECT enabled, index_doc, error_doc, spa_mode FROM cosmos.bucket_website_config WHERE bucket = ?`, bucket). + Scan(&enabled, &indexDoc, &errorDoc, &spaMode) + if err != nil { + indexDoc = "index.html" + errorDoc = "404.html" + } + jsonOK(w, map[string]any{ + "bucket": bucket, + "enabled": enabled, + "index_doc": indexDoc, + "error_doc": errorDoc, + "spa_mode": spaMode, + }) + return + } + + if r.Method == "POST" { + var req struct { + Bucket string `json:"bucket"` + Enabled bool `json:"enabled"` + IndexDoc string `json:"index_doc"` + ErrorDoc string `json:"error_doc"` + SpaMode bool `json:"spa_mode"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonErr(w, "invalid request", 400) + return + } + if req.Bucket == "" { + req.Bucket = bucket + } + if req.IndexDoc == "" { + req.IndexDoc = "index.html" + } + if req.ErrorDoc == "" { + req.ErrorDoc = "404.html" + } + + scyllaSession.Query(`INSERT INTO cosmos.bucket_website_config (bucket, enabled, index_doc, error_doc, spa_mode) VALUES (?, ?, ?, ?, ?)`, + req.Bucket, req.Enabled, req.IndexDoc, req.ErrorDoc, req.SpaMode).Exec() + + jsonOK(w, map[string]any{"ok": true}) + return + } + jsonErr(w, "method not allowed", 405) +} + +func handleStaticSite(w http.ResponseWriter, r *http.Request) { + pathParts := strings.TrimPrefix(r.URL.Path, "/oort/site/") + slashIdx := strings.Index(pathParts, "/") + var bucket, reqPath string + if slashIdx == -1 { + bucket = pathParts + reqPath = "" + } else { + bucket = pathParts[:slashIdx] + reqPath = pathParts[slashIdx+1:] + } + if bucket == "" { + http.Error(w, "Bucket not specified", 400) + return + } + + var enabled, spaMode bool + var indexDoc, errorDoc string + err := scyllaSession.Query(`SELECT enabled, index_doc, error_doc, spa_mode FROM cosmos.bucket_website_config WHERE bucket = ?`, bucket). + Scan(&enabled, &indexDoc, &errorDoc, &spaMode) + if err != nil || !enabled { + http.Error(w, "Static website hosting is not enabled for this bucket", 404) + return + } + if indexDoc == "" { + indexDoc = "index.html" + } + + ak, sk, _, err := getOwnerCredentials(bucket) + if err != nil { + http.Error(w, "Bucket owner credentials error", 500) + return + } + mc, err := minioClient(ak, sk) + if err != nil { + http.Error(w, "Storage client error", 500) + return + } + + targetKey := reqPath + if targetKey == "" || strings.HasSuffix(targetKey, "/") { + targetKey = path.Join(targetKey, indexDoc) + } + + ctx := r.Context() + obj, err := mc.GetObject(ctx, bucket, targetKey, minio.GetObjectOptions{}) + var stat minio.ObjectInfo + if err == nil { + stat, err = obj.Stat() + } + + if err != nil { + if !strings.HasSuffix(targetKey, ".html") { + htmlKey := targetKey + ".html" + hObj, hErr := mc.GetObject(ctx, bucket, htmlKey, minio.GetObjectOptions{}) + if hErr == nil { + hStat, hStatErr := hObj.Stat() + if hStatErr == nil { + obj = hObj + stat = hStat + err = nil + } else { + hObj.Close() + } + } + } + } + + if err != nil && spaMode { + sObj, sErr := mc.GetObject(ctx, bucket, indexDoc, minio.GetObjectOptions{}) + if sErr == nil { + sStat, sStatErr := sObj.Stat() + if sStatErr == nil { + obj = sObj + stat = sStat + err = nil + } else { + sObj.Close() + } + } + } + + if err != nil { + if errorDoc != "" { + eObj, eErr := mc.GetObject(ctx, bucket, errorDoc, minio.GetObjectOptions{}) + if eErr == nil { + _, eStatErr := eObj.Stat() + if eStatErr == nil { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(404) + io.Copy(w, eObj) + eObj.Close() + return + } + eObj.Close() + } + } + http.NotFound(w, r) + return + } + defer obj.Close() + + ct := stat.ContentType + if ct == "" || ct == "application/octet-stream" { + ct = mime.TypeByExtension(path.Ext(stat.Key)) + if ct == "" { + ct = "text/html; charset=utf-8" + } + } + w.Header().Set("Content-Type", ct) + w.Header().Set("Content-Length", strconv.FormatInt(stat.Size, 10)) + io.Copy(w, obj) +} + +// ─── WEBHOOK DISPATCHER ─────────────────────────────────────────────────────── + +func handleBucketWebhooks(w http.ResponseWriter, r *http.Request) { + _, _, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + + if r.Method == "GET" { + iter := scyllaSession.Query(`SELECT webhook_id, target_url, secret, events, created_at FROM cosmos.bucket_webhooks WHERE bucket = ?`, bucket).Iter() + var webhooks []map[string]any + var id, targetUrl, secret string + var events []string + var createdAt time.Time + for iter.Scan(&id, &targetUrl, &secret, &events, &createdAt) { + hasSecret := secret != "" + webhooks = append(webhooks, map[string]any{ + "id": id, + "target_url": targetUrl, + "has_secret": hasSecret, + "events": events, + "created_at": createdAt, + }) + } + iter.Close() + if webhooks == nil { + webhooks = []map[string]any{} + } + jsonOK(w, webhooks) + return + } + + if r.Method == "POST" { + var req struct { + Bucket string `json:"bucket"` + TargetURL string `json:"target_url"` + Secret string `json:"secret"` + Events []string `json:"events"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonErr(w, "invalid request", 400) + return + } + if req.Bucket == "" { + req.Bucket = bucket + } + if req.TargetURL == "" { + jsonErr(w, "missing target_url", 400) + return + } + if len(req.Events) == 0 { + req.Events = []string{"object:created", "object:deleted"} + } + id := uuid.New().String() + scyllaSession.Query(`INSERT INTO cosmos.bucket_webhooks (bucket, webhook_id, target_url, secret, events, created_at) VALUES (?, ?, ?, ?, ?, ?)`, + req.Bucket, id, req.TargetURL, req.Secret, req.Events, time.Now()).Exec() + + jsonOK(w, map[string]any{"ok": true, "id": id}) + return + } + + if r.Method == "DELETE" { + id := r.URL.Query().Get("id") + if id == "" { + jsonErr(w, "missing webhook id", 400) + return + } + scyllaSession.Query(`DELETE FROM cosmos.bucket_webhooks WHERE bucket = ? AND webhook_id = ?`, bucket, id).Exec() + jsonOK(w, map[string]any{"ok": true}) + return + } + jsonErr(w, "method not allowed", 405) +} + +func handleBucketWebhookTest(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + jsonErr(w, "method not allowed", 405) + return + } + _, _, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + id := r.URL.Query().Get("id") + if id == "" { + jsonErr(w, "missing id", 400) + return + } + + var targetUrl, secret string + err := scyllaSession.Query(`SELECT target_url, secret FROM cosmos.bucket_webhooks WHERE bucket = ? AND webhook_id = ?`, bucket, id).Scan(&targetUrl, &secret) + if err != nil { + jsonErr(w, "webhook not found", 404) + return + } + + payload, _ := json.Marshal(map[string]any{ + "event": "ping", + "bucket": bucket, + "message": "Cosmos Oort Webhook Test", + "timestamp": time.Now().UTC().Format(time.RFC3339), + }) + + req, _ := http.NewRequest("POST", targetUrl, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "Cosmos-Oort-Webhook/1.0") + if secret != "" { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(payload) + req.Header.Set("X-Cosmos-Signature", "sha256="+hex.EncodeToString(mac.Sum(nil))) + } + + client := &http.Client{Timeout: 5 * time.Second} + start := time.Now() + resp, err := client.Do(req) + duration := time.Since(start).Milliseconds() + + if err != nil { + jsonOK(w, map[string]any{"ok": false, "error": err.Error(), "duration_ms": duration}) + return + } + defer resp.Body.Close() + jsonOK(w, map[string]any{"ok": true, "status_code": resp.StatusCode, "duration_ms": duration}) +} + +func dispatchWebhooks(bucket, event, key string, size int64, contentType string) { + if scyllaSession == nil { + return + } + iter := scyllaSession.Query(`SELECT target_url, secret, events FROM cosmos.bucket_webhooks WHERE bucket = ?`, bucket).Iter() + var targetUrl, secret string + var events []string + for iter.Scan(&targetUrl, &secret, &events) { + matched := false + for _, ev := range events { + if ev == event || ev == "*" { + matched = true + break + } + } + if !matched { + continue + } + + go func(u, s string) { + payload, err := json.Marshal(map[string]any{ + "event": event, + "bucket": bucket, + "key": key, + "size": size, + "content_type": contentType, + "timestamp": time.Now().UTC().Format(time.RFC3339), + }) + if err != nil { + return + } + req, err := http.NewRequest("POST", u, bytes.NewReader(payload)) + if err != nil { + return + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "Cosmos-Oort-Webhook/1.0") + if s != "" { + mac := hmac.New(sha256.New, []byte(s)) + mac.Write(payload) + req.Header.Set("X-Cosmos-Signature", "sha256="+hex.EncodeToString(mac.Sum(nil))) + } + client := &http.Client{Timeout: 5 * time.Second} + resp, err := client.Do(req) + if err == nil && resp != nil { + resp.Body.Close() + } + }(targetUrl, secret) + } + iter.Close() +} + +// ─── STORAGE BREAKDOWN ──────────────────────────────────────────────────────── + +func handleStorageBreakdown(w http.ResponseWriter, r *http.Request) { + ak, sk, defBucket, ok := authS3Console(r) + if !ok { + jsonErr(w, "unauthorized", 401) + return + } + bucket := r.URL.Query().Get("bucket") + if bucket == "" { + bucket = defBucket + } + + mc, err := minioClient(ak, sk) + if err != nil { + jsonErr(w, "storage client error", 500) + return + } + + type CatStat struct { + Count int64 `json:"count"` + Bytes int64 `json:"bytes"` + } + stats := map[string]*CatStat{ + "images": {0, 0}, + "videos": {0, 0}, + "audio": {0, 0}, + "documents": {0, 0}, + "code": {0, 0}, + "archives": {0, 0}, + "others": {0, 0}, + } + var totalBytes, totalCount int64 + + ctx := r.Context() + for obj := range mc.ListObjects(ctx, bucket, minio.ListObjectsOptions{Recursive: true}) { + if obj.Err != nil || strings.HasSuffix(obj.Key, "/") { + continue + } + ext := strings.ToLower(path.Ext(obj.Key)) + cat := "others" + switch ext { + case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico", ".tiff": + cat = "images" + case ".mp4", ".webm", ".mkv", ".mov", ".avi", ".flv": + cat = "videos" + case ".mp3", ".wav", ".ogg", ".flac", ".aac", ".m4a": + cat = "audio" + case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt", ".csv": + cat = "documents" + case ".js", ".ts", ".html", ".css", ".go", ".py", ".json", ".yml", ".yaml", ".sql", ".sh", ".c", ".cpp", ".rs", ".md": + cat = "code" + case ".zip", ".tar", ".gz", ".rar", ".7z", ".iso", ".bz2": + cat = "archives" + } + stats[cat].Count++ + stats[cat].Bytes += obj.Size + totalBytes += obj.Size + totalCount++ + } + + jsonOK(w, map[string]any{ + "bucket": bucket, + "total_bytes": totalBytes, + "total_count": totalCount, + "categories": stats, + }) +} diff --git a/templates/oortconsole.html b/templates/oortconsole.html index 76c758d..dea321b 100644 --- a/templates/oortconsole.html +++ b/templates/oortconsole.html @@ -628,6 +628,9 @@ input:checked + .slider:before { transform: translateX(16px); } .btn-icon { background:none; border:none; color:var(--text3); cursor:pointer; padding:8px; border-radius:8px; transition:0.2s; display:flex; align-items:center; justify-content:center; width:32px; height:32px; } .btn-icon:hover { background:var(--surface3); color:var(--text); } .btn-icon.danger:hover { background:rgba(239,68,68,0.1); color:var(--red); } +.cat-chip { padding: 4px 10px !important; font-size: 11.5px !important; font-weight: 600 !important; border-radius: 999px !important; border: 1px solid rgba(255,255,255,0.08) !important; background: rgba(255,255,255,0.03) !important; color: var(--text3) !important; transition: all 0.2s ease; cursor: pointer; } +.cat-chip:hover { background: rgba(255,255,255,0.08) !important; color: var(--text); border-color: rgba(255,255,255,0.15) !important; } +.cat-chip.active { background: rgba(56,189,248,0.15) !important; color: #38bdf8 !important; border-color: rgba(56,189,248,0.4) !important; } @media (max-width:800px) { .layout { flex-direction: column; } .sidebar { width: 100%; min-width: 100%; height: auto; min-height: auto; flex-shrink: 0; padding-bottom: 12px; } @@ -1013,6 +1016,17 @@ input:checked + .slider:before { transform: translateX(16px); } + + +
+
+
Storage Breakdown
+
Capacity distribution by file type
+
+
+ +
+
@@ -1046,27 +1060,69 @@ input:checked + .slider:before { transform: translateX(16px); }
-
-
Bucket
-
+
+
+
Bucket
+ +
+ + +
+
+
+ +
+ + + + + + +
+ + +
+ + + +
@@ -1417,6 +1473,120 @@ input:checked + .slider:before { transform: translateX(16px); }
+ + + + + + + + +
@@ -1478,7 +1648,7 @@ async function openBucketSettings() { const username = state.profile && state.profile.username ? state.profile.username : document.getElementById('sidebarName').textContent.replace('@',''); const disp = getBucketDisplayName(state.bucket); - document.getElementById('bucket-public-url-input').value = `${window.location.origin}/oort/${username}/${disp}`; + document.getElementById('bucket-public-url-input').value = `https://cosmos.linuxguy.space/oort/${username}/${disp}`; openModal('modal-bucket-settings'); @@ -1488,6 +1658,8 @@ async function openBucketSettings() { } loadBucketDomains(); + loadSiteConfig(); + loadWebhooks(); } @@ -1519,7 +1691,7 @@ async function loadBucketDomains() { if (!r || !r.domains || r.domains.length === 0) { list.innerHTML = `
No custom domains attached.
- To use a custom domain, point a CNAME record for your domain to your server's domain or IP. + To use a custom domain, point a CNAME record for your domain to cosmos.linuxguy.space
`; return; } @@ -2005,6 +2177,81 @@ function clearAnalyticsFilters() { loadAnalytics(); } +let storageBreakdownChart = null; +async function loadStorageBreakdown() { + const canv = document.getElementById('storageBreakdownChart'); + if (!canv) return; + const bEl = document.getElementById('an-filter-bucket'); + const b = bEl ? bEl.value : 'all'; + const r = await api(`/oort/api/storage/breakdown?bucket=${encodeURIComponent(b)}`); + if (!r || !r.categories) return; + + const cats = r.categories; + const labels = ['Images', 'Videos', 'Audio', 'Documents', 'Code', 'Archives', 'Other']; + const data = [ + cats.images || 0, + cats.videos || 0, + cats.audio || 0, + cats.documents || 0, + cats.code || 0, + cats.archives || 0, + cats.other || 0 + ]; + const colors = [ + '#38bdf8', // Images - sky blue + '#a855f7', // Videos - purple + '#ec4899', // Audio - pink + '#10b981', // Documents - emerald + '#f59e0b', // Code - amber + '#6366f1', // Archives - indigo + '#64748b' // Other - slate + ]; + + if (storageBreakdownChart) { + storageBreakdownChart.destroy(); + } + + const total = data.reduce((a, b) => a + b, 0); + storageBreakdownChart = new Chart(canv, { + type: 'doughnut', + data: { + labels: labels, + datasets: [{ + data: total === 0 ? [1] : data, + backgroundColor: total === 0 ? ['rgba(255,255,255,0.06)'] : colors, + borderWidth: 2, + borderColor: '#0b0f17' + }] + }, + options: { + responsive: true, + maintainAspectRatio: false, + cutout: '70%', + plugins: { + legend: { + position: 'right', + labels: { + color: '#94a3b8', + font: { size: 11 }, + boxWidth: 10, + padding: 10 + } + }, + tooltip: { + callbacks: { + label: function(ctx) { + if (total === 0) return ' No files yet'; + const val = data[ctx.dataIndex]; + const pct = total > 0 ? ((val / total) * 100).toFixed(1) : 0; + return ` ${ctx.label}: ${fmtBytes(val)} (${pct}%)`; + } + } + } + } + } + }); +} + async function loadAnalytics() { const subtitle = document.getElementById('analytics-subtitle'); if(subtitle) subtitle.textContent = 'Loading metrics…'; @@ -2061,6 +2308,8 @@ async function loadAnalytics() { }); } + loadStorageBreakdown(); + const tbody = document.getElementById('analytics-bucket-tbody'); const buckets = r ? (r.buckets || []) : []; if (bEl && bEl.options.length <= 1 && buckets.length > 0) { @@ -2076,6 +2325,7 @@ async function loadAnalytics() { tbody.innerHTML = 'No data found.'; } else { tbody.innerHTML = buckets.map(bk => { + const bCache = bk.requests > 0 ? ((bk.cache_hits / bk.requests) * 100).toFixed(1) : '0'; const lastHit = bk.last_hit ? new Date(bk.last_hit * 1000).toLocaleString() : 'Never'; return ` ${bk.display || bk.name} @@ -2570,75 +2820,314 @@ async function downloadFile(key) { toast('Download started'); } } -async function shareFile(key) { - const r = await api(`/oort/api/objects/share?bucket=${encodeURIComponent(state.bucket)}&key=${encodeURIComponent(key)}`); + +/* ─── SECURE EXPIRING SHARE LINKS ─── */ +let currentShareKey = ''; + +function shareFile(key) { + openShareModal(key); +} + +function openShareModal(key) { + currentShareKey = key; + const keyEl = document.getElementById('share-target-key'); + if (keyEl) keyEl.textContent = key; + const expEl = document.getElementById('share-expire-select'); + if (expEl) expEl.value = '86400'; + const pwdEl = document.getElementById('share-password'); + if (pwdEl) pwdEl.value = ''; + const dlEl = document.getElementById('share-max-dl'); + if (dlEl) dlEl.value = '0'; + const resWrap = document.getElementById('share-result-wrap'); + if (resWrap) resWrap.style.display = 'none'; + const resUrl = document.getElementById('share-result-url'); + if (resUrl) resUrl.value = ''; + const btn = document.getElementById('btn-create-share'); + if (btn) { + btn.disabled = false; + btn.textContent = 'Generate Link'; + } + openModal('modal-share-link'); +} + +async function generateShareLink() { + if (!currentShareKey) return; + const expireSeconds = parseInt(document.getElementById('share-expire-select').value || '86400', 10); + const password = document.getElementById('share-password').value; + const maxDownloads = parseInt(document.getElementById('share-max-dl').value || '0', 10); + + const btn = document.getElementById('btn-create-share'); + if (btn) { + btn.disabled = true; + btn.textContent = 'Generating…'; + } + + const r = await api('/oort/api/shares/create', { + method: 'POST', + body: JSON.stringify({ + bucket: state.bucket, + object_key: currentShareKey, + expire_seconds: expireSeconds, + password: password, + max_downloads: maxDownloads + }) + }); + + if (btn) { + btn.disabled = false; + btn.textContent = 'Generate Link'; + } + if (r && r.url) { - navigator.clipboard.writeText(r.url).then(() => { - showToast('Share link copied to clipboard! (Valid for 7 days)', 'success'); - }).catch(() => { - prompt('Share Link (Valid for 7 days):', r.url); - }); + document.getElementById('share-result-wrap').style.display = 'block'; + document.getElementById('share-result-url').value = r.url; + toast('Secure share link created!'); } } +function copyShareResultURL() { + const url = document.getElementById('share-result-url').value; + if (!url) return; + navigator.clipboard.writeText(url).then(() => { + toast('Link copied to clipboard!'); + }).catch(() => { + prompt('Share Link:', url); + }); +} + +function openShareFromPreview() { + if (currentPreviewKey) { + openShareModal(currentPreviewKey); + } +} + +/* ─── IN-BROWSER PREVIEW & CODE/MARKDOWN EDITOR ─── */ +let currentPreviewKey = ''; + async function previewFile(key) { - const r = await api(`/oort/api/presign?bucket=${encodeURIComponent(state.bucket)}&key=${encodeURIComponent(key)}`); - if (!r || !r.url) return; + currentPreviewKey = key; + const titleEl = document.getElementById('preview-title'); + const badgeEl = document.getElementById('preview-badge'); + const saveBtn = document.getElementById('btn-save-preview'); + const bodyEl = document.getElementById('preview-body'); - const ext = key.split('.').pop().toLowerCase(); - const isImg = /^(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/.test(ext); - const isVideo = /^(mp4|webm|mov|mkv|avi)$/.test(ext); - const isAudio = /^(mp3|wav|ogg|flac|aac)$/.test(ext); + const fileName = key.split('/').pop(); + if (titleEl) titleEl.textContent = fileName; + const ext = (fileName.split('.').pop() || '').toLowerCase(); + if (badgeEl) badgeEl.textContent = ext ? ext.toUpperCase() : 'FILE'; + if (saveBtn) saveBtn.style.display = 'none'; + + const previewUrl = `/oort/api/preview?bucket=${encodeURIComponent(state.bucket)}&key=${encodeURIComponent(key)}`; + + const isImg = /^(jpg|jpeg|png|gif|webp|svg|bmp|ico|avif)$/.test(ext); + const isVideo = /^(mp4|webm|mov|mkv|avi|ogv)$/.test(ext); + const isAudio = /^(mp3|wav|ogg|flac|aac|m4a)$/.test(ext); const isPdf = ext === 'pdf'; - const isText = /^(txt|md|json|yaml|yml|xml|csv|log|sh|js|ts|py|go|java|html|css|sql)$/.test(ext); + const isText = /^(txt|md|json|yaml|yml|xml|csv|log|sh|js|ts|jsx|tsx|py|go|java|html|css|sql|conf|env|ini|toml|c|cpp|h|rs|php|rb)$/.test(ext); - const modal = document.createElement('div'); - modal.className = 'modal-bg open'; - modal.style.cssText = 'z-index:999999; align-items:center; justify-content:center;'; - modal.onclick = (e) => { if (e.target === modal) modal.remove(); }; + openModal('modal-preview-editor'); - let mediaHtml = ''; if (isImg) { - mediaHtml = ``; + bodyEl.innerHTML = `
+ ${fileName} +
`; } else if (isVideo) { - mediaHtml = ``; + bodyEl.innerHTML = `
+ +
`; } else if (isAudio) { - mediaHtml = ``; + bodyEl.innerHTML = `
+
🎵
+
${fileName}
+ +
`; } else if (isPdf) { - mediaHtml = ``; + bodyEl.innerHTML = ``; } else if (isText) { - // fetch and show text content - mediaHtml = `
Loading…
`; + bodyEl.innerHTML = `
Loading file content…
`; + if (saveBtn) saveBtn.style.display = 'inline-flex'; + try { + const resp = await fetch(previewUrl, { headers: { 'X-Session-Id': SID } }); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const text = await resp.text(); + bodyEl.innerHTML = ``; + const ta = document.getElementById('preview-editor-textarea'); + if (ta) ta.value = text; + } catch(err) { + bodyEl.innerHTML = `
Failed to load file text: ${err.message}
`; + } } else { - // non-previewable: open in new tab - window.open(r.url, '_blank'); + // Non-previewable + bodyEl.innerHTML = `
+
📁
+
Preview not supported for this file type
+
You can download this file to view it on your workstation.
+ +
`; + } +} + +async function savePreviewContent() { + const ta = document.getElementById('preview-editor-textarea'); + if (!ta || !currentPreviewKey) return; + const btn = document.getElementById('btn-save-preview'); + const oldText = btn.innerHTML; + btn.disabled = true; + btn.textContent = 'Saving…'; + + const r = await api('/oort/api/preview/save', { + method: 'POST', + body: JSON.stringify({ + bucket: state.bucket, + key: currentPreviewKey, + content: ta.value + }) + }); + + btn.disabled = false; + btn.innerHTML = oldText; + + if (r) { + toast(`Saved and uploaded new version of ${currentPreviewKey.split('/').pop()}!`); + loadObjects(); + } +} + +function downloadPreviewFile() { + if (currentPreviewKey) { + downloadFile(currentPreviewKey); + } +} + +/* ─── STATIC WEBSITE HOSTING ─── */ +function toggleSiteInputs(enabled) { + const f = document.getElementById('site-config-fields'); + if (f) f.style.display = enabled ? 'flex' : 'none'; +} + +async function loadSiteConfig() { + const chk = document.getElementById('site-setting-enabled'); + if (!chk) return; + const r = await api(`/oort/api/bucket/website?bucket=${encodeURIComponent(state.bucket)}`); + const enabled = r && !!r.enabled; + chk.checked = enabled; + toggleSiteInputs(enabled); + if (r) { + const idx = document.getElementById('site-index-doc'); + const err = document.getElementById('site-error-doc'); + const spa = document.getElementById('site-spa-mode'); + if (idx) idx.value = r.index_doc || 'index.html'; + if (err) err.value = r.error_doc || '404.html'; + if (spa) spa.checked = !!r.spa_mode; + } + const hostLink = document.getElementById('site-hosted-url'); + if (hostLink) { + hostLink.href = `/oort/site/${encodeURIComponent(state.bucket)}/`; + } +} + +async function saveSiteConfig() { + const chk = document.getElementById('site-setting-enabled'); + const enabled = chk ? chk.checked : false; + const idx = document.getElementById('site-index-doc'); + const err = document.getElementById('site-error-doc'); + const spa = document.getElementById('site-spa-mode'); + const indexDoc = idx ? idx.value.trim() || 'index.html' : 'index.html'; + const errorDoc = err ? err.value.trim() || '404.html' : '404.html'; + const spaMode = spa ? spa.checked : false; + + const r = await api('/oort/api/bucket/website', { + method: 'POST', + body: JSON.stringify({ + bucket: state.bucket, + enabled: enabled, + index_doc: indexDoc, + error_doc: errorDoc, + spa_mode: spaMode + }) + }); + + if (r) { + toast('Static website settings saved successfully!'); + } +} + +/* ─── S3 EVENT WEBHOOKS ─── */ +async function loadWebhooks() { + const listEl = document.getElementById('bucket-webhooks-list'); + if (!listEl) return; + listEl.innerHTML = '
Loading webhooks…
'; + + const r = await api(`/oort/api/bucket/webhooks?bucket=${encodeURIComponent(state.bucket)}`); + if (!r || !r.webhooks || !r.webhooks.length) { + listEl.innerHTML = '
No webhooks configured for this bucket.
'; return; } - modal.innerHTML = ` -
-
-
${key.split('/').pop()}
-
- - + listEl.innerHTML = r.webhooks.map(w => { + const evts = (w.events || []).join(', '); + return ` +
+
+
${w.target_url}
+
Events: ${evts || 'all'} ${w.secret ? '• HMAC signed' : ''}
+
+
+ +
-
- ${mediaHtml} -
-
- `; - document.body.appendChild(modal); + `; + }).join(''); +} - // Load text content - if (isText) { - fetch(r.url).then(res => res.text()).then(text => { - const pre = modal.querySelector('#preview-text-loading'); - if (pre) { - pre.outerHTML = `
${text.replace(//g,'>')}
`; - } - }).catch(() => {}); +async function saveNewWebhook() { + const targetUrl = document.getElementById('webhook-target-url').value.trim(); + if (!targetUrl) return toast('Target URL is required', 'error'); + const secret = document.getElementById('webhook-secret').value.trim(); + const evts = []; + if (document.getElementById('wh-evt-upload').checked) evts.push('object:created'); + if (document.getElementById('wh-evt-delete').checked) evts.push('object:deleted'); + if (!evts.length) return toast('Select at least one trigger event', 'error'); + + const r = await api('/oort/api/bucket/webhooks', { + method: 'POST', + body: JSON.stringify({ + bucket: state.bucket, + target_url: targetUrl, + secret: secret, + events: evts + }) + }); + + if (r) { + toast('Webhook registered successfully!'); + closeModal('modal-add-webhook'); + document.getElementById('webhook-target-url').value = ''; + document.getElementById('webhook-secret').value = ''; + loadWebhooks(); + } +} + +async function deleteWebhook(id) { + if (!confirm('Are you sure you want to delete this webhook?')) return; + const r = await api(`/oort/api/bucket/webhooks?bucket=${encodeURIComponent(state.bucket)}&webhook_id=${encodeURIComponent(id)}`, { + method: 'DELETE' + }); + if (r) { + toast('Webhook deleted'); + loadWebhooks(); + } +} + +async function testWebhook(id) { + toast('Dispatching test ping…'); + const r = await api('/oort/api/bucket/webhooks/test', { + method: 'POST', + body: JSON.stringify({ bucket: state.bucket, webhook_id: id }) + }); + if (r) { + toast(`Test payload delivered! (Status: ${r.status_code || 200})`); } } @@ -2721,59 +3210,199 @@ async function loadObjects() { } const objects = r.objects || []; - if (!objects.length) { - wrap.innerHTML = ` -
-
-

Empty

-

Upload files or create a folder to get started.

-
- - ${uiMode === 'drive' ? `` : ''} - -
-
`; + state.rawObjects = objects; + + renderFilteredObjects(); +} + +/* ─── CATEGORY FILTERING & SEARCH ─── */ +function getFileCategory(name) { + const ext = (name.split('.').pop() || '').toLowerCase(); + if (/^(jpg|jpeg|png|gif|webp|svg|bmp|ico|tiff|avif)$/.test(ext)) return 'images'; + if (/^(mp4|webm|mov|mkv|avi|mp3|wav|ogg|flac|aac|m4a|ogv)$/.test(ext)) return 'media'; + if (/^(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf|odt|csv)$/.test(ext)) return 'docs'; + if (/^(js|ts|jsx|tsx|py|go|html|css|json|yaml|yml|xml|sh|sql|md|c|cpp|h|rs|php|rb|conf|env|ini|toml)$/.test(ext)) return 'code'; + if (/^(zip|tar|gz|tgz|bz2|7z|rar|iso)$/.test(ext)) return 'archives'; + return 'other'; +} + +function filterByCategory(cat) { + state.activeCategory = cat; + document.querySelectorAll('.cat-chip').forEach(el => { + el.classList.toggle('active', el.dataset.cat === cat); + }); + renderFilteredObjects(); +} + +function filterObjectsByQuery(q) { + state.searchQuery = (q || '').trim().toLowerCase(); + renderFilteredObjects(); +} + +function clearFilters() { + state.searchQuery = ''; + state.activeCategory = 'all'; + const inp = document.getElementById('browser-search-inp'); + if (inp) inp.value = ''; + document.querySelectorAll('.cat-chip').forEach(el => { + el.classList.toggle('active', el.dataset.cat === 'all'); + }); + renderFilteredObjects(); +} + +function renderFilteredObjects() { + const wrap = document.getElementById('file-table-wrap'); + if (!wrap) return; + const raw = state.rawObjects || []; + const q = state.searchQuery || ''; + const cat = state.activeCategory || 'all'; + + let filtered = raw.filter(o => { + if (o.name === '.keep' || o.name === '') return false; + if (q) { + const matchName = o.name.toLowerCase().includes(q); + const matchKey = o.key.toLowerCase().includes(q); + if (!matchName && !matchKey) return false; + } + if (cat !== 'all') { + if (o.is_dir) return false; + if (getFileCategory(o.name) !== cat) return false; + } + return true; + }); + + if (!filtered.length) { + if (q || cat !== 'all') { + wrap.innerHTML = ` +
+
+

No matching files found

+

Try adjusting your search query or category filter.

+ +
`; + } else { + wrap.innerHTML = ` +
+
+

Empty

+

Upload files or create a folder to get started.

+
+ + ${typeof uiMode !== 'undefined' && uiMode === 'drive' ? `` : ''} + +
+
`; + } + updateBatchSelection(); return; } - { - // ─── UNIFIED HIERARCHICAL MODE (both S3 and Drive) ─── - const sorted = [...objects.filter(o => o.is_dir && o.name !== ''), ...objects.filter(o => !o.is_dir && o.name !== '.keep')]; - wrap.innerHTML = ` -
-
-
Name
-
Last Modified
-
Size
-
-
- ${sorted.map(o => { - const cls = o.is_dir ? 'folder' : fileIconClass(o.name); - const icon = o.is_dir ? folderSVG() : fileSVG(cls); - const dateStr = o.is_dir ? '—' : new Date(o.last_modified).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}); - const sizeStr = o.is_dir ? '—' : fmtBytes(o.size); - return ` -
-
-
- ${icon} -
-
- ${o.name} -
-
-
${dateStr}
-
${sizeStr}
-
- -
-
`; - }).join('')} + const sorted = [...filtered.filter(o => o.is_dir), ...filtered.filter(o => !o.is_dir)]; + wrap.innerHTML = ` +
+
+
+ +
+
Name
+
Last Modified
+
Size
+
- `; + ${sorted.map(o => { + const cls = o.is_dir ? 'folder' : fileIconClass(o.name); + const icon = o.is_dir ? folderSVG() : fileSVG(cls); + const dateStr = o.is_dir ? '—' : new Date(o.last_modified).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}); + const sizeStr = o.is_dir ? '—' : fmtBytes(o.size); + const escKey = o.key.replace(/'/g, "\\'"); + return ` +
+
+ ${o.is_dir ? '' : ``} +
+
+
+ ${icon} +
+
+ ${o.name} +
+
+
${dateStr}
+
${sizeStr}
+
+ +
+
`; + }).join('')} +
+ `; + updateBatchSelection(); +} + +/* ─── BATCH OPERATIONS ─── */ +function toggleSelectAll(masterCb) { + const cbs = document.querySelectorAll('.file-select-cb'); + cbs.forEach(cb => { cb.checked = masterCb.checked; }); + updateBatchSelection(); +} + +function updateBatchSelection() { + const cbs = Array.from(document.querySelectorAll('.file-select-cb:checked')); + const bar = document.getElementById('batch-action-bar'); + if (!bar) return; + + if (cbs.length > 0) { + bar.style.display = 'flex'; + let totalSize = 0; + cbs.forEach(cb => { + totalSize += parseInt(cb.dataset.size || '0', 10); + }); + const cntBadge = document.getElementById('batch-count-badge'); + const szBadge = document.getElementById('batch-size-badge'); + if (cntBadge) cntBadge.textContent = `${cbs.length} item${cbs.length === 1 ? '' : 's'} selected`; + if (szBadge) szBadge.textContent = fmtBytes(totalSize); + } else { + bar.style.display = 'none'; + const master = document.getElementById('select-all-cb'); + if (master) master.checked = false; + } +} + +function clearBatchSelection() { + const master = document.getElementById('select-all-cb'); + if (master) master.checked = false; + document.querySelectorAll('.file-select-cb').forEach(cb => { cb.checked = false; }); + updateBatchSelection(); +} + +function batchDownloadZip() { + const cbs = Array.from(document.querySelectorAll('.file-select-cb:checked')); + if (!cbs.length) return toast('No files selected', 'error'); + const params = new URLSearchParams(); + params.set('bucket', state.bucket); + cbs.forEach(cb => params.append('keys', cb.dataset.key)); + window.location.href = `/oort/api/batch/zip?${params.toString()}`; +} + +async function batchDeleteSelected() { + const cbs = Array.from(document.querySelectorAll('.file-select-cb:checked')); + if (!cbs.length) return toast('No files selected', 'error'); + if (!confirm(`Are you sure you want to permanently delete ${cbs.length} selected file(s)? This cannot be undone.`)) return; + + const keys = cbs.map(cb => cb.dataset.key); + const r = await api('/oort/api/batch/delete', { + method: 'POST', + body: JSON.stringify({ bucket: state.bucket, keys: keys }) + }); + + if (r) { + toast(`Successfully deleted ${r.deleted || keys.length} file(s)`); + clearBatchSelection(); + loadObjects(); } } @@ -2855,11 +3484,49 @@ window.addEventListener('drop', (e) => { dragCounter = 0; document.getElementById('global-dropzone').style.display = 'none'; if (!state.bucket) return toast('Select a bucket first', 'error'); - if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { + if (e.dataTransfer.items && e.dataTransfer.items.length > 0) { + handleDropEntries(e.dataTransfer.items); + } else if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { queueFiles(e.dataTransfer.files); } }); +async function handleDropEntries(items) { + const files = []; + async function traverse(entry, path = '') { + if (entry.isFile) { + const file = await new Promise((res, rej) => entry.file(res, rej)); + Object.defineProperty(file, 'webkitRelativePath', { + value: path + file.name, + writable: true + }); + files.push(file); + } else if (entry.isDirectory) { + const reader = entry.createReader(); + const readAll = () => new Promise((res, rej) => { + reader.readEntries(async entries => { + if (!entries.length) return res(); + for (const child of entries) { + await traverse(child, path + entry.name + '/'); + } + readAll().then(res); + }, rej); + }); + await readAll(); + } + } + for (let i = 0; i < items.length; i++) { + const entry = items[i].webkitGetAsEntry ? items[i].webkitGetAsEntry() : null; + if (entry) { + await traverse(entry); + } else if (items[i].kind === 'file') { + const f = items[i].getAsFile(); + if (f) files.push(f); + } + } + if (files.length > 0) queueFiles(files); +} + function openUploader() { if (!state.bucket) { toast('Select a bucket first', 'error'); return; } document.getElementById('file-input').click(); @@ -2897,7 +3564,8 @@ async function uploadFile(file) { activeUploads++; updateUMHeader(); - const key = state.prefix + file.name; + const relPath = file.webkitRelativePath || file.name; + const key = state.prefix + relPath; const id = 'u' + Math.random().toString(36).slice(2); const item = document.createElement('div'); @@ -2905,7 +3573,7 @@ async function uploadFile(file) { item.innerHTML = `
-
${file.name}
+
${relPath}
Preparing...${fmtBytes(file.size)}
@@ -3376,7 +4044,7 @@ async function copyPublicURL() { ? state.profile.username : document.getElementById('sidebarName').textContent.replace('@','').trim(); const disp = getBucketDisplayName(state.bucket); - const url = `${window.location.origin}/oort/${username}/${disp}/${key}`; + const url = `https://cosmos.linuxguy.space/oort/${username}/${disp}/${key}`; try { await navigator.clipboard.writeText(url); toast('Public URL copied!'); @@ -3626,6 +4294,57 @@ async function restoreVersion(key, versionId) {
Loading domains...
+ + +
+ +
+
+
+
Host as Static Site
+
Serve SPAs or static sites directly from this bucket with clean URL routing.
+
+ +
+ +
+
+ + +
+
+
+ +
Receive HTTP POST pings when files are uploaded or deleted.
+
+ +
+
Loading webhooks...
+
diff --git a/templates/share.html b/templates/share.html new file mode 100644 index 0000000..7c41b30 --- /dev/null +++ b/templates/share.html @@ -0,0 +1,358 @@ + + + + + + {{if .FileName}}{{.FileName}} — Cosmos Oort Share{{else}}Cosmos Oort Share{{end}} + + + + + + + +
+ + + + + + + + +