-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfiles.go
354 lines (274 loc) · 9.04 KB
/
files.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
// Copyright 2024 qbee.io
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
)
const filePath = "/api/v2/file"
// UploadFile a file to the file-manager.
// path must start with a slash (/)
func (cli *Client) UploadFile(ctx context.Context, path, name string, reader io.Reader) error {
return cli.UploadFileReplace(ctx, path, name, false, reader)
}
// UploadFileReplace a file to the file-manager if replace is set to true
func (cli *Client) UploadFileReplace(ctx context.Context, path, name string, replace bool, reader io.Reader) error {
buf := new(bytes.Buffer)
multipartWriter := multipart.NewWriter(buf)
partHeaders := make(textproto.MIMEHeader)
partHeaders.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, name))
partHeaders.Set("Content-Type", "")
part, err := multipartWriter.CreatePart(partHeaders)
if err != nil {
return err
}
if _, err = io.Copy(part, reader); err != nil {
return err
}
if part, err = multipartWriter.CreateFormField("path"); err != nil {
return err
}
if _, err = part.Write([]byte(path)); err != nil {
return err
}
if part, err = multipartWriter.CreateFormField("replace"); err != nil {
return err
}
if _, err = part.Write([]byte(fmt.Sprintf("%t", replace))); err != nil {
return err
}
if err = multipartWriter.Close(); err != nil {
return err
}
requestURL := cli.baseURL + filePath
var request *http.Request
if request, err = http.NewRequestWithContext(ctx, http.MethodPost, requestURL, buf); err != nil {
return err
}
request.Header.Add("Content-Type", multipartWriter.FormDataContentType())
request.Header.Set("Authorization", "Bearer "+cli.authToken)
var response *http.Response
if response, err = cli.DoWithRefresh(request); err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
var responseBody []byte
if responseBody, err = io.ReadAll(response.Body); err != nil {
return fmt.Errorf("error reading response body: %w", err)
}
if len(responseBody) > 0 {
return ParseErrorResponse(responseBody)
}
return fmt.Errorf("got an http error with no body: %d", response.StatusCode)
}
return nil
}
const fileMetadataPath = "/api/v2/file/metadata"
// GetFileMetadata returns the metadata for the given file.
func (cli *Client) GetFileMetadata(ctx context.Context, filePath string) (*File, error) {
path := fileMetadataPath + "?path=" + filePath
file := new(File)
if err := cli.Call(ctx, http.MethodGet, path, nil, file); err != nil {
return nil, err
}
return file, nil
}
type renameRequest struct {
// Path to the file to rename.
Path string `json:"path"`
// New name of the file. If set, the NewPath field should be empty.
Name string `json:"name"`
// NewPath of the file. If set, the Name field should be empty.
NewPath string `json:"newPath"`
}
// RenameFile in the file-manager.
func (cli *Client) RenameFile(ctx context.Context, path, name, newPath string) error {
req := &renameRequest{
Path: path,
Name: name,
NewPath: newPath,
}
return cli.Call(ctx, http.MethodPatch, filePath, req, nil)
}
// DeleteFile deletes a file.
func (cli *Client) DeleteFile(ctx context.Context, name string) error {
path := filePath
body := map[string]string{
"path": name,
}
return cli.Call(ctx, http.MethodDelete, path, body, nil)
}
// DownloadFile from the file-manager.
// Returns a ReadCloser that must be closed after use.
func (cli *Client) DownloadFile(ctx context.Context, name string) (io.ReadCloser, error) {
requestURL := cli.baseURL + filePath + "?path=" + name
request, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
if err != nil {
return nil, err
}
request.Header.Set("Authorization", "Bearer "+cli.authToken)
var response *http.Response
if response, err = cli.DoWithRefresh(request); err != nil {
return nil, err
}
if response.StatusCode >= http.StatusBadRequest {
defer response.Body.Close()
var responseBody []byte
if responseBody, err = io.ReadAll(response.Body); err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
if len(responseBody) > 0 {
return nil, ParseErrorResponse(responseBody)
}
return nil, fmt.Errorf("got an http error with no body: %d", response.StatusCode)
}
return response.Body, nil
}
const fileCreateDirPath = "/api/v2/file/createdir"
type createDirectoryRequest struct {
Path string `json:"path"`
Name string `json:"name"`
}
// CreateDirectory creates a directory with the given name in the given path.
func (cli *Client) CreateDirectory(ctx context.Context, path, name string) error {
req := &createDirectoryRequest{
Path: path,
Name: name,
}
return cli.Call(ctx, http.MethodPost, fileCreateDirPath, req, nil)
}
// File represents a file in the file-manager.
type File struct {
Name string `json:"name"`
Extension string `json:"extension"`
Mime string `json:"mime"`
Size int `json:"size"`
Created int64 `json:"created"`
IsDir bool `json:"is_dir"`
Path string `json:"path"`
Digest string `json:"digest"`
User struct {
ID string `json:"user_id"`
} `json:"user"`
}
// FilesListResponse is a response from the file-manager containing a list of files.
type FilesListResponse struct {
Items []File `json:"items"`
Total int `json:"total"`
}
const fileListPath = "/api/v2/files"
// ListSearch defines search parameters for ListQuery.
type ListSearch struct {
// Name - file name to search for (partial-match).
Name string `json:"name"`
// Path - file path to search for (partial-match).
Path string `json:"path"`
}
const (
// SortDirectionAsc returns the files sorted in ascending order.
SortDirectionAsc = "asc"
// SortDirectionDesc returns the files sorted in descending order.
SortDirectionDesc = "desc"
)
// ListQuery defines query parameters for FileList.
type ListQuery struct {
// Path defines path to the directory to list files in.
// If path is empty and:
// - search is empty - show files from the root directory
// - search is not empty - search in ALL files
// Else, if path is not empty and:
// - search is empty - show files from that directory
// - search is not empty - search in that directory only
Path string
Search ListSearch
// SortField defines field used to sort, 'name' by default.
// Supported sort fields:
// - name
// - size
// - extension
// - created
SortField string
// SortDirection defines sort direction, 'asc' by default.
SortDirection string
// ItemsPerPage defines maximum number of records in result, default 50, max 1000
ItemsPerPage int
// Offset defines offset of the first record in result, default 0
Offset int
}
// String returns string representation of CommitListQuery which can be used as query string.
func (q ListQuery) String() (string, error) {
values := make(url.Values)
if q.Path != "" {
values.Set("path", q.Path)
}
searchQueryJSON, err := json.Marshal(q.Search)
if err != nil {
return "", err
}
values.Set("search", string(searchQueryJSON))
if q.SortField != "" {
values.Set("sort_field", q.SortField)
}
if q.SortDirection != "" {
values.Set("sort_direction", q.SortDirection)
}
if q.ItemsPerPage != 0 {
values.Set("items_per_page", fmt.Sprintf("%d", q.ItemsPerPage))
}
if q.Offset != 0 {
values.Set("offset", fmt.Sprintf("%d", q.Offset))
}
return values.Encode(), nil
}
// ListFiles returns a list of files in the file-manager.
func (cli *Client) ListFiles(ctx context.Context, query ListQuery) (*FilesListResponse, error) {
response := new(FilesListResponse)
requestQueryParameters, err := query.String()
if err != nil {
return nil, fmt.Errorf("failed to encode query: %w", err)
}
requestPath := fileListPath + "?" + requestQueryParameters
if err = cli.Call(ctx, http.MethodGet, requestPath, nil, response); err != nil {
return nil, err
}
return response, nil
}
const fileStatsPath = "/api/v2/file/stats"
// Stats represents the statistics of file manager for a company.
type Stats struct {
// CountFiles is the number of files in the file-manager.
CountFiles int64 `json:"count_files"`
// Quota is the allocated storage space in MB.
Quota int64 `json:"quota"`
// Used is the used storage space in MB.
Used float64 `json:"used"`
}
// FileStats returns file-manager statistics.
func (cli *Client) FileStats(ctx context.Context) (*Stats, error) {
stats := new(Stats)
if err := cli.Call(ctx, http.MethodGet, fileStatsPath, nil, stats); err != nil {
return nil, err
}
return stats, nil
}