-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.go
1684 lines (1578 loc) · 42.2 KB
/
main.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
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 main
import (
"bufio"
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/alexflint/go-arg"
"github.com/dustin/go-humanize"
"github.com/grafov/m3u8"
)
const (
devKey = "x7f54tgbdyc64y656thy47er4"
clientId = "Eg7HuH873H65r5rt325UytR5429"
layout = "01/02/2006 15:04:05"
userAgent = "NugsNet/3.26.724 (Android; 7.1.2; Asus; ASUS_Z01QD; Scale/2.0; en)"
userAgentTwo = "nugsnetAndroid"
authUrl = "https://id.nugs.net/connect/token"
streamApiBase = "https://streamapi.nugs.net/"
subInfoUrl = "https://subscriptions.nugs.net/api/v1/me/subscriptions"
userInfoUrl = "https://id.nugs.net/connect/userinfo"
playerUrl = "https://play.nugs.net/"
sanRegexStr = `[\/:*?"><|]`
chapsFileFname = "chapters_nugs_dl_tmp.txt"
durRegex = `Duration: ([\d:.]+)`
bitrateRegex = `[\w]+(?:_(\d+)k_v\d+)`
)
var (
jar, _ = cookiejar.New(nil)
client = &http.Client{Jar: jar}
)
var regexStrings = [11]string{
`^https://play.nugs.net/release/(\d+)$`,
`^https://play.nugs.net/#/playlists/playlist/(\d+)$`,
`^https://play.nugs.net/library/playlist/(\d+)$`,
`(^https://2nu.gs/[a-zA-Z\d]+$)`,
`^https://play.nugs.net/#/videos/artist/\d+/.+/(\d+)$`,
`^https://play.nugs.net/artist/(\d+)(?:/albums|/latest|)$`,
`^https://play.nugs.net/livestream/(\d+)/exclusive$`,
`^https://play.nugs.net/watch/livestreams/exclusive/(\d+)$`,
`^https://play.nugs.net/#/my-webcasts/\d+-(\d+)-\d+-\d+$`,
`^https://www.nugs.net/on/demandware.store/Sites-NugsNet-Site/d`+
`efault/(?:Stash-QueueVideo|NugsVideo-GetStashVideo)\?([a-zA-Z0-9=%&-]+$)`,
`^https://play.nugs.net/library/webcast/(\d+)$`,
}
var qualityMap = map[string]Quality{
".alac16/": {Specs: "16-bit / 44.1 kHz ALAC", Extension: ".m4a", Format: 1},
".flac16/": {Specs: "16-bit / 44.1 kHz FLAC", Extension: ".flac", Format: 2},
// .mqa24/ must be above .flac?
".mqa24/": {Specs: "24-bit / 48 kHz MQA", Extension: ".flac", Format: 3},
".flac?": {Specs: "FLAC", Extension: ".flac", Format: 2},
".s360/": {Specs: "360 Reality Audio", Extension: ".mp4", Format: 4},
".aac150/": {Specs: "150 Kbps AAC", Extension: ".m4a", Format: 5},
".m4a?": {Specs: "AAC", Extension: ".m4a", Format: 5},
".m3u8?": {Extension: ".m4a", Format: 6},
}
var resolveRes = map[int]string{
1: "480",
2: "720",
3: "1080",
4: "1440",
5: "2160",
}
var trackFallback = map[int]int{
1: 2,
2: 5,
3: 2,
4: 3,
}
var resFallback = map[string]string{
"720": "480",
"1080": "720",
"1440": "1080",
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
var speed int64 = 0
n := len(p)
wc.Downloaded += int64(n)
percentage := float64(wc.Downloaded) / float64(wc.Total) * float64(100)
wc.Percentage = int(percentage)
toDivideBy := time.Now().UnixMilli() - wc.StartTime
if toDivideBy != 0 {
speed = int64(wc.Downloaded) / toDivideBy * 1000
}
fmt.Printf("\r%d%% @ %s/s, %s/%s ", wc.Percentage, humanize.Bytes(uint64(speed)),
humanize.Bytes(uint64(wc.Downloaded)), wc.TotalStr)
return n, nil
}
func handleErr(errText string, err error, _panic bool) {
errString := errText + "\n" + err.Error()
if _panic {
panic(errString)
}
fmt.Println(errString)
}
func wasRunFromSrc() bool {
buildPath := filepath.Join(os.TempDir(), "go-build")
return strings.HasPrefix(os.Args[0], buildPath)
}
func getScriptDir() (string, error) {
var (
ok bool
err error
fname string
)
runFromSrc := wasRunFromSrc()
if runFromSrc {
_, fname, _, ok = runtime.Caller(0)
if !ok {
return "", errors.New("failed to get script filename")
}
} else {
fname, err = os.Executable()
if err != nil {
return "", err
}
}
return filepath.Dir(fname), nil
}
func readTxtFile(path string) ([]string, error) {
var lines []string
f, err := os.OpenFile(path, os.O_RDONLY, 0755)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" {
lines = append(lines, line)
}
}
if scanner.Err() != nil {
return nil, scanner.Err()
}
return lines, nil
}
func contains(lines []string, value string) bool {
for _, line := range lines {
if strings.EqualFold(line, value) {
return true
}
}
return false
}
func processUrls(urls []string) ([]string, error) {
var (
processed []string
txtPaths []string
)
for _, _url := range urls {
if strings.HasSuffix(_url, ".txt") && !contains(txtPaths, _url) {
txtLines, err := readTxtFile(_url)
if err != nil {
return nil, err
}
for _, txtLine := range txtLines {
if !contains(processed, txtLine) {
txtLine = strings.TrimSuffix(txtLine, "/")
processed = append(processed, txtLine)
}
}
txtPaths = append(txtPaths, _url)
} else {
if !contains(processed, _url) {
_url = strings.TrimSuffix(_url, "/")
processed = append(processed, _url)
}
}
}
return processed, nil
}
func parseCfg() (*Config, error) {
cfg, err := readConfig()
if err != nil {
return nil, err
}
args := parseArgs()
if args.Format != -1 {
cfg.Format = args.Format
}
if args.VideoFormat != -1 {
cfg.VideoFormat = args.VideoFormat
}
if !(cfg.Format >= 1 && cfg.Format <= 5) {
return nil, errors.New("track Format must be between 1 and 5")
}
if !(cfg.VideoFormat >= 1 && cfg.VideoFormat <= 5) {
return nil, errors.New("video format must be between 1 and 5")
}
cfg.WantRes = resolveRes[cfg.VideoFormat]
if args.OutPath != "" {
cfg.OutPath = args.OutPath
}
if cfg.OutPath == "" {
cfg.OutPath = "Nugs downloads"
}
if cfg.Token != "" {
cfg.Token = strings.TrimPrefix(cfg.Token, "Bearer ")
}
if cfg.UseFfmpegEnvVar {
cfg.FfmpegNameStr = "ffmpeg"
} else {
cfg.FfmpegNameStr = "./ffmpeg"
}
cfg.Urls, err = processUrls(args.Urls)
if err != nil {
fmt.Println("Failed to process URLs.")
return nil, err
}
cfg.ForceVideo = args.ForceVideo
cfg.SkipVideos = args.SkipVideos
cfg.SkipChapters = args.SkipChapters
return cfg, nil
}
func readConfig() (*Config, error) {
data, err := ioutil.ReadFile("config.json")
if err != nil {
return nil, err
}
var obj Config
err = json.Unmarshal(data, &obj)
if err != nil {
return nil, err
}
return &obj, nil
}
func parseArgs() *Args {
var args Args
arg.MustParse(&args)
return &args
}
func makeDirs(path string) error {
err := os.MkdirAll(path, 0755)
return err
}
func fileExists(path string) (bool, error) {
f, err := os.Stat(path)
if err == nil {
return !f.IsDir(), nil
} else if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func sanitise(filename string) string {
san := regexp.MustCompile(sanRegexStr).ReplaceAllString(filename, "_")
return strings.TrimSuffix(san, "\t")
}
func auth(email, pwd string) (string, error) {
data := url.Values{}
data.Set("client_id", clientId)
data.Set("grant_type", "password")
data.Set("scope", "openid profile email nugsnet:api nugsnet:legacyapi offline_access")
data.Set("username", email)
data.Set("password", pwd)
req, err := http.NewRequest(http.MethodPost, authUrl, strings.NewReader(data.Encode()))
if err != nil {
return "", err
}
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
do, err := client.Do(req)
if err != nil {
return "", err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return "", errors.New(do.Status)
}
var obj Auth
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return "", err
}
return obj.AccessToken, nil
}
func getUserInfo(token string) (string, error) {
req, err := http.NewRequest(http.MethodGet, userInfoUrl, nil)
if err != nil {
return "", err
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("User-Agent", userAgent)
do, err := client.Do(req)
if err != nil {
return "", err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return "", errors.New(do.Status)
}
var obj UserInfo
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return "", err
}
return obj.Sub, nil
}
func getSubInfo(token string) (*SubInfo, error) {
req, err := http.NewRequest(http.MethodGet, subInfoUrl, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("User-Agent", userAgent)
do, err := client.Do(req)
if err != nil {
return nil, err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return nil, errors.New(do.Status)
}
var obj SubInfo
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return nil, err
}
return &obj, nil
}
func getPlan(subInfo *SubInfo) (string, bool) {
if !reflect.ValueOf(subInfo.Plan).IsZero() {
return subInfo.Plan.Description, false
} else {
return subInfo.Promo.Plan.Description, true
}
}
func parseTimestamps(start, end string) (string, string) {
startTime, _ := time.Parse(layout, start)
endTime, _ := time.Parse(layout, end)
parsedStart := strconv.FormatInt(startTime.Unix(), 10)
parsedEnd := strconv.FormatInt(endTime.Unix(), 10)
return parsedStart, parsedEnd
}
func parseStreamParams(userId string, subInfo *SubInfo, isPromo bool) *StreamParams {
startStamp, endStamp := parseTimestamps(subInfo.StartedAt, subInfo.EndsAt)
streamParams := &StreamParams{
SubscriptionID: subInfo.LegacySubscriptionID,
SubCostplanIDAccessList: subInfo.Plan.PlanID,
UserID: userId,
StartStamp: startStamp,
EndStamp: endStamp,
}
if isPromo {
streamParams.SubCostplanIDAccessList = subInfo.Promo.Plan.PlanID
} else {
streamParams.SubCostplanIDAccessList = subInfo.Plan.PlanID
}
return streamParams
}
func checkUrl(_url string) (string, int) {
for i, regexStr := range regexStrings {
regex := regexp.MustCompile(regexStr)
match := regex.FindStringSubmatch(_url)
if match != nil {
return match[1], i
}
}
return "", 0
}
func extractLegToken(tokenStr string) (string, string, error) {
payload := strings.SplitN(tokenStr, ".", 3)[1]
decoded, err := base64.RawURLEncoding.DecodeString(payload)
if err != nil {
return "", "", err
}
var obj Payload
err = json.Unmarshal(decoded, &obj)
if err != nil {
return "", "", err
}
return obj.LegacyToken, obj.LegacyUguid, nil
}
func getAlbumMeta(albumId string) (*AlbumMeta, error) {
req, err := http.NewRequest(http.MethodGet, streamApiBase+"api.aspx", nil)
if err != nil {
return nil, err
}
query := url.Values{}
query.Set("method", "catalog.container")
query.Set("containerID", albumId)
query.Set("vdisp", "1")
req.URL.RawQuery = query.Encode()
req.Header.Add("User-Agent", userAgent)
do, err := client.Do(req)
if err != nil {
return nil, err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return nil, errors.New(do.Status)
}
var obj AlbumMeta
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return nil, err
}
return &obj, nil
}
func getPlistMeta(plistId, email, legacyToken string, cat bool) (*PlistMeta, error) {
var path string
if cat {
path = "api.aspx"
} else {
path = "secureApi.aspx"
}
req, err := http.NewRequest(http.MethodGet, streamApiBase+path, nil)
if err != nil {
return nil, err
}
query := url.Values{}
if cat {
query.Set("method", "catalog.playlist")
query.Set("plGUID", plistId)
} else {
query.Set("method", "user.playlist")
query.Set("playlistID", plistId)
query.Set("developerKey", devKey)
query.Set("user", email)
query.Set("token", legacyToken)
}
req.URL.RawQuery = query.Encode()
req.Header.Add("User-Agent", userAgentTwo)
do, err := client.Do(req)
if err != nil {
return nil, err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return nil, errors.New(do.Status)
}
var obj PlistMeta
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return nil, err
}
return &obj, nil
}
func getArtistMeta(artistId string) ([]*ArtistMeta, error) {
var allArtistMeta []*ArtistMeta
offset := 1
query := url.Values{}
query.Set("method", "catalog.containersAll")
query.Set("limit", "100")
query.Set("artistList", artistId)
query.Set("availType", "1")
query.Set("vdisp", "1")
for {
req, err := http.NewRequest(http.MethodGet, streamApiBase+"api.aspx", nil)
if err != nil {
return nil, err
}
query.Set("startOffset", strconv.Itoa(offset))
req.URL.RawQuery = query.Encode()
req.Header.Add("User-Agent", userAgent)
do, err := client.Do(req)
if err != nil {
return nil, err
}
if do.StatusCode != http.StatusOK {
do.Body.Close()
return nil, errors.New(do.Status)
}
var obj ArtistMeta
err = json.NewDecoder(do.Body).Decode(&obj)
do.Body.Close()
if err != nil {
return nil, err
}
retLen := len(obj.Response.Containers)
if retLen == 0 {
break
}
allArtistMeta = append(allArtistMeta, &obj)
offset += retLen
}
return allArtistMeta, nil
}
func getPurchasedManUrl(skuID int, showID, userID, uguID string) (string, error) {
req, err := http.NewRequest(http.MethodGet, streamApiBase+"bigriver/vidPlayer.aspx", nil)
if err != nil {
return "", err
}
query := url.Values{}
query.Set("skuId", strconv.Itoa(skuID))
query.Set("showId", showID)
query.Set("uguid", uguID)
query.Set("nn_userID", userID)
query.Set("app", "1")
req.URL.RawQuery = query.Encode()
req.Header.Add("User-Agent", userAgentTwo)
do, err := client.Do(req)
if err != nil {
return "", err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return "", errors.New(do.Status)
}
var obj PurchasedManResp
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return "", err
}
return obj.FileURL, nil
}
func getStreamMeta(trackId, skuId, format int, streamParams *StreamParams) (string, error) {
req, err := http.NewRequest(http.MethodGet, streamApiBase+"bigriver/subPlayer.aspx", nil)
if err != nil {
return "", err
}
query := url.Values{}
if format == 0 {
query.Set("skuId", strconv.Itoa(skuId))
query.Set("containerID", strconv.Itoa(trackId))
query.Set("chap", "1")
} else {
query.Set("platformID", strconv.Itoa(format))
query.Set("trackID", strconv.Itoa(trackId))
}
query.Set("app", "1")
query.Set("subscriptionID", streamParams.SubscriptionID)
query.Set("subCostplanIDAccessList", streamParams.SubCostplanIDAccessList)
query.Set("nn_userID", streamParams.UserID)
query.Set("startDateStamp", streamParams.StartStamp)
query.Set("endDateStamp", streamParams.EndStamp)
req.URL.RawQuery = query.Encode()
req.Header.Add("User-Agent", userAgentTwo)
do, err := client.Do(req)
if err != nil {
return "", err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return "", errors.New(do.Status)
}
var obj StreamMeta
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return "", err
}
return obj.StreamLink, nil
}
func queryQuality(streamUrl string) *Quality {
for k, v := range qualityMap {
if strings.Contains(streamUrl, k) {
v.URL = streamUrl
return &v
}
}
return nil
}
func downloadTrack(trackPath, _url string) error {
f, err := os.OpenFile(trackPath, os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return err
}
defer f.Close()
req, err := http.NewRequest(http.MethodGet, _url, nil)
if err != nil {
return err
}
req.Header.Add("Referer", playerUrl)
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Range", "bytes=0-")
do, err := client.Do(req)
if err != nil {
return err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK && do.StatusCode != http.StatusPartialContent {
return errors.New(do.Status)
}
totalBytes := do.ContentLength
counter := &WriteCounter{
Total: totalBytes,
TotalStr: humanize.Bytes(uint64(totalBytes)),
StartTime: time.Now().UnixMilli(),
}
_, err = io.Copy(f, io.TeeReader(do.Body, counter))
fmt.Println("")
return err
}
func getTrackQual(quals []*Quality, wantFmt int) *Quality {
for _, quality := range quals {
if quality.Format == wantFmt {
return quality
}
}
return nil
}
func extractBitrate(manUrl string) string {
regex := regexp.MustCompile(bitrateRegex)
match := regex.FindStringSubmatch(manUrl)
if match != nil {
return match[1]
}
return ""
}
func parseHlsMaster(qual *Quality) error {
req, err := client.Get(qual.URL)
if err != nil {
return err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return errors.New(req.Status)
}
playlist, _, err := m3u8.DecodeFrom(req.Body, true)
if err != nil {
return err
}
master := playlist.(*m3u8.MasterPlaylist)
sort.Slice(master.Variants, func(x, y int) bool {
return master.Variants[x].Bandwidth > master.Variants[y].Bandwidth
})
variantUri := master.Variants[0].URI
bitrate := extractBitrate(variantUri)
if bitrate == "" {
return errors.New("no regex match for manifest bitrate")
}
qual.Specs = bitrate + " Kbps AAC"
manBase, q, err := getManifestBase(qual.URL)
if err != nil {
return err
}
qual.URL = manBase + variantUri + q
return nil
}
func getKey(keyUrl string) ([]byte, error) {
req, err := client.Get(keyUrl)
if err != nil {
return nil, err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return nil, errors.New(req.Status)
}
buf := make([]byte, 16)
_, err = io.ReadFull(req.Body, buf)
if err != nil {
return nil, err
}
return buf, nil
}
// func decryptTrack(key, iv []byte, inPath, outPath string) error {
// var stream cipher.Stream
// fmt.Println("Decrypting...")
// in_f, err := os.Open(inPath)
// if err != nil {
// return err
// }
// block, err := aes.NewCipher([]byte(key))
// if err != nil {
// in_f.Close()
// return err
// }
// stream = cipher.NewCTR(block, []byte(iv))
// reader := &cipher.StreamReader{S: stream, R: in_f}
// out_f, err := os.Create(outPath)
// if err != nil {
// in_f.Close()
// return err
// }
// defer out_f.Close()
// _, err = io.Copy(out_f, reader)
// if err != nil {
// in_f.Close()
// return err
// }
// in_f.Close()
// err = os.Remove(inPath)
// if err != nil {
// fmt.Println("Failed to delete encrypted track.")
// }
// return nil
// }
func pkcs5Trimming(data []byte) []byte {
padding := data[len(data)-1]
return data[:len(data)-int(padding)]
}
func decryptTrack(key, iv []byte) ([]byte, error) {
encData, err := os.ReadFile("temp_enc.ts")
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ecb := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(encData))
fmt.Println("Decrypting...")
ecb.CryptBlocks(decrypted, encData)
return decrypted, nil
}
func tsToAac(decData []byte, outPath, ffmpegNameStr string) error {
var errBuffer bytes.Buffer
cmd := exec.Command(ffmpegNameStr, "-i", "pipe:", "-c:a", "copy", outPath)
cmd.Stdin = bytes.NewReader(decData)
cmd.Stderr = &errBuffer
err := cmd.Run()
if err != nil {
errString := fmt.Sprintf("%s\n%s", err, errBuffer.String())
return errors.New(errString)
}
return nil
}
func hlsOnly(trackPath, manUrl, ffmpegNameStr string) error {
req, err := client.Get(manUrl)
if err != nil {
return err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return errors.New(req.Status)
}
playlist, _, err := m3u8.DecodeFrom(req.Body, true)
if err != nil {
return err
}
media := playlist.(*m3u8.MediaPlaylist)
manBase, q, err := getManifestBase(manUrl)
if err != nil {
return err
}
tsUrl := manBase + media.Segments[0].URI + q
key := media.Key
keyBytes, err := getKey(manBase + key.URI)
if err != nil {
return err
}
iv, err := hex.DecodeString(key.IV[2:])
if err != nil {
return err
}
err = downloadTrack("temp_enc.ts", tsUrl)
if err != nil {
return err
}
decData, err := decryptTrack(keyBytes, iv)
if err != nil {
return err
}
err = os.Remove("temp_enc.ts")
if err != nil {
return err
}
err = tsToAac(decData, trackPath, ffmpegNameStr)
return err
}
func checkIfHlsOnly(quals []*Quality) bool {
for _, quality := range quals {
if !strings.Contains(quality.URL, ".m3u8?") {
return false
}
}
return true
}
func processTrack(folPath string, trackNum, trackTotal int, cfg *Config, track *Track, streamParams *StreamParams) error {
origWantFmt := cfg.Format
wantFmt := origWantFmt
var (
quals []*Quality
chosenQual *Quality
)
// Call the stream meta endpoint four times to get all avail formats since the formats can shift.
// This will ensure the right format's always chosen.
for _, i := range [4]int{1, 4, 7, 10} {
streamUrl, err := getStreamMeta(track.TrackID, 0, i, streamParams)
if err != nil {
fmt.Println("failed to get track stream metadata")
return err
} else if streamUrl == "" {
return errors.New("the api didn't return a track stream URL")
}
quality := queryQuality(streamUrl)
if quality == nil {
fmt.Println("The API returned an unsupported format, URL:", streamUrl)
continue
//return errors.New("The API returned an unsupported format.")
}
quals = append(quals, quality)
// if quality.Format == 6 {
// isHlsOnly = true
// break
// }
}
if len(quals) == 0 {
return errors.New("the api didn't return any formats")
}
isHlsOnly := checkIfHlsOnly(quals)
if isHlsOnly {
fmt.Println("HLS-only track. Only AAC is available, tags currently unsupported.")
chosenQual = quals[0]
err := parseHlsMaster(chosenQual)
if err != nil {
return err
}
} else {
for {
chosenQual = getTrackQual(quals, wantFmt)
if chosenQual != nil {
break
} else {
// Fallback quality.
wantFmt = trackFallback[wantFmt]
}
}
if chosenQual == nil {
return errors.New("no track format was chosen")
}
if wantFmt != origWantFmt && origWantFmt != 4 {
fmt.Println("Unavailable in your chosen format.")
}
}
trackFname := fmt.Sprintf(
"%02d. %s%s", trackNum, sanitise(track.SongTitle), chosenQual.Extension,
)
trackPath := filepath.Join(folPath, trackFname)
exists, err := fileExists(trackPath)
if err != nil {
fmt.Println("Failed to check if track already exists locally.")
return err
}
if exists {
fmt.Println("Track already exists locally.")
return nil
}
fmt.Printf(
"Downloading track %d of %d: %s - %s\n", trackNum, trackTotal, track.SongTitle,
chosenQual.Specs,
)
if isHlsOnly {
err = hlsOnly(trackPath, chosenQual.URL, cfg.FfmpegNameStr)
} else {
err = downloadTrack(trackPath, chosenQual.URL)
}
if err != nil {
fmt.Println("Failed to download track.")
return err
}
return nil
}
func album(albumID string, cfg *Config, streamParams *StreamParams, artResp *AlbArtResp) error {
var (
meta *AlbArtResp
tracks []Track
)
if albumID == "" {
meta = artResp
tracks = meta.Songs
} else {
_meta, err := getAlbumMeta(albumID)
if err != nil {
fmt.Println("Failed to get metadata.")
return err
}
meta = _meta.Response
tracks = meta.Tracks
}
trackTotal := len(tracks)
skuID := getVideoSku(meta.Products)
if skuID == 0 && trackTotal < 1 {
return errors.New("release has no tracks or videos")
}
if skuID != 0 {
if cfg.SkipVideos {
fmt.Println("Video-only album, skipped.")
return nil
}
if cfg.ForceVideo || trackTotal < 1 {
return video(albumID, "", cfg, streamParams, meta, false)
}
}
albumFolder := meta.ArtistName + " - " + strings.TrimRight(meta.ContainerInfo, " ")
fmt.Println(albumFolder)
if len(albumFolder) > 120 {
albumFolder = albumFolder[:120]
fmt.Println(
"Album folder name was chopped because it exceeds 120 characters.")
}
albumPath := filepath.Join(cfg.OutPath, sanitise(albumFolder))
err := makeDirs(albumPath)
if err != nil {
fmt.Println("Failed to make album folder.")
return err
}
for trackNum, track := range tracks {
trackNum++
err := processTrack(
albumPath, trackNum, trackTotal, cfg, &track, streamParams)
if err != nil {
handleErr("Track failed.", err, false)
}
}
return nil
}
func getAlbumTotal(meta []*ArtistMeta) int {
var total int
for _, _meta := range meta {
total += len(_meta.Response.Containers)
}
return total
}
func artist(artistId string, cfg *Config, streamParams *StreamParams) error {
meta, err := getArtistMeta(artistId)
if err != nil {
fmt.Println("Failed to get artist metadata.")
return err
}
if len(meta) == 0 {
return errors.New(
"The API didn't return any artist metadata.")