repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
065a976
parent
4914642
author
Eric Bower
date
2024-03-12 18:46:44 +0000 UTC
feat(ui): api for fetching project objects
1 files changed,  +52, -0
M ui/api.go
+52, -0
 1@@ -5,6 +5,7 @@ import (
 2 	"fmt"
 3 	"io"
 4 	"net/http"
 5+	"time"
 6 
 7 	"github.com/charmbracelet/ssh"
 8 	"github.com/picosh/pico/db"
 9@@ -350,6 +351,56 @@ func getPosts(httpCtx *shared.HttpCtx, ctx ssh.Context, user *db.User, space str
10 	}
11 }
12 
13+type objectsPayload struct {
14+	Objects []*ProjectObject `json:"objects"`
15+}
16+
17+type ProjectObject struct {
18+	Name    string    `json:"name"`
19+	Size    int64     `json:"size"`
20+	ModTime time.Time `json:"mod_time"`
21+}
22+
23+func getProjectObjects(httpCtx *shared.HttpCtx, ctx ssh.Context, user *db.User) http.HandlerFunc {
24+	logger := httpCtx.Cfg.Logger
25+	storage := httpCtx.Storage
26+	return func(w http.ResponseWriter, r *http.Request) {
27+		w.Header().Set("Content-Type", "application/json")
28+		if !ensureUser(w, user) {
29+			return
30+		}
31+
32+		projectName := shared.GetField(r, 0)
33+		bucketName := shared.GetAssetBucketName(user.ID)
34+		bucket, err := storage.GetBucket(bucketName)
35+		if err != nil {
36+			logger.Info("bucket not found", "err", err.Error())
37+			shared.JSONError(w, err.Error(), http.StatusNotFound)
38+			return
39+		}
40+		objects, err := storage.ListObjects(bucket, projectName, true)
41+		if err != nil {
42+			logger.Info("cannot fetch objects", "err", err.Error())
43+			shared.JSONError(w, err.Error(), http.StatusUnprocessableEntity)
44+			return
45+		}
46+
47+		pobjs := []*ProjectObject{}
48+		for _, obj := range objects {
49+			pobjs = append(pobjs, &ProjectObject{
50+				Name:    obj.Name(),
51+				Size:    obj.Size(),
52+				ModTime: obj.ModTime(),
53+			})
54+		}
55+
56+		err = json.NewEncoder(w).Encode(&objectsPayload{Objects: pobjs})
57+		if err != nil {
58+			logger.Error(err.Error())
59+		}
60+	}
61+}
62+
63 func CreateRoutes(httpCtx *shared.HttpCtx, ctx ssh.Context) []shared.Route {
64 	logger := httpCtx.Cfg.Logger
65 	dbpool := httpCtx.Dbpool
66@@ -378,6 +429,7 @@ func CreateRoutes(httpCtx *shared.HttpCtx, ctx ssh.Context) []shared.Route {
67 		shared.NewCorsRoute("POST", "/api/tokens", createToken(httpCtx, ctx, user)),
68 		shared.NewCorsRoute("DELETE", "/api/tokens/(.+)", deleteToken(httpCtx, ctx, user)),
69 		shared.NewCorsRoute("GET", "/api/projects", getProjects(httpCtx, ctx, user)),
70+		shared.NewCorsRoute("GET", "/api/projects/(.+)", getProjectObjects(httpCtx, ctx, user)),
71 		shared.NewCorsRoute("GET", "/api/posts/prose", getPosts(httpCtx, ctx, user, "prose")),
72 		shared.NewCorsRoute("GET", "/api/posts/pastes", getPosts(httpCtx, ctx, user, "pastes")),
73 		shared.NewCorsRoute("GET", "/api/posts/feeds", getPosts(httpCtx, ctx, user, "feeds")),