-
Notifications
You must be signed in to change notification settings - Fork 1
/
wetransfer.go
583 lines (509 loc) · 15.8 KB
/
wetransfer.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
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
// Download/upload files via wetransfer.com
//
// transfergo is a CLI to download/upload files via wetransfer.com.
//
// It exposes `download' and `upload' subcommands, respectively used to download
// files from a `we.tl' or `wetransfer.com/downloads' URLs and upload files that
// will be shared via emails or link.
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strings"
"sync"
)
const (
WeTransferAPIURL = "https://wetransfer.com/api/v4/transfers"
WeTransferDownloadURL = WeTransferAPIURL + "/%s/download"
WeTransferUploadEmailURL = WeTransferAPIURL + "/email"
WeTransferUploadLinkURL = WeTransferAPIURL + "/link"
WeTransferFilesURL = WeTransferAPIURL + "/%s/files"
WeTransferPartPutURL = WeTransferFilesURL + "/%s/part-put-url"
WeTransferFinalizeMPPURL = WeTransferFilesURL + "/%s/finalize-mpp"
WeTransferFinalizeURL = WeTransferAPIURL + "/%s/finalize"
WeTransferDefaultChunkSize = 5242880
Debug = false
)
type WeRequest struct {
SecurityHash string `json:"security_hash"`
RecipientID string `json:"recipient_id"`
}
type WeDirectLink struct {
DirectLink string `json:"direct_link"`
}
type WeID struct {
ID string `json:"id"`
}
type WeShortenedURL struct {
ShortenedURL string `json:"shortened_url"`
}
type WeURL struct {
RawURL string `json:"url"`
}
type WeUpload struct {
FileNames []string `json:"filenames"`
From string `json:"from,omitempty"`
Message string `json:"message"`
Recipients []string `json:"recipients,omitempty"`
UILanguage string `json:"ui_language"`
}
type WeFile struct {
Name string `json:"name"`
Size int64 `json:"size"`
}
type WeChunk struct {
ChunkCRC uint32 `json:"chunk_crc"`
ChunkNumber int `json:"chunk_number"`
ChunkSize int `json:"chunk_size"`
Retries int `json:"retries"`
}
type WeChunkCount struct {
ChunkCount int `json:"chunk_count"`
}
// DefaultClient is the default Client and is used by Put, and Options.
var DefaultClient = &http.Client{}
// GetDirectLink returns the download URL (AKA `direct_link') as a str.
//
// Given a wetransfer.com download URL download return the downloadable URL.
//
// The URL should be of the form `https://we.tl/' or
// `https://wetransfer.com/downloads/'. If it is a short URL (i.e. `we.tl')
// the redirect is followed in order to retrieve the corresponding
// `wetransfer.com/downloads/' URL.
//
// The following type of URLs are supported:
// - `https://we.tl/<short_url_id>`:
// received via link upload, via email to the sender and printed by
// `upload` action
// - `https://wetransfer.com/<transfer_id>/<security_hash>`:
// directly not shared in any ways but the short URLs actually redirect to
// them
// - `https://wetransfer.com/<transfer_id>/<recipient_id>/<security_hash>`:
// received via email by recipients when the files are shared via email
// upload
func GetDirectLink(rawURL string) (string, error) {
if strings.HasPrefix(rawURL, "https://we.tl/") {
response, err := http.Head(rawURL)
if err != nil {
return "", err
}
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("GetDirectLink: Error occurs while processing HEAD request: %s, response: %s\n", rawURL, responseDump)
}
return "", errors.New(response.Status)
}
rawURL = response.Request.URL.String()
}
path := strings.Replace(rawURL, "https://wetransfer.com/downloads/", "", 1)
params := strings.Split(path, "/")
transferID, recipientID, securityHash := "", "", ""
if len(params) == 2 {
transferID, securityHash = params[0], params[1]
} else if len(params) == 3 {
transferID, recipientID, securityHash = params[0], params[1], params[2]
}
j := &WeRequest{securityHash, recipientID}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return "", err
}
if Debug {
log.Printf("GetDirectLink: Generated json data: %s\n", b.String())
}
response, err := http.Post(
fmt.Sprintf(WeTransferDownloadURL, transferID),
"application/json; charset=utf-8",
b,
)
if err != nil {
return "", err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
// TODO {"message":"No download access to this Transfer"}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("GetDirectLink: Error occurs while processing POST request: %s %s\n", rawURL, responseDump)
}
return "", errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("GetDirectLink: Received body while processing POST request: %s %s\n", rawURL, responseDump)
}
result := &WeDirectLink{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return "", err
}
return result.DirectLink, nil
}
// PrepareEmailUpload returns the parsed JSON response.
//
// Given a list of filenames, message a sender and recipients prepare for
// the email upload.
func PrepareEmailUpload(fileNames []string, message string, sender string, recipients []string) (*WeID, error) {
j := &WeUpload{fileNames, sender, message, recipients, "en"}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return nil, err
}
if Debug {
log.Printf("PrepareEmailUpload: Generated json data: %s\n", b.String())
}
response, err := http.Post(
WeTransferUploadEmailURL,
"application/json; charset=utf-8",
b,
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareEmailUpload: Error occurs while processing POST request: %s\n", responseDump)
}
return nil, errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareEmailUpload: Received body while processing POST request: %s\n", responseDump)
}
result := &WeID{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
// PrepareLinkUpload returns the parsed JSON response.
//
// Given a list of filenames and a message prepare for the link upload.
func PrepareLinkUpload(fileNames []string, message string) (*WeID, error) {
j := &WeUpload{
FileNames: fileNames,
Message: message,
UILanguage: "en",
}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return nil, err
}
if Debug {
log.Printf("PrepareLinkUpload: Generated json data: %s\n", b.String())
}
response, err := http.Post(
WeTransferUploadLinkURL,
"application/json; charset=utf-8",
b,
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareLinkUpload: Error occurs while processing POST request: %s\n", responseDump)
}
return nil, errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareLinkUpload: Received body while processing POST request: %s\n", responseDump)
}
result := &WeID{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
// PrepareFileUpload returns the parsed JSON response.
//
// Given a transfer_id and file prepare it for the upload.
func PrepareFileUpload(transferID string, filePath string) (*WeID, error) {
fileStat, err := os.Stat(filePath)
if err != nil {
return nil, err
}
j := &WeFile{filepath.Base(filePath), fileStat.Size()}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return nil, err
}
if Debug {
log.Printf("PrepareFileUpload: Generated json data: %s\n", b.String())
}
response, err := http.Post(
fmt.Sprintf(WeTransferFilesURL, transferID),
"application/json; charset=utf-8",
b,
)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareFileUpload: Error occurs while processing POST request: %s\n", responseDump)
}
return nil, errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("PrepareFileUpload: Received body while processing POST request: %s\n", responseDump)
}
result := &WeID{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
// FinalizeUpload returns the parsed JSON response.
//
// Given a transfer_id finalize the upload.
func FinalizeUpload(transferID string) (*WeShortenedURL, error) {
req, err := http.NewRequest(http.MethodPut, fmt.Sprintf(WeTransferFinalizeURL, transferID), nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
response, err := DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("FinalizeUpload: Error occurs while processing PUT request: %s\n", responseDump)
}
return nil, errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("FinalizeUpload: Received body while processing PUT request: %s\n", responseDump)
}
result := &WeShortenedURL{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return nil, err
}
return result, nil
}
// UploadChunks uploads file partially.
//
// Given a transfer_id, file_id and file upload it.
func UploadChunks(transferID string, fileID string, filePath string, defaultChunkSize int) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
fileStat, err := os.Stat(filePath)
if err != nil {
return err
}
fileSize := int(fileStat.Size())
reader := bufio.NewReader(file)
chunk := make([]byte, defaultChunkSize)
chunkNumber, totalChunkSize := 0, 0
for {
fmt.Printf(
"\rtransferred %v / %v bytes (%.2f%%)",
totalChunkSize,
fileSize,
100*(float64(totalChunkSize)/float64(fileSize)),
)
chunkSize, err := reader.Read(chunk)
totalChunkSize += chunkSize
if err == io.EOF || chunkSize == 0 {
break
} else if err != nil {
return err
}
chunkNumber++
j := &WeChunk{crc32.ChecksumIEEE(chunk[:chunkSize]), chunkNumber, chunkSize, 0}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return err
}
if Debug {
log.Printf("UploadChunks: Generated json data: %s\n", b.String())
}
response, err := http.Post(
fmt.Sprintf(WeTransferPartPutURL, transferID, fileID),
"application/json; charset=utf-8",
b,
)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Error occurs while processing POST request: %s\n", responseDump)
}
return errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Received body while processing POST request: %s\n", responseDump)
}
result := &WeURL{}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return err
}
response.Body.Close()
req, err := http.NewRequest(http.MethodOptions, result.RawURL, nil)
if err != nil {
return err
}
req.Header.Set("Origin", "https://wetransfer.com")
req.Header.Set("Access-Control-Request-Method", "PUT")
response, err = DefaultClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Error occurs while processing OPTIONS request: %s\n", responseDump)
}
return errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Received body while processing OPTIONS request: %s, status: %s\n", responseDump, response.Status)
}
response.Body.Close()
req, err = http.NewRequest(http.MethodPut, result.RawURL, bytes.NewBuffer(chunk[:chunkSize]))
if err != nil {
return err
}
response, err = DefaultClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Error occurs while processing PUT request: %s\n", responseDump)
}
return errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Received body while processing PUT request: %s\n", responseDump)
}
response.Body.Close()
}
j := &WeChunkCount{chunkNumber}
b := bytes.NewBuffer(nil)
if err := json.NewEncoder(b).Encode(j); err != nil {
return err
}
if Debug {
log.Printf("UploadChunks: Generated json data: %s\n", b.String())
}
req, err := http.NewRequest(http.MethodPut, fmt.Sprintf(WeTransferFinalizeMPPURL, transferID, fileID), b)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
response, err := DefaultClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Error occurs while processing PUT request: %s\n", responseDump)
}
return errors.New(response.Status)
}
if Debug {
responseDump, _ := httputil.DumpResponse(response, true)
log.Printf("UploadChunks: Received body while processing PUT request: %s\n", responseDump)
}
return nil
}
// UploadFile returns the short URL of the transfer on success.
//
// Given a list of files upload them and return the corresponding URL.
//
// Also accepts optional parameters:
// - `message': message used as a description of the transfer
// - `sender': email address used to receive an ACK if the upload is
// successfull. For every download by the recipients an email
// will be also sent
// - `recipients': list of email addresses of recipients. When the upload
// succeed every recipients will receive an email with a link
//
// If both sender and recipient parameters are passed the email upload will be
// used. Otherwise, the link upload will be used.
func UploadFile(filePaths []string, fileNames []string, message string, sender string, recipients []string, workers int) (*WeShortenedURL, error) {
transferID := ""
if sender != "" && len(recipients) > 0 {
// email upload
result, err := PrepareEmailUpload(fileNames, message, sender, recipients)
if err != nil {
return nil, err
}
transferID = result.ID
} else {
// link upload
result, err := PrepareLinkUpload(fileNames, message)
if err != nil {
return nil, err
}
transferID = result.ID
}
var wg sync.WaitGroup
// TODO goroutine termination and error handling
// If any of the goroutine fails, return that first error immediately,
// and stop all goroutine
chErr := make(chan error)
for i, filePath := range filePaths {
wg.Add(1)
go func(filePath string) {
defer wg.Done()
result, err := PrepareFileUpload(transferID, filePath)
if err != nil {
chErr <- err
return
}
fileID := result.ID
err = UploadChunks(transferID, fileID, filePath, WeTransferDefaultChunkSize)
if err != nil {
chErr <- err
return
}
}(filePath)
if (i+1)%workers == 0 {
wg.Wait()
}
}
wg.Wait()
result, err := FinalizeUpload(transferID)
if err != nil {
return nil, err
}
return result, nil
}