-
Notifications
You must be signed in to change notification settings - Fork 2
/
fetch.go
95 lines (83 loc) · 2.28 KB
/
fetch.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
package hlsdl
import (
"bytes"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"time"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/grafov/m3u8"
"github.com/sunshineplan/chrome"
"github.com/sunshineplan/gohttp"
"github.com/sunshineplan/useragent"
)
var ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
func DefaultUserAgent() string { return ua }
func init() {
ua = useragent.UserAgent(ua)
SetAgent(ua)
}
func LoadM3U8MediaPlaylist(file string) (*url.URL, *m3u8.MediaPlaylist, error) {
f, err := os.Open(file)
if err != nil {
return nil, nil, err
}
playlist, _, err := m3u8.DecodeFrom(f, false)
if err != nil {
return nil, nil, err
}
return parse(&url.URL{Host: file}, playlist)
}
func FetchM3U8MediaPlaylist(u *url.URL) (*url.URL, *m3u8.MediaPlaylist, error) {
resp, err := gohttp.Get(u.String(), nil)
if err != nil {
return nil, nil, err
}
if resp.StatusCode != 200 {
return nil, nil, fmt.Errorf("no StatusOK response from %s", u)
}
var r io.Reader
playlist, _, err := m3u8.DecodeFrom(bytes.NewReader(resp.Bytes()), false)
if err != nil {
slog.Debug("Analyzing " + u.String())
r, u, err = fetchURL(u.String())
if err != nil {
return nil, nil, err
}
slog.Debug("Found " + u.String())
playlist, _, err = m3u8.DecodeFrom(r, false)
if err != nil {
return nil, nil, err
}
}
return parse(u, playlist)
}
func fetchURL(address string) (io.Reader, *url.URL, error) {
c := chrome.Headless().UserAgent(ua).DisableAutomationControlled()
if _, _, err := c.WithTimeout(15 * time.Second); err != nil {
return nil, nil, err
}
defer c.Close()
if err := c.EnableFetch(func(ev *fetch.EventRequestPaused) bool {
return ev.ResourceType == network.ResourceTypeImage ||
ev.ResourceType == network.ResourceTypeStylesheet ||
ev.ResourceType == network.ResourceTypeMedia
}); err != nil {
return nil, nil, err
}
done := c.ListenEvent(chrome.URLContains(".m3u8"), "GET", true)
if err := chromedp.Run(c, chromedp.Navigate(address)); err != nil {
return nil, nil, err
}
select {
case <-c.Done():
return nil, nil, c.Err()
case e := <-done:
u, _ := url.Parse(e.Response.Response.URL)
return bytes.NewReader(e.Bytes), u, nil
}
}