-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
415 lines (340 loc) · 10.5 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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/Brawl345/get-dmax-links/structs"
"github.com/hellflame/argparse"
"github.com/xuri/excelize/v2"
)
const ApiBase = "https://eu1-prod.disco-api.com"
const ShowInfoUrl = ApiBase + "/content/videos/?include=primaryChannel,primaryChannel.images,show,show.images,genres,tags,images,contentPackages&sort=-seasonNumber,-episodeNumber&filter[show.id]=%d&filter[videoType]=EPISODE&page[number]=%d&page[size]=100"
const PlayerUrl = ApiBase + "/playback/v3/videoPlaybackInfo"
const UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/127.0"
const DeviceInfo = "STONEJS/1 (Unknown/Unknown; Unknown/Unknown; Unknown)"
const DiscoClient = "Alps:HyogaPlayer:0.0.0"
const MaxAttempts = 6
var REALMS = []string{"dmaxde", "hgtv", "tlcde"}
func getValidFileName(showName string) string {
re := regexp.MustCompile(`[^-\w.]`)
newName := strings.TrimSpace(showName)
newName = strings.ReplaceAll(newName, " ", "_")
newName = re.ReplaceAllString(newName, "")
return newName
}
func fileExists(fileName string) bool {
if _, err := os.Stat(fileName); err == nil {
return true
}
return false
}
func contains(stack []string, needle string) bool {
for _, v := range stack {
if v == needle {
return true
}
}
return false
}
func doRequest(url string, token string, result any) error {
client := http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
if token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("X-Device-Info", DeviceInfo)
req.Header.Set("X-Disco-Client", DiscoClient)
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode == 429 {
return &structs.RateLimitError{}
}
if resp.StatusCode != 200 {
return fmt.Errorf("got HTTP status code %d", resp.StatusCode)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.New("could not read body")
}
if err := json.Unmarshal(body, &result); err != nil {
return errors.New("can not unmarshal JSON")
}
return nil
}
func doPostRequest(url string, token string, input any, result any) error {
var reqBody io.Reader
jsonData, err := json.Marshal(input)
if err != nil {
return err
}
reqBody = bytes.NewBuffer(jsonData)
client := http.Client{}
req, err := http.NewRequest("POST", url, reqBody)
if err != nil {
return err
}
if token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("X-Device-Info", DeviceInfo)
req.Header.Set("X-Disco-Client", DiscoClient)
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode == 429 {
return &structs.RateLimitError{}
}
if resp.StatusCode != 200 {
return fmt.Errorf("got HTTP status code %d", resp.StatusCode)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.New("could not read body")
}
if err := json.Unmarshal(body, &result); err != nil {
return errors.New("can not unmarshal JSON")
}
return nil
}
func getAuthorizationToken(realm string) (string, error) {
var result structs.GetAuthorizationTokenResponse
err := doRequest(
fmt.Sprintf("%s/token?realm=%s", ApiBase, realm),
"",
&result,
)
if err != nil {
return "", err
}
if result.Data.Attributes.Token == "" {
return "", errors.New("got empty token")
}
return result.Data.Attributes.Token, nil
}
func getShow(showId int, token string, page int) (structs.GetShowResponse, error) {
var result structs.GetShowResponse
err := doRequest(
fmt.Sprintf(ShowInfoUrl, showId, page),
token,
&result,
)
if err != nil {
return structs.GetShowResponse{}, err
}
if result.Meta.TotalPages == 0 || len(result.Data) == 0 {
return structs.GetShowResponse{}, errors.New("show does not exist")
}
return result, nil
}
func getVideoUrl(token, episodeId string) (string, error) {
request := &structs.GetVideoUrlRequest{
DeviceInfo: structs.DeviceInfo{
AdBlocker: false,
DrmSupported: false,
HdrCapabilities: []string{"SDR"},
HwDecodingCapabilities: []string{},
SoundCapabilities: []string{"STEREO"},
},
WisteriaProperties: struct{}{},
VideoId: episodeId,
}
var result structs.GetVideoUrlResponse
err := doPostRequest(
PlayerUrl,
token,
request,
&result,
)
if err != nil {
return "", err
}
if len(result.Data.Attributes.Streaming) == 0 {
return "", errors.New("no streaming URL found")
}
return result.Data.Attributes.Streaming[0].Url, nil
}
func parseArgs() (structs.Flags, error) {
var flags structs.Flags
parser := argparse.NewParser("get-dmax-links", `Gets direct links for DMAX and Discovery series.
You need the showId of the show you want to get the links for. See the README:
https://github.com/Brawl345/Get-DMAX-Links`, &argparse.ParserConfig{
WithHint: true,
AddShellCompletion: true,
})
flags.ShowId = parser.Int("id", "showId", &argparse.Option{
Required: true,
Positional: true,
Help: "showId of the series (see README)",
})
flags.Realm = parser.String("r", "realm", &argparse.Option{
Default: REALMS[0],
Help: fmt.Sprintf("Site to download from. Must be one of: %s", strings.Join(REALMS, ", ")),
})
flags.Episode = parser.Int("e", "episode", &argparse.Option{
Default: "0",
Help: "Episode of season to get (0 = all) - season MUST be set!",
})
flags.Season = parser.Int("s", "season", &argparse.Option{
Default: "0",
Help: "Season to get (0 = all)",
})
if err := parser.Parse(nil); err != nil {
return structs.Flags{}, err
}
if !contains(REALMS, *flags.Realm) {
return structs.Flags{}, fmt.Errorf("unknown Realm. Must be one of: %s", strings.Join(REALMS, ", "))
}
if *flags.Episode > 0 && *flags.Season == 0 {
return structs.Flags{}, errors.New("need season when downloading episodes")
}
if *flags.Episode < 0 || *flags.Season < 0 {
return structs.Flags{}, errors.New("episode/season must be > 0")
}
return flags, nil
}
func main() {
flags, err := parseArgs()
if err != nil {
fmt.Print(err.Error())
os.Exit(0)
}
log.Printf("Getting Authorization token for '%s'...", *flags.Realm)
token, err := getAuthorizationToken(*flags.Realm)
if err != nil {
log.Fatalln(err)
}
log.Println("Loading show data...")
result, err := getShow(*flags.ShowId, token, 1)
if err != nil {
log.Fatalln(err)
}
if result.Meta.TotalPages > 1 {
log.Println(" More than 100 videos, need to get more pages...")
for i := 1; i < result.Meta.TotalPages; i++ {
log.Printf(" Loading page %d...", i+1)
moreData, err := getShow(*flags.ShowId, token, i+1)
if err != nil {
log.Println("Couldn't get page, skipping...")
continue
}
result.Data = append(result.Data, moreData.Data...)
}
}
show := structs.Show{}
for _, inc := range result.Included {
if inc.Type == "show" {
show = inc.Attributes
}
}
if show.Name == "" {
show.Name = "Unknown show"
}
log.Printf("=> %s", show.Name)
var episodes []structs.Episode
if *flags.Season == 0 && *flags.Episode == 0 { // Get EVERYTHING
episodes = append(episodes, result.Data...)
} else if *flags.Season > 0 && *flags.Episode == 0 { // Get whole season
for _, episode := range result.Data {
if episode.Attributes.Season == *flags.Season {
episodes = append(episodes, episode)
}
}
if len(episodes) == 0 {
log.Fatalln("This season does not exist")
}
} else { // Single episode
for _, episode := range result.Data {
if episode.Attributes.Season == *flags.Season && episode.Attributes.Episode == *flags.Episode {
episodes = append(episodes, episode)
}
}
if len(episodes) == 0 {
log.Fatalln("Episode not found")
}
}
if len(episodes) == 0 {
log.Fatalln("No episodes found")
}
xlsx := excelize.NewFile()
currentRow := 1
worksheet := "Sheet1"
xlsx.SetCellValue(worksheet, fmt.Sprintf("A%d", currentRow), "Name")
xlsx.SetCellValue(worksheet, fmt.Sprintf("B%d", currentRow), "Description")
xlsx.SetCellValue(worksheet, fmt.Sprintf("C%d", currentRow), "File name")
xlsx.SetCellValue(worksheet, fmt.Sprintf("D%d", currentRow), "Link")
xlsx.SetCellValue(worksheet, fmt.Sprintf("E%d", currentRow), "Command")
style, _ := xlsx.NewStyle(&excelize.Style{
Font: &excelize.Font{
Bold: true,
},
})
xlsx.SetCellStyle(worksheet, "A1", "E1", style)
currentRow += 1
length := len(episodes)
rateLimitError := &structs.RateLimitError{}
for num, episode := range episodes {
log.Printf("Getting link %d of %d: %s", num+1, length, episode.Attributes.Name)
var filename string
if episode.Attributes.Season == 0 && episode.Attributes.Episode == 0 {
filename = fmt.Sprintf("%s - %s", show.Name, episode.Attributes.Name)
} else if episode.Attributes.Season == 0 && episode.Attributes.Episode != 0 {
filename = fmt.Sprintf("%s - E%02d - %s", show.Name, episode.Attributes.Episode, episode.Attributes.Name)
} else {
filename = fmt.Sprintf("%s - S%02dE%02d - %s", show.Name, episode.Attributes.Season, episode.Attributes.Episode, episode.Attributes.Name)
}
xlsx.SetCellValue(worksheet, fmt.Sprintf("A%d", currentRow), episode.Attributes.Name)
xlsx.SetCellValue(worksheet, fmt.Sprintf("B%d", currentRow), episode.Attributes.Description)
xlsx.SetCellValue(worksheet, fmt.Sprintf("C%d", currentRow), filename)
for attempt := 0; attempt <= MaxAttempts; attempt++ {
if attempt == MaxAttempts {
log.Println("Couldn't get episode")
currentRow += 1
break
}
url, err := getVideoUrl(token, episode.Id)
if err != nil {
if errors.As(err, &rateLimitError) {
waittime := (attempt + 1) * 5
log.Printf("Got rate-limited, waiting %d seconds (attempt %d of %d)", waittime, attempt+1, MaxAttempts)
time.Sleep(time.Duration(waittime) * time.Second)
} else {
log.Println(err)
}
continue
}
xlsx.SetCellValue(worksheet, fmt.Sprintf("D%d", currentRow), url)
xlsx.SetCellValue(worksheet, fmt.Sprintf("E%d", currentRow), fmt.Sprintf("yt-dlp \"%s\" -o \"%s.mp4\"", url, filename))
currentRow += 1
break
}
}
xlsxname := getValidFileName(show.Name) + ".xlsx"
fileNum := 0
for fileExists(xlsxname) {
fileNum += 1
xlsxname = fmt.Sprintf("%s-%d.xlsx", getValidFileName(show.Name), fileNum)
}
if err := xlsx.SaveAs(xlsxname); err != nil {
log.Fatalln(err)
}
log.Printf("=> Saved to %s", xlsxname)
}