-
-
Notifications
You must be signed in to change notification settings - Fork 193
/
objects.go
237 lines (218 loc) · 8.02 KB
/
objects.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package client
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path"
"strings"
"github.com/go-errors/errors"
"github.com/spf13/afero"
"github.com/supabase/cli/internal/utils"
"github.com/supabase/cli/internal/utils/tenant"
)
const PAGE_LIMIT = 100
type ListObjectsQuery struct {
Prefix string `json:"prefix"`
Search string `json:"search,omitempty"`
Limit int `json:"limit,omitempty"`
Offset int `json:"offset,omitempty"`
}
type ObjectResponse struct {
Name string `json:"name"` // "abstract.pdf"
Id *string `json:"id"` // "9b7f9f48-17a6-4ca8-b14a-39b0205a63e9"
UpdatedAt *string `json:"updated_at"` // "2023-10-13T18:08:22.068Z"
CreatedAt *string `json:"created_at"` // "2023-10-13T18:08:22.068Z"
LastAccessedAt *string `json:"last_accessed_at"` // "2023-10-13T18:08:22.068Z"
Metadata *ObjectMetadata `json:"metadata"` // null
}
type ObjectMetadata struct {
ETag string `json:"eTag"` // "\"887ea9be3c68e6f2fca7fd2d7c77d8fe\""
Size int `json:"size"` // 82702
Mimetype string `json:"mimetype"` // "application/pdf"
CacheControl string `json:"cacheControl"` // "max-age=3600"
LastModified string `json:"lastModified"` // "2023-10-13T18:08:22.000Z"
ContentLength int `json:"contentLength"` // 82702
HttpStatusCode int `json:"httpStatusCode"` // 200
}
func ListStorageObjects(ctx context.Context, projectRef, bucket, prefix string, page int) ([]ObjectResponse, error) {
url := fmt.Sprintf("https://%s/storage/v1/object/list/%s", utils.GetSupabaseHost(projectRef), bucket)
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return nil, err
}
dir, name := path.Split(prefix)
query := ListObjectsQuery{
Prefix: dir,
Search: name,
Limit: PAGE_LIMIT,
Offset: PAGE_LIMIT * page,
}
data, err := tenant.JsonResponseWithBearer[[]ObjectResponse](ctx, http.MethodPost, url, apiKey.ServiceRole, query)
if err != nil {
return nil, err
}
return *data, nil
}
type FileOptions struct {
CacheControl string
ContentType string
}
func UploadStorageObject(ctx context.Context, projectRef, remotePath, localPath string, fsys afero.Fs, opts ...func(*FileOptions)) error {
f, err := fsys.Open(localPath)
if err != nil {
return errors.Errorf("failed to open file: %w", err)
}
defer f.Close()
// Customise file options
fo := &FileOptions{}
for _, apply := range opts {
apply(fo)
}
// Use default value of storage-js: https://github.com/supabase/storage-js/blob/main/src/packages/StorageFileApi.ts#L22
if len(fo.CacheControl) == 0 {
fo.CacheControl = "max-age=3600"
}
// Decode mimetype
if len(fo.ContentType) == 0 {
header := io.LimitReader(f, 512)
buf, err := io.ReadAll(header)
if err != nil {
return errors.Errorf("failed to read file: %w", err)
}
fo.ContentType = http.DetectContentType(buf)
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return errors.Errorf("failed to seek file: %w", err)
}
}
// Prepare request
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return err
}
remotePath = strings.TrimPrefix(remotePath, "/")
url := fmt.Sprintf("https://%s/storage/v1/object/%s", utils.GetSupabaseHost(projectRef), remotePath)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, f)
if err != nil {
return errors.Errorf("failed to initialise http request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+apiKey.ServiceRole)
req.Header.Add("Content-Type", fo.ContentType)
req.Header.Add("Cache-Control", fo.CacheControl)
// Sends request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Errorf("failed to send http request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Errorf("failed to read http response: %w", err)
}
return errors.Errorf("Error status %d: %s", resp.StatusCode, body)
}
return nil
}
func DownloadStorageObject(ctx context.Context, projectRef, remotePath, localPath string, fsys afero.Fs) error {
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return err
}
remotePath = strings.TrimPrefix(remotePath, "/")
url := fmt.Sprintf("https://%s/storage/v1/object/%s", utils.GetSupabaseHost(projectRef), remotePath)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return errors.Errorf("failed to initialise http request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+apiKey.ServiceRole)
// Sends request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Errorf("failed to send http request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Errorf("failed to read http response: %w", err)
}
return errors.Errorf("Error status %d: %s", resp.StatusCode, body)
}
// Streams to file
f, err := fsys.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return errors.Errorf("failed to open file: %w", err)
}
defer f.Close()
if _, err = io.Copy(f, resp.Body); err != nil {
return errors.Errorf("failed to write file: %w", err)
}
return nil
}
type MoveObjectRequest struct {
BucketId string `json:"bucketId"`
SourceKey string `json:"sourceKey"`
DestinationKey string `json:"destinationKey"`
}
type MoveObjectResponse = DeleteBucketResponse
func MoveStorageObject(ctx context.Context, projectRef, bucketId, srcPath, dstPath string) (*MoveObjectResponse, error) {
url := fmt.Sprintf("https://%s/storage/v1/object/move", utils.GetSupabaseHost(projectRef))
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return nil, err
}
body := MoveObjectRequest{
BucketId: bucketId,
SourceKey: srcPath,
DestinationKey: dstPath,
}
return tenant.JsonResponseWithBearer[MoveObjectResponse](ctx, http.MethodPost, url, apiKey.ServiceRole, body)
}
type CopyObjectRequest = MoveObjectRequest
type CopyObjectResponse struct {
Key string `json:"key"`
}
func CopyStorageObject(ctx context.Context, projectRef, bucketId, srcPath, dstPath string) (*CopyObjectResponse, error) {
url := fmt.Sprintf("https://%s/storage/v1/object/copy", utils.GetSupabaseHost(projectRef))
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return nil, err
}
body := CopyObjectRequest{
BucketId: bucketId,
SourceKey: srcPath,
DestinationKey: dstPath,
}
return tenant.JsonResponseWithBearer[CopyObjectResponse](ctx, http.MethodPost, url, apiKey.ServiceRole, body)
}
type DeleteObjectsRequest struct {
Prefixes []string `json:"prefixes"`
}
type DeleteObjectsResponse struct {
BucketId string `json:"bucket_id"` // "private"
Owner string `json:"owner"` // ""
OwnerId string `json:"owner_id"` // ""
Version string `json:"version"` // "cf5c5c53-ee73-4806-84e3-7d92c954b436"
Name string `json:"name"` // "abstract.pdf"
Id string `json:"id"` // "9b7f9f48-17a6-4ca8-b14a-39b0205a63e9"
UpdatedAt string `json:"updated_at"` // "2023-10-13T18:08:22.068Z"
CreatedAt string `json:"created_at"` // "2023-10-13T18:08:22.068Z"
LastAccessedAt string `json:"last_accessed_at"` // "2023-10-13T18:08:22.068Z"
Metadata ObjectMetadata `json:"metadata"` // null
}
func DeleteStorageObjects(ctx context.Context, projectRef, bucket string, prefixes []string) ([]DeleteObjectsResponse, error) {
url := fmt.Sprintf("https://%s/storage/v1/object/%s", utils.GetSupabaseHost(projectRef), bucket)
apiKey, err := tenant.GetApiKeys(ctx, projectRef)
if err != nil {
return nil, err
}
body := DeleteObjectsRequest{Prefixes: prefixes}
data, err := tenant.JsonResponseWithBearer[[]DeleteObjectsResponse](ctx, http.MethodDelete, url, apiKey.ServiceRole, body)
if err != nil {
return nil, err
}
return *data, nil
}