-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1024 lines (887 loc) · 30.8 KB
/
client.go
File metadata and controls
1024 lines (887 loc) · 30.8 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package sirv provides a Go SDK for the Sirv REST API.
//
// Example usage:
//
// client := sirv.NewClient(sirv.ClientConfig{
// ClientID: "your-client-id",
// ClientSecret: "your-client-secret",
// })
//
// ctx := context.Background()
// token, err := client.Connect(ctx)
// if err != nil {
// log.Fatal(err)
// }
//
// account, err := client.GetAccountInfo(ctx)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println("CDN URL:", account.CdnURL)
package sirv
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"sync"
"time"
)
const (
// DefaultBaseURL is the default Sirv API base URL.
DefaultBaseURL = "https://api.sirv.com"
// DefaultTokenRefreshBuffer is the default seconds before token expiry to trigger refresh.
DefaultTokenRefreshBuffer = 60
// DefaultTimeout is the default HTTP request timeout.
DefaultTimeout = 30 * time.Second
// DefaultMaxRetries is the default maximum number of retries for failed requests.
DefaultMaxRetries = 3
)
// ClientConfig holds the configuration for the Sirv client.
type ClientConfig struct {
// ClientID is your Sirv API client ID (required).
ClientID string
// ClientSecret is your Sirv API client secret (required).
ClientSecret string
// BaseURL is the base URL for API (default: https://api.sirv.com).
BaseURL string
// AutoRefreshToken enables automatic token refresh before expiry (default: true).
AutoRefreshToken *bool
// TokenRefreshBuffer is seconds before token expiry to trigger refresh (default: 60).
TokenRefreshBuffer int
// Timeout is the request timeout (default: 30s).
Timeout time.Duration
// MaxRetries is the maximum number of retries for failed requests (default: 3).
MaxRetries int
// HTTPClient allows using a custom HTTP client.
HTTPClient *http.Client
}
// Client is the Sirv REST API client.
type Client struct {
config ClientConfig
httpClient *http.Client
token string
tokenExpiry time.Time
mu sync.RWMutex
}
// NewClient creates a new Sirv API client.
func NewClient(config ClientConfig) (*Client, error) {
if config.ClientID == "" || config.ClientSecret == "" {
return nil, fmt.Errorf("sirv: clientId and clientSecret are required")
}
if config.BaseURL == "" {
config.BaseURL = DefaultBaseURL
}
if config.AutoRefreshToken == nil {
autoRefresh := true
config.AutoRefreshToken = &autoRefresh
}
if config.TokenRefreshBuffer == 0 {
config.TokenRefreshBuffer = DefaultTokenRefreshBuffer
}
if config.Timeout == 0 {
config.Timeout = DefaultTimeout
}
if config.MaxRetries == 0 {
config.MaxRetries = DefaultMaxRetries
}
httpClient := config.HTTPClient
if httpClient == nil {
httpClient = &http.Client{
Timeout: config.Timeout,
}
}
return &Client{
config: config,
httpClient: httpClient,
}, nil
}
// isTokenExpired checks if the token is expired or about to expire.
func (c *Client) isTokenExpired() bool {
c.mu.RLock()
defer c.mu.RUnlock()
buffer := time.Duration(0)
if c.config.AutoRefreshToken != nil && *c.config.AutoRefreshToken {
buffer = time.Duration(c.config.TokenRefreshBuffer) * time.Second
}
return time.Now().After(c.tokenExpiry.Add(-buffer))
}
// getToken returns a valid token, refreshing if necessary.
func (c *Client) getToken(ctx context.Context) (string, error) {
if c.token == "" || c.isTokenExpired() {
_, err := c.Connect(ctx)
if err != nil {
return "", err
}
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.token, nil
}
// doRequest makes an HTTP request.
func (c *Client) doRequest(ctx context.Context, method, endpoint string, body interface{}, headers map[string]string) (*http.Response, error) {
var bodyReader io.Reader
if body != nil {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("sirv: failed to marshal request body: %w", err)
}
bodyReader = bytes.NewReader(jsonBody)
}
req, err := http.NewRequestWithContext(ctx, method, c.config.BaseURL+endpoint, bodyReader)
if err != nil {
return nil, fmt.Errorf("sirv: failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
return c.httpClient.Do(req)
}
// doRequestWithRetry makes an authenticated request with retry logic.
func (c *Client) doRequestWithRetry(ctx context.Context, method, endpoint string, body interface{}, retries int) (*http.Response, error) {
token, err := c.getToken(ctx)
if err != nil {
return nil, err
}
headers := map[string]string{
"Authorization": "Bearer " + token,
}
resp, err := c.doRequest(ctx, method, endpoint, body, headers)
if err != nil {
return nil, err
}
// Retry on 5xx errors
if resp.StatusCode >= 500 && retries < c.config.MaxRetries {
resp.Body.Close()
time.Sleep(time.Duration(1<<retries) * time.Second)
return c.doRequestWithRetry(ctx, method, endpoint, body, retries+1)
}
return resp, nil
}
// request makes an authenticated API request and decodes the response.
func (c *Client) request(ctx context.Context, method, endpoint string, body interface{}, result interface{}) error {
resp, err := c.doRequestWithRetry(ctx, method, endpoint, body, 0)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var apiErr APIError
if err := json.NewDecoder(resp.Body).Decode(&apiErr); err != nil {
return NewAPIError(resp.StatusCode, http.StatusText(resp.StatusCode), "")
}
apiErr.StatusCode = resp.StatusCode
return &apiErr
}
if result != nil {
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return fmt.Errorf("sirv: failed to decode response: %w", err)
}
}
return nil
}
// requestWithQuery makes an authenticated GET request with query parameters.
func (c *Client) requestWithQuery(ctx context.Context, endpoint string, params map[string]string, result interface{}) error {
if len(params) > 0 {
q := url.Values{}
for k, v := range params {
q.Set(k, v)
}
endpoint = endpoint + "?" + q.Encode()
}
return c.request(ctx, http.MethodGet, endpoint, nil, result)
}
// ============================================================================
// Authentication
// ============================================================================
// Connect authenticates and obtains a bearer token.
// expiresIn is optional - pass nil for default (1200 seconds/20 minutes).
// Valid range is 5-604800 seconds.
func (c *Client) Connect(ctx context.Context, expiresIn ...int) (*TokenResponse, error) {
body := map[string]interface{}{
"clientId": c.config.ClientID,
"clientSecret": c.config.ClientSecret,
}
if len(expiresIn) > 0 {
exp := expiresIn[0]
if exp < 5 || exp > 604800 {
return nil, NewAPIError(400, "expiresIn must be between 5 and 604800 seconds", "")
}
body["expiresIn"] = exp
}
resp, err := c.doRequest(ctx, http.MethodPost, "/v2/token", body, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, NewAPIError(resp.StatusCode, "Authentication failed", "")
}
var tokenResp TokenResponse
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
return nil, fmt.Errorf("sirv: failed to decode token response: %w", err)
}
c.mu.Lock()
c.token = tokenResp.Token
c.tokenExpiry = time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
c.mu.Unlock()
return &tokenResp, nil
}
// IsConnected checks if client is connected with a valid token.
func (c *Client) IsConnected() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.token != "" && !c.isTokenExpired()
}
// GetAccessToken returns the current token (useful for external integrations).
func (c *Client) GetAccessToken() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.token
}
// ============================================================================
// Account API
// ============================================================================
// GetAccountInfo gets account information.
func (c *Client) GetAccountInfo(ctx context.Context) (*AccountInfo, error) {
var result AccountInfo
if err := c.request(ctx, http.MethodGet, "/v2/account", nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// UpdateAccount updates account settings.
func (c *Client) UpdateAccount(ctx context.Context, options *AccountUpdateOptions) error {
return c.request(ctx, http.MethodPost, "/v2/account", options, nil)
}
// GetAccountLimits gets API rate limits.
func (c *Client) GetAccountLimits(ctx context.Context) (*AccountLimits, error) {
var result AccountLimits
if err := c.request(ctx, http.MethodGet, "/v2/account/limits", nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// GetStorageInfo gets storage usage information.
func (c *Client) GetStorageInfo(ctx context.Context) (*StorageInfo, error) {
var result StorageInfo
if err := c.request(ctx, http.MethodGet, "/v2/account/storage", nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// GetAccountUsers gets all account users.
func (c *Client) GetAccountUsers(ctx context.Context) ([]AccountUser, error) {
var result []AccountUser
if err := c.request(ctx, http.MethodGet, "/v2/account/users", nil, &result); err != nil {
return nil, err
}
return result, nil
}
// GetBillingPlan gets billing plan details.
func (c *Client) GetBillingPlan(ctx context.Context) (*BillingPlan, error) {
var result BillingPlan
if err := c.request(ctx, http.MethodGet, "/v2/billing/plan", nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// SearchEvents searches account events.
func (c *Client) SearchEvents(ctx context.Context, params *EventSearchParams) ([]AccountEvent, error) {
var result []AccountEvent
if err := c.request(ctx, http.MethodPost, "/v2/account/events/search", params, &result); err != nil {
return nil, err
}
return result, nil
}
// MarkEventsSeen marks events as seen.
func (c *Client) MarkEventsSeen(ctx context.Context, eventIDs []string) error {
return c.request(ctx, http.MethodPost, "/v2/account/events/seen", eventIDs, nil)
}
// ============================================================================
// User API
// ============================================================================
// GetUserInfo gets user information.
// userID is optional - pass empty string to get current user.
func (c *Client) GetUserInfo(ctx context.Context, userID string) (*UserInfo, error) {
params := make(map[string]string)
if userID != "" {
params["userId"] = userID
}
var result UserInfo
if err := c.requestWithQuery(ctx, "/v2/user", params, &result); err != nil {
return nil, err
}
return &result, nil
}
// ============================================================================
// Files API - Reading
// ============================================================================
// GetFileInfo gets file information.
func (c *Client) GetFileInfo(ctx context.Context, filename string) (*FileInfo, error) {
var result FileInfo
if err := c.requestWithQuery(ctx, "/v2/files/stat", map[string]string{"filename": filename}, &result); err != nil {
return nil, err
}
return &result, nil
}
// ReadFolderContents reads folder contents.
func (c *Client) ReadFolderContents(ctx context.Context, dirname string, continuation string) (*FolderContents, error) {
params := map[string]string{"dirname": dirname}
if continuation != "" {
params["continuation"] = continuation
}
var result FolderContents
if err := c.requestWithQuery(ctx, "/v2/files/readdir", params, &result); err != nil {
return nil, err
}
return &result, nil
}
// IterateFolderContents iterates through all items in a folder (handles pagination automatically).
// Returns a channel that yields FileInfo items.
func (c *Client) IterateFolderContents(ctx context.Context, dirname string) (<-chan FileInfo, <-chan error) {
fileCh := make(chan FileInfo)
errCh := make(chan error, 1)
go func() {
defer close(fileCh)
defer close(errCh)
continuation := ""
for {
result, err := c.ReadFolderContents(ctx, dirname, continuation)
if err != nil {
errCh <- err
return
}
for _, item := range result.Contents {
select {
case fileCh <- item:
case <-ctx.Done():
errCh <- ctx.Err()
return
}
}
if result.Continuation == "" {
return
}
continuation = result.Continuation
}
}()
return fileCh, errCh
}
// GetFolderOptions gets folder options.
func (c *Client) GetFolderOptions(ctx context.Context, dirname string) (*FolderOptions, error) {
var result FolderOptions
if err := c.requestWithQuery(ctx, "/v2/files/options", map[string]string{"dirname": dirname}, &result); err != nil {
return nil, err
}
return &result, nil
}
// SetFolderOptions sets folder options.
func (c *Client) SetFolderOptions(ctx context.Context, dirname string, options *FolderOptions) error {
body := map[string]interface{}{
"dirname": dirname,
}
if options.ScanSpins != nil {
body["scanSpins"] = *options.ScanSpins
}
if options.AllowListing != nil {
body["allowListing"] = *options.AllowListing
}
return c.request(ctx, http.MethodPost, "/v2/files/options", body, nil)
}
// transformSearchResult transforms raw Elasticsearch response to SearchResult.
func transformSearchResult(raw *rawSearchResult) *SearchResult {
hits := make([]FileInfo, 0, len(raw.Hits))
for _, hit := range raw.Hits {
var source *rawFileSource
if hit.Source != nil {
source = hit.Source
}
if source != nil {
hits = append(hits, FileInfo{
Filename: source.Filename,
Dirname: source.Dirname,
Basename: source.Basename,
IsDirectory: source.IsDirectory,
Size: source.Size,
Ctime: source.Ctime,
Mtime: source.Mtime,
ContentType: source.ContentType,
Meta: source.Meta,
})
}
}
var total int64
switch t := raw.Total.(type) {
case float64:
total = int64(t)
case map[string]interface{}:
if v, ok := t["value"].(float64); ok {
total = int64(v)
}
}
return &SearchResult{
Hits: hits,
Total: total,
ScrollID: raw.ScrollID,
}
}
// SearchFiles searches files.
func (c *Client) SearchFiles(ctx context.Context, params *SearchParams) (*SearchResult, error) {
var raw rawSearchResult
if err := c.request(ctx, http.MethodPost, "/v2/files/search", params, &raw); err != nil {
return nil, err
}
return transformSearchResult(&raw), nil
}
// ScrollSearch continues paginated search.
func (c *Client) ScrollSearch(ctx context.Context, scrollID string) (*SearchResult, error) {
var raw rawSearchResult
if err := c.request(ctx, http.MethodPost, "/v2/files/search/scroll", map[string]string{"scrollId": scrollID}, &raw); err != nil {
return nil, err
}
return transformSearchResult(&raw), nil
}
// IterateSearchResults iterates through all search results (handles pagination automatically).
// Returns a channel that yields FileInfo items.
func (c *Client) IterateSearchResults(ctx context.Context, params *SearchParams) (<-chan FileInfo, <-chan error) {
fileCh := make(chan FileInfo)
errCh := make(chan error, 1)
go func() {
defer close(fileCh)
defer close(errCh)
result, err := c.SearchFiles(ctx, params)
if err != nil {
errCh <- err
return
}
for _, hit := range result.Hits {
select {
case fileCh <- hit:
case <-ctx.Done():
errCh <- ctx.Err()
return
}
}
for result.ScrollID != "" && len(result.Hits) > 0 {
result, err = c.ScrollSearch(ctx, result.ScrollID)
if err != nil {
errCh <- err
return
}
for _, hit := range result.Hits {
select {
case fileCh <- hit:
case <-ctx.Done():
errCh <- ctx.Err()
return
}
}
}
}()
return fileCh, errCh
}
// DownloadFile downloads a file and returns its content as bytes.
func (c *Client) DownloadFile(ctx context.Context, filename string) ([]byte, error) {
token, err := c.getToken(ctx)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.config.BaseURL+"/v2/files/download?filename="+url.QueryEscape(filename), nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, NewAPIError(resp.StatusCode, "Download failed", "")
}
return io.ReadAll(resp.Body)
}
// DownloadFileTo downloads a file to a local path.
func (c *Client) DownloadFileTo(ctx context.Context, filename, localPath string) error {
data, err := c.DownloadFile(ctx, filename)
if err != nil {
return err
}
return os.WriteFile(localPath, data, 0644)
}
// ============================================================================
// Files API - Writing
// ============================================================================
// UploadFile uploads a file from bytes.
func (c *Client) UploadFile(ctx context.Context, targetPath string, content []byte, options *UploadOptions) error {
return c.uploadFileContent(ctx, targetPath, bytes.NewReader(content), options)
}
// UploadFileFromPath uploads a file from local path.
func (c *Client) UploadFileFromPath(ctx context.Context, targetPath, localPath string, options *UploadOptions) error {
file, err := os.Open(localPath)
if err != nil {
return fmt.Errorf("sirv: failed to open file: %w", err)
}
defer file.Close()
if options == nil {
options = &UploadOptions{}
}
if options.Filename == "" {
options.Filename = filepath.Base(localPath)
}
return c.uploadFileContent(ctx, targetPath, file, options)
}
// UploadFileFromReader uploads a file from io.Reader.
func (c *Client) UploadFileFromReader(ctx context.Context, targetPath string, reader io.Reader, options *UploadOptions) error {
return c.uploadFileContent(ctx, targetPath, reader, options)
}
func (c *Client) uploadFileContent(ctx context.Context, targetPath string, reader io.Reader, options *UploadOptions) error {
token, err := c.getToken(ctx)
if err != nil {
return err
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
filename := filepath.Base(targetPath)
if options != nil && options.Filename != "" {
filename = options.Filename
}
part, err := writer.CreateFormFile("file", filename)
if err != nil {
return fmt.Errorf("sirv: failed to create form file: %w", err)
}
if _, err := io.Copy(part, reader); err != nil {
return fmt.Errorf("sirv: failed to copy file content: %w", err)
}
if err := writer.Close(); err != nil {
return fmt.Errorf("sirv: failed to close multipart writer: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.config.BaseURL+"/v2/files/upload?filename="+url.QueryEscape(targetPath), &body)
if err != nil {
return err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+token)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return NewAPIError(resp.StatusCode, "Upload failed", "")
}
return nil
}
// CreateFolder creates a new folder.
func (c *Client) CreateFolder(ctx context.Context, dirname string) error {
return c.request(ctx, http.MethodPost, "/v2/files/mkdir", map[string]string{"dirname": dirname}, nil)
}
// DeleteFile deletes a file or empty folder.
func (c *Client) DeleteFile(ctx context.Context, filename string) error {
return c.request(ctx, http.MethodPost, "/v2/files/delete", map[string]string{"filename": filename}, nil)
}
// BatchDelete deletes multiple files/folders.
func (c *Client) BatchDelete(ctx context.Context, filenames []string) (*BatchDeleteResult, error) {
var result BatchDeleteResult
if err := c.request(ctx, http.MethodPost, "/v2/files/delete", filenames, &result); err != nil {
return nil, err
}
return &result, nil
}
// GetBatchDeleteStatus gets batch delete job status.
func (c *Client) GetBatchDeleteStatus(ctx context.Context, jobID string) (*BatchDeleteResult, error) {
var result BatchDeleteResult
if err := c.request(ctx, http.MethodGet, "/v2/files/delete/"+jobID, nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// CopyFile copies a file.
func (c *Client) CopyFile(ctx context.Context, params *CopyParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/copy", params, nil)
}
// RenameFile renames or moves a file/folder.
func (c *Client) RenameFile(ctx context.Context, params *RenameParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/rename", params, nil)
}
// FetchURL fetches file from external URL.
func (c *Client) FetchURL(ctx context.Context, params *FetchURLParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/fetch", params, nil)
}
// BatchZip creates ZIP archive from multiple files.
func (c *Client) BatchZip(ctx context.Context, params *BatchZipParams) (*BatchZipResult, error) {
var result BatchZipResult
if err := c.request(ctx, http.MethodPost, "/v2/files/zip", params, &result); err != nil {
return nil, err
}
return &result, nil
}
// GetZipStatus gets ZIP job status.
func (c *Client) GetZipStatus(ctx context.Context, jobID string) (*BatchZipResult, error) {
var result BatchZipResult
if err := c.request(ctx, http.MethodGet, "/v2/files/zip/"+jobID, nil, &result); err != nil {
return nil, err
}
return &result, nil
}
// ============================================================================
// Metadata API
// ============================================================================
// GetFileMeta gets all file metadata.
func (c *Client) GetFileMeta(ctx context.Context, filename string) (*FileMeta, error) {
var result FileMeta
if err := c.requestWithQuery(ctx, "/v2/files/meta", map[string]string{"filename": filename}, &result); err != nil {
return nil, err
}
return &result, nil
}
// SetFileMeta sets file metadata.
func (c *Client) SetFileMeta(ctx context.Context, filename string, meta *FileMeta) error {
body := map[string]interface{}{
"filename": filename,
}
if meta.Title != "" {
body["title"] = meta.Title
}
if meta.Description != "" {
body["description"] = meta.Description
}
if meta.Tags != nil {
body["tags"] = meta.Tags
}
if meta.Approved != nil {
body["approved"] = *meta.Approved
}
return c.request(ctx, http.MethodPost, "/v2/files/meta", body, nil)
}
// GetFileTitle gets file title.
func (c *Client) GetFileTitle(ctx context.Context, filename string) (string, error) {
var result struct {
Title string `json:"title"`
}
if err := c.requestWithQuery(ctx, "/v2/files/meta/title", map[string]string{"filename": filename}, &result); err != nil {
return "", err
}
return result.Title, nil
}
// SetFileTitle sets file title.
func (c *Client) SetFileTitle(ctx context.Context, filename, title string) error {
return c.request(ctx, http.MethodPost, "/v2/files/meta/title", map[string]interface{}{"filename": filename, "title": title}, nil)
}
// GetFileDescription gets file description.
func (c *Client) GetFileDescription(ctx context.Context, filename string) (string, error) {
var result struct {
Description string `json:"description"`
}
if err := c.requestWithQuery(ctx, "/v2/files/meta/description", map[string]string{"filename": filename}, &result); err != nil {
return "", err
}
return result.Description, nil
}
// SetFileDescription sets file description.
func (c *Client) SetFileDescription(ctx context.Context, filename, description string) error {
return c.request(ctx, http.MethodPost, "/v2/files/meta/description", map[string]interface{}{"filename": filename, "description": description}, nil)
}
// GetFileTags gets file tags.
func (c *Client) GetFileTags(ctx context.Context, filename string) ([]string, error) {
var result struct {
Tags []string `json:"tags"`
}
if err := c.requestWithQuery(ctx, "/v2/files/meta/tags", map[string]string{"filename": filename}, &result); err != nil {
return nil, err
}
return result.Tags, nil
}
// AddFileTags adds tags to file.
func (c *Client) AddFileTags(ctx context.Context, filename string, tags []string) error {
return c.request(ctx, http.MethodPost, "/v2/files/meta/tags", map[string]interface{}{"filename": filename, "tags": tags}, nil)
}
// RemoveFileTags removes tags from file.
func (c *Client) RemoveFileTags(ctx context.Context, filename string, tags []string) error {
return c.request(ctx, http.MethodDelete, "/v2/files/meta/tags", map[string]interface{}{"filename": filename, "tags": tags}, nil)
}
// GetProductMeta gets product metadata.
func (c *Client) GetProductMeta(ctx context.Context, filename string) (*ProductMeta, error) {
var result ProductMeta
if err := c.requestWithQuery(ctx, "/v2/files/meta/product", map[string]string{"filename": filename}, &result); err != nil {
return nil, err
}
return &result, nil
}
// SetProductMeta sets product metadata.
func (c *Client) SetProductMeta(ctx context.Context, filename string, meta *ProductMeta) error {
body := map[string]interface{}{
"filename": filename,
}
if meta.ID != "" {
body["id"] = meta.ID
}
if meta.Name != "" {
body["name"] = meta.Name
}
if meta.Brand != "" {
body["brand"] = meta.Brand
}
if meta.Category != "" {
body["category"] = meta.Category
}
if meta.SKU != "" {
body["sku"] = meta.SKU
}
return c.request(ctx, http.MethodPost, "/v2/files/meta/product", body, nil)
}
// GetApprovalFlag gets approval flag.
func (c *Client) GetApprovalFlag(ctx context.Context, filename string) (bool, error) {
var result struct {
Approved bool `json:"approved"`
}
if err := c.requestWithQuery(ctx, "/v2/files/meta/approval", map[string]string{"filename": filename}, &result); err != nil {
return false, err
}
return result.Approved, nil
}
// SetApprovalFlag sets approval flag.
func (c *Client) SetApprovalFlag(ctx context.Context, filename string, approved bool) error {
return c.request(ctx, http.MethodPost, "/v2/files/meta/approval", map[string]interface{}{"filename": filename, "approved": approved}, nil)
}
// ============================================================================
// JWT API
// ============================================================================
// GenerateJWT generates JWT protected URL.
func (c *Client) GenerateJWT(ctx context.Context, params *JWTParams) (*JWTResponse, error) {
var result JWTResponse
if err := c.request(ctx, http.MethodPost, "/v2/files/jwt", params, &result); err != nil {
return nil, err
}
return &result, nil
}
// ============================================================================
// Spins/360 API
// ============================================================================
// Spin2Video converts spin to video.
func (c *Client) Spin2Video(ctx context.Context, params *SpinConvertParams) (string, error) {
var result struct {
Filename string `json:"filename"`
}
if err := c.request(ctx, http.MethodPost, "/v2/files/spin2video", params, &result); err != nil {
return "", err
}
return result.Filename, nil
}
// Video2Spin converts video to spin.
func (c *Client) Video2Spin(ctx context.Context, params *Video2SpinParams) (string, error) {
var result struct {
Filename string `json:"filename"`
}
if err := c.request(ctx, http.MethodPost, "/v2/files/video2spin", params, &result); err != nil {
return "", err
}
return result.Filename, nil
}
// ExportSpinToAmazon exports spin to Amazon.
func (c *Client) ExportSpinToAmazon(ctx context.Context, params *ExportSpinParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/spin/export/amazon", params, nil)
}
// ExportSpinToWalmart exports spin to Walmart.
func (c *Client) ExportSpinToWalmart(ctx context.Context, params *ExportSpinParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/spin/export/walmart", params, nil)
}
// ExportSpinToHomeDepot exports spin to Home Depot.
func (c *Client) ExportSpinToHomeDepot(ctx context.Context, params *ExportSpinParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/spin/export/homedepot", params, nil)
}
// ExportSpinToLowes exports spin to Lowe's.
func (c *Client) ExportSpinToLowes(ctx context.Context, params *ExportSpinParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/spin/export/lowes", params, nil)
}
// ExportSpinToGrainger exports spin to Grainger.
func (c *Client) ExportSpinToGrainger(ctx context.Context, params *ExportSpinParams) error {
return c.request(ctx, http.MethodPost, "/v2/files/spin/export/grainger", params, nil)
}
// ============================================================================
// Points of Interest API
// ============================================================================
// GetPointsOfInterest gets points of interest for a file.
func (c *Client) GetPointsOfInterest(ctx context.Context, filename string) ([]PointOfInterest, error) {
var result []PointOfInterest
if err := c.requestWithQuery(ctx, "/v2/files/poi", map[string]string{"filename": filename}, &result); err != nil {
return nil, err
}
return result, nil
}
// SetPointOfInterest sets point of interest.
func (c *Client) SetPointOfInterest(ctx context.Context, filename string, poi *PointOfInterest) error {
body := map[string]interface{}{
"filename": filename,
"name": poi.Name,
"x": poi.X,
"y": poi.Y,
}
if poi.Frame != nil {
body["frame"] = *poi.Frame
}
return c.request(ctx, http.MethodPost, "/v2/files/poi", body, nil)
}
// DeletePointOfInterest deletes point of interest.
func (c *Client) DeletePointOfInterest(ctx context.Context, filename, name string) error {
return c.request(ctx, http.MethodDelete, "/v2/files/poi", map[string]string{"filename": filename, "name": name}, nil)
}
// ============================================================================
// Statistics API
// ============================================================================
// GetHTTPStats gets HTTP transfer statistics.
func (c *Client) GetHTTPStats(ctx context.Context, params *StatsParams) ([]HTTPStats, error) {
var result []HTTPStats
if err := c.requestWithQuery(ctx, "/v2/stats/http", map[string]string{"from": params.From, "to": params.To}, &result); err != nil {
return nil, err
}
return result, nil
}
// GetSpinViewsStats gets spin views statistics (max 5-day range).
func (c *Client) GetSpinViewsStats(ctx context.Context, params *StatsParams) ([]SpinViewStats, error) {
var result []SpinViewStats
if err := c.requestWithQuery(ctx, "/v2/stats/spins/views", map[string]string{"from": params.From, "to": params.To}, &result); err != nil {
return nil, err
}
return result, nil
}
// GetStorageStats gets storage statistics.
func (c *Client) GetStorageStats(ctx context.Context, params *StatsParams) ([]StorageStats, error) {
var result []StorageStats
if err := c.requestWithQuery(ctx, "/v2/stats/storage", map[string]string{"from": params.From, "to": params.To}, &result); err != nil {
return nil, err
}
return result, nil
}
// Helper function to create bool pointer
func BoolPtr(b bool) *bool {
return &b
}