forked from cloudflare/cloudflare-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimages.go
401 lines (344 loc) · 11.9 KB
/
images.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package cloudflare
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"time"
"github.com/goccy/go-json"
)
var (
ErrInvalidImagesAPIVersion = errors.New("invalid images API version")
ErrMissingImageID = errors.New("required image ID missing")
)
type ImagesAPIVersion string
const (
ImagesAPIVersionV1 ImagesAPIVersion = "v1"
ImagesAPIVersionV2 ImagesAPIVersion = "v2"
)
// Image represents a Cloudflare Image.
type Image struct {
ID string `json:"id"`
Filename string `json:"filename"`
Meta map[string]interface{} `json:"meta,omitempty"`
RequireSignedURLs bool `json:"requireSignedURLs"`
Variants []string `json:"variants"`
Uploaded time.Time `json:"uploaded"`
}
// UploadImageParams is the data required for an Image Upload request.
type UploadImageParams struct {
File io.ReadCloser
URL string
Name string
RequireSignedURLs bool
Metadata map[string]interface{}
}
// write writes the image upload data to a multipart writer, so
// it can be used in an HTTP request.
func (b UploadImageParams) write(mpw *multipart.Writer) error {
if b.File == nil && b.URL == "" {
return errors.New("a file or url to upload must be specified")
}
if b.File != nil {
name := b.Name
part, err := mpw.CreateFormFile("file", name)
if err != nil {
return err
}
_, err = io.Copy(part, b.File)
if err != nil {
_ = b.File.Close()
return err
}
_ = b.File.Close()
}
if b.URL != "" {
err := mpw.WriteField("url", b.URL)
if err != nil {
return err
}
}
// According to the Cloudflare docs, this field defaults to false.
// For simplicity, we will only send it if the value is true, however
// if the default is changed to true, this logic will need to be updated.
if b.RequireSignedURLs {
err := mpw.WriteField("requireSignedURLs", "true")
if err != nil {
return err
}
}
if b.Metadata != nil {
part, err := mpw.CreateFormField("metadata")
if err != nil {
return err
}
err = json.NewEncoder(part).Encode(b.Metadata)
if err != nil {
return err
}
}
return nil
}
// UpdateImageParams is the data required for an UpdateImage request.
type UpdateImageParams struct {
ID string `json:"-"`
RequireSignedURLs bool `json:"requireSignedURLs"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// CreateImageDirectUploadURLParams is the data required for a CreateImageDirectUploadURL request.
type CreateImageDirectUploadURLParams struct {
Version ImagesAPIVersion `json:"-"`
Expiry *time.Time `json:"expiry,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
RequireSignedURLs *bool `json:"requireSignedURLs,omitempty"`
}
// ImageDirectUploadURLResponse is the API response for a direct image upload url.
type ImageDirectUploadURLResponse struct {
Result ImageDirectUploadURL `json:"result"`
Response
}
// ImageDirectUploadURL .
type ImageDirectUploadURL struct {
ID string `json:"id"`
UploadURL string `json:"uploadURL"`
}
// ImagesListResponse is the API response for listing all images.
type ImagesListResponse struct {
Result struct {
Images []Image `json:"images"`
} `json:"result"`
Response
}
// ImageDetailsResponse is the API response for getting an image's details.
type ImageDetailsResponse struct {
Result Image `json:"result"`
Response
}
// ImagesStatsResponse is the API response for image stats.
type ImagesStatsResponse struct {
Result struct {
Count ImagesStatsCount `json:"count"`
} `json:"result"`
Response
}
// ImagesStatsCount is the stats attached to a ImagesStatsResponse.
type ImagesStatsCount struct {
Current int64 `json:"current"`
Allowed int64 `json:"allowed"`
}
type ListImagesParams struct {
ResultInfo
}
// UploadImage uploads a single image.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-upload-an-image-using-a-single-http-request
func (api *API) UploadImage(ctx context.Context, rc *ResourceContainer, params UploadImageParams) (Image, error) {
if rc.Level != AccountRouteLevel {
return Image{}, ErrRequiredAccountLevelResourceContainer
}
if params.File != nil && params.URL != "" {
return Image{}, errors.New("file and url uploads are mutually exclusive and can only be performed individually")
}
uri := fmt.Sprintf("/accounts/%s/images/v1", rc.Identifier)
body := &bytes.Buffer{}
w := multipart.NewWriter(body)
if err := params.write(w); err != nil {
_ = w.Close()
return Image{}, fmt.Errorf("error writing multipart body: %w", err)
}
_ = w.Close()
res, err := api.makeRequestContextWithHeaders(
ctx,
http.MethodPost,
uri,
body,
http.Header{
"Accept": []string{"application/json"},
"Content-Type": []string{w.FormDataContentType()},
},
)
if err != nil {
return Image{}, err
}
var imageDetailsResponse ImageDetailsResponse
err = json.Unmarshal(res, &imageDetailsResponse)
if err != nil {
return Image{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imageDetailsResponse.Result, nil
}
// UpdateImage updates an existing image's metadata.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-update-image
func (api *API) UpdateImage(ctx context.Context, rc *ResourceContainer, params UpdateImageParams) (Image, error) {
if rc.Level != AccountRouteLevel {
return Image{}, ErrRequiredAccountLevelResourceContainer
}
uri := fmt.Sprintf("/accounts/%s/images/v1/%s", rc.Identifier, params.ID)
res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, params)
if err != nil {
return Image{}, err
}
var imageDetailsResponse ImageDetailsResponse
err = json.Unmarshal(res, &imageDetailsResponse)
if err != nil {
return Image{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imageDetailsResponse.Result, nil
}
var imagesMultipartBoundary = "----CloudflareImagesGoClientBoundary"
// CreateImageDirectUploadURL creates an authenticated direct upload url.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-create-authenticated-direct-upload-url
func (api *API) CreateImageDirectUploadURL(ctx context.Context, rc *ResourceContainer, params CreateImageDirectUploadURLParams) (ImageDirectUploadURL, error) {
if rc.Level != AccountRouteLevel {
return ImageDirectUploadURL{}, ErrRequiredAccountLevelResourceContainer
}
if params.Version != "" && params.Version != ImagesAPIVersionV1 && params.Version != ImagesAPIVersionV2 {
return ImageDirectUploadURL{}, ErrInvalidImagesAPIVersion
}
var err error
var uri string
var res []byte
switch params.Version {
case ImagesAPIVersionV2:
uri = fmt.Sprintf("/%s/%s/images/%s/direct_upload", rc.Level, rc.Identifier, params.Version)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if err := writer.SetBoundary(imagesMultipartBoundary); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error setting multipart boundary")
}
if *params.RequireSignedURLs {
if err = writer.WriteField("requireSignedURLs", "true"); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error writing requireSignedURLs field: %w", err)
}
}
if !params.Expiry.IsZero() {
if err = writer.WriteField("expiry", params.Expiry.Format(time.RFC3339)); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error writing expiry field: %w", err)
}
}
if params.Metadata != nil {
var metadataBytes []byte
if metadataBytes, err = json.Marshal(params.Metadata); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error marshalling metadata to JSON: %w", err)
}
if err = writer.WriteField("metadata", string(metadataBytes)); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error writing metadata field: %w", err)
}
}
if err = writer.Close(); err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("error closing multipart writer: %w", err)
}
res, err = api.makeRequestContextWithHeaders(
ctx,
http.MethodPost,
uri,
body,
http.Header{
"Accept": []string{"application/json"},
"Content-Type": []string{writer.FormDataContentType()},
},
)
case ImagesAPIVersionV1:
case "":
uri = fmt.Sprintf("/%s/%s/images/%s/direct_upload", rc.Level, rc.Identifier, ImagesAPIVersionV1)
res, err = api.makeRequestContext(ctx, http.MethodPost, uri, params)
default:
return ImageDirectUploadURL{}, ErrInvalidImagesAPIVersion
}
if err != nil {
return ImageDirectUploadURL{}, err
}
var imageDirectUploadURLResponse ImageDirectUploadURLResponse
err = json.Unmarshal(res, &imageDirectUploadURLResponse)
if err != nil {
return ImageDirectUploadURL{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imageDirectUploadURLResponse.Result, nil
}
// ListImages lists all images.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-list-images
func (api *API) ListImages(ctx context.Context, rc *ResourceContainer, params ListImagesParams) ([]Image, error) {
uri := buildURI(fmt.Sprintf("/accounts/%s/images/v1", rc.Identifier), params)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return []Image{}, err
}
var imagesListResponse ImagesListResponse
err = json.Unmarshal(res, &imagesListResponse)
if err != nil {
return []Image{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imagesListResponse.Result.Images, nil
}
// GetImage gets the details of an uploaded image.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-image-details
func (api *API) GetImage(ctx context.Context, rc *ResourceContainer, id string) (Image, error) {
if rc.Level != AccountRouteLevel {
return Image{}, ErrRequiredAccountLevelResourceContainer
}
uri := fmt.Sprintf("/accounts/%s/images/v1/%s", rc.Identifier, id)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return Image{}, err
}
var imageDetailsResponse ImageDetailsResponse
err = json.Unmarshal(res, &imageDetailsResponse)
if err != nil {
return Image{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imageDetailsResponse.Result, nil
}
// GetBaseImage gets the base image used to derive variants.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-base-image
func (api *API) GetBaseImage(ctx context.Context, rc *ResourceContainer, id string) ([]byte, error) {
if rc.Level != AccountRouteLevel {
return []byte{}, ErrRequiredAccountLevelResourceContainer
}
uri := fmt.Sprintf("/accounts/%s/images/v1/%s/blob", rc.Identifier, id)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, err
}
return res, nil
}
// DeleteImage deletes an image.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-delete-image
func (api *API) DeleteImage(ctx context.Context, rc *ResourceContainer, id string) error {
if rc.Level != AccountRouteLevel {
return ErrRequiredAccountLevelResourceContainer
}
uri := fmt.Sprintf("/accounts/%s/images/v1/%s", rc.Identifier, id)
_, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
if err != nil {
return err
}
return nil
}
// GetImagesStats gets an account's statistics for Cloudflare Images.
//
// API Reference: https://api.cloudflare.com/#cloudflare-images-images-usage-statistics
func (api *API) GetImagesStats(ctx context.Context, rc *ResourceContainer) (ImagesStatsCount, error) {
if rc.Level != AccountRouteLevel {
return ImagesStatsCount{}, ErrRequiredAccountLevelResourceContainer
}
uri := fmt.Sprintf("/accounts/%s/images/v1/stats", rc.Identifier)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return ImagesStatsCount{}, err
}
var imagesStatsResponse ImagesStatsResponse
err = json.Unmarshal(res, &imagesStatsResponse)
if err != nil {
return ImagesStatsCount{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return imagesStatsResponse.Result.Count, nil
}