-
Notifications
You must be signed in to change notification settings - Fork 1
/
uploadToB2.go
257 lines (214 loc) · 7.03 KB
/
uploadToB2.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
package helpers
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
)
type B2AuthResp struct {
AbsoluteMinimumPartSize int `json:"absoluteMinimumPartSize"`
AccountId string `json:"accountId"`
Allowed struct {
BucketId string `json:"bucketId"`
BucketName string `json:"bucketName"`
Capabilities []string `json:"capabilities"`
NamePrefix string `json:"namePrefix"`
} `json:"allowed"`
ApiUrl string `json:"apiUrl"`
AuthorizationToken string `json:"authorizationToken"`
DownloadUrl string `json:"downloadUrl"`
RecommendedPartSize int `json:"recommendedPartSize"`
S3ApiUrl string `json:"s3ApiUrl"`
}
type B2UpUrlResp struct {
BucketId string `json:"bucketId"`
UploadUrl string `json:"uploadUrl"`
AuthorizationToken string `json:"authorizationToken"`
}
type B2UploadResp struct {
FileId string `json:"fileId"`
FileName string `json:"fileName"`
AccountId string `json:"accountId"`
BucketId string `json:"bucketId"`
ContentLength int `json:"contentLength"`
ContentSha1 string `json:"contentSha1"`
ContentType string `json:"contentType"`
FileInfo struct {
Author string `json:"author"`
} `json:"fileInfo"`
ServerSideEncryption struct {
Algorithm string `json:"algorithm"`
Mode string `json:"mode"`
} `json:"serverSideEncryption"`
}
type B2Error struct {
Status int `json:"status"`
Code string `json:"code"`
Message string `json:"message"`
}
type B2AuthTokens struct {
ApiUrl string
AuthorizationToken string
DownloadUrl string
RecommendedPartSize int
}
type B2UploadTokens struct {
Endpoint string
AuthToken string
DownloadUrl string
}
// Authorize B2 bucket for upload.
// DOCS: https://www.backblaze.com/b2/docs/b2_authorize_account.html
func AuthTokens() (B2AuthTokens, error) {
keyID, err := GetKeys("APP_KEY_ID")
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens]%w", err)
}
key, err := GetKeys("APP_KEY")
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens]%w", err)
}
token := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", keyID, key)))
client := &http.Client{}
req, err := http.NewRequest("GET", "https://api.backblazeb2.com/b2api/v2/b2_authorize_account", nil)
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens][http.NewRequest]: %w", err)
}
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", token))
resp, err := client.Do(req)
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens][client.Do]: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var b2Error B2Error
err := json.NewDecoder(resp.Body).Decode(&b2Error)
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens][json.NewDecoder](b2Error): %w", err)
}
msg := b2Error.Message
if msg == "" {
msg = fmt.Sprintf("%d - %s", b2Error.Status, b2Error.Code)
}
return B2AuthTokens{}, fmt.Errorf("[AuthTokens][b2Error]: %s", msg)
}
var results B2AuthResp
err = json.NewDecoder(resp.Body).Decode(&results)
if err != nil {
return B2AuthTokens{}, fmt.Errorf("[AuthTokens][json.NewDecoder](results): %w", err)
}
AuthTokens := B2AuthTokens{
ApiUrl: results.ApiUrl,
AuthorizationToken: results.AuthorizationToken,
DownloadUrl: results.DownloadUrl,
RecommendedPartSize: results.RecommendedPartSize,
}
return AuthTokens, nil
}
// Get B2 endpoint for upload.
// DOCS: https://www.backblaze.com/b2/docs/b2_get_upload_url.html
func GetUploadUrl() (B2UploadTokens, error) {
authData, err := AuthTokens()
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl]%w", err)
}
bucketID, err := GetKeys("BUCKET_ID")
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl]%w", err)
}
payload := map[string]string{"bucketId": bucketID}
payloadBytes, _ := json.Marshal(payload)
req, err := http.NewRequest("POST", fmt.Sprintf("%s/b2api/v1/b2_get_upload_url", authData.ApiUrl), bytes.NewBuffer(payloadBytes))
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl][http.NewRequest]: %w", err)
}
req.Header.Set("Authorization", authData.AuthorizationToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl][client.Do]: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var b2Error B2Error
err := json.NewDecoder(resp.Body).Decode(&b2Error)
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl][json.NewDecoder](b2Error): %w", err)
}
msg := b2Error.Message
if msg == "" {
msg = fmt.Sprintf("%d - %s", b2Error.Status, b2Error.Code)
}
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl][b2Error]: %s", msg)
}
var results B2UpUrlResp
err = json.NewDecoder(resp.Body).Decode(&results)
if err != nil {
return B2UploadTokens{}, fmt.Errorf("[GetUploadUrl][json.NewDecoder](results): %w", err)
}
uploadTokens := B2UploadTokens{
Endpoint: results.UploadUrl,
AuthToken: results.AuthorizationToken,
DownloadUrl: authData.DownloadUrl,
}
return uploadTokens, nil
}
// Upload file to B2 bucket.
// DOCS: https://www.backblaze.com/b2/docs/b2_upload_file.html
func UploadToB2(data []byte, name, fileType string) (string, error) {
authData, err := GetUploadUrl()
if err != nil {
return "", fmt.Errorf("[UploadToB2]%w", err)
}
hasher := sha1.New()
hasher.Write(data)
hash := fmt.Sprintf("%x", hasher.Sum(nil))
if fileType == "" {
fileType = "b2/x-auto"
}
req, err := http.NewRequest("POST", authData.Endpoint, bytes.NewReader(data))
if err != nil {
return "", fmt.Errorf("[UploadToB2][http.NewRequest]: %w", err)
}
req.Header.Set("Authorization", authData.AuthToken)
req.Header.Set("X-Bz-File-Name", name)
req.Header.Set("Content-Type", fileType)
req.Header.Set("Content-Length", strconv.Itoa(len(data)))
req.Header.Set("X-Bz-Content-Sha1", hash)
req.Header.Set("X-Bz-Info-Author", "rivendell")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("[UploadToB2][client.Do]: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var b2Error B2Error
err := json.NewDecoder(resp.Body).Decode(&b2Error)
if err != nil {
return "", fmt.Errorf("[UploadToB2][json.NewDecoder](b2Error): %w", err)
}
msg := b2Error.Message
if msg == "" {
msg = fmt.Sprintf("%d - %s", b2Error.Status, b2Error.Code)
}
return "", fmt.Errorf("[UploadToB2][b2Error]: %s", msg)
}
var results B2UploadResp
err = json.NewDecoder(resp.Body).Decode(&results)
if err != nil {
return "", fmt.Errorf("[UploadToB2][json.NewDecoder](results): %w", err)
}
bucketName, err := GetKeys("BUCKET_NAME")
if err != nil {
return "", fmt.Errorf("[UploadToB2]%w", err)
}
log.Printf("[UploadToB2]: Uploaded '%s'.\n", results.FileName)
publicURL := fmt.Sprintf("%s/file/%s/%s", authData.DownloadUrl, bucketName, results.FileName)
return publicURL, nil
}