internal/providers/anineko/vibeproxy.go
242 lines · 5904 bytes
19 symbols in this file
pngIENDMarkervibeProxyMuvibeProxyServervibeSessionvibeSegmentvibeProxyregisterVibeStreamgetVibeProxyvibeProxy.registervibeProxy.handlevibeProxy.serveMastervibeProxy.serveVariantvibeProxy.serveSegmentrewritePlaylistLinesparseExtInfDurationstripPNGWrapperwritePlaylistrandomSessionIDresetVibeProxyForTest
1package anineko
2
3import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "strconv"
12 "strings"
13 "sync"
14)
15
16var pngIENDMarker = []byte{0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
17
18var (
19 vibeProxyMu sync.Mutex
20 vibeProxyServer *vibeProxy
21)
22
23type vibeSession struct {
24 masterURL string
25 referer string
26 variants map[string][]vibeSegment
27}
28
29type vibeSegment struct {
30 duration float64
31 url string
32}
33
34type vibeProxy struct {
35 baseURL string
36 server *http.Server
37 sessions map[string]*vibeSession
38}
39
40func registerVibeStream(masterURL, referer string) (string, error) {
41 proxy, err := getVibeProxy()
42 if err != nil {
43 return "", err
44 }
45 return proxy.register(masterURL, referer)
46}
47
48func getVibeProxy() (*vibeProxy, error) {
49 vibeProxyMu.Lock()
50 defer vibeProxyMu.Unlock()
51
52 if vibeProxyServer != nil {
53 return vibeProxyServer, nil
54 }
55
56 proxy := &vibeProxy{sessions: map[string]*vibeSession{}}
57 mux := http.NewServeMux()
58 mux.HandleFunc("/stream/", proxy.handle)
59 server := &http.Server{Handler: mux}
60
61 listener, err := net.Listen("tcp", "127.0.0.1:0")
62 if err != nil {
63 return nil, fmt.Errorf("start vibe proxy listener: %w", err)
64 }
65 proxy.server = server
66 proxy.baseURL = "http://" + listener.Addr().String()
67
68 go func() {
69 _ = server.Serve(listener)
70 }()
71
72 vibeProxyServer = proxy
73 return proxy, nil
74}
75
76func (p *vibeProxy) register(masterURL, referer string) (string, error) {
77 id, err := randomSessionID()
78 if err != nil {
79 return "", err
80 }
81 vibeProxyMu.Lock()
82 p.sessions[id] = &vibeSession{
83 masterURL: masterURL,
84 referer: referer,
85 variants: map[string][]vibeSegment{},
86 }
87 vibeProxyMu.Unlock()
88 return p.baseURL + "/stream/" + id + "/master.m3u8", nil
89}
90
91func (p *vibeProxy) handle(w http.ResponseWriter, r *http.Request) {
92 path := strings.TrimPrefix(r.URL.Path, "/stream/")
93 parts := strings.Split(path, "/")
94 if len(parts) < 2 {
95 http.NotFound(w, r)
96 return
97 }
98 sessionID := parts[0]
99
100 vibeProxyMu.Lock()
101 session, ok := p.sessions[sessionID]
102 vibeProxyMu.Unlock()
103 if !ok {
104 http.NotFound(w, r)
105 return
106 }
107
108 switch {
109 case len(parts) == 2 && parts[1] == "master.m3u8":
110 p.serveMaster(w, sessionID, session, parts[1])
111 case len(parts) == 2 && strings.HasSuffix(parts[1], ".m3u8"):
112 p.serveVariant(w, sessionID, session, parts[1])
113 case len(parts) == 4 && parts[2] == "seg":
114 p.serveSegment(w, r, session, parts[1], parts[3])
115 default:
116 http.NotFound(w, r)
117 }
118}
119
120func (p *vibeProxy) serveMaster(w http.ResponseWriter, sessionID string, session *vibeSession, _ string) {
121 body, err := fetchString(session.masterURL, session.referer)
122 if err != nil {
123 http.Error(w, err.Error(), http.StatusBadGateway)
124 return
125 }
126 rewritten := rewritePlaylistLines(body, func(line string) string {
127 line = strings.TrimSpace(line)
128 if line == "" || strings.HasPrefix(line, "#") {
129 return line
130 }
131 return p.baseURL + "/stream/" + sessionID + "/" + line
132 })
133 writePlaylist(w, rewritten)
134}
135
136func (p *vibeProxy) serveVariant(w http.ResponseWriter, sessionID string, session *vibeSession, variantName string) {
137 variantURL := resolvePlaylistURL(session.masterURL, variantName)
138 body, err := fetchString(variantURL, session.referer)
139 if err != nil {
140 http.Error(w, err.Error(), http.StatusBadGateway)
141 return
142 }
143
144 segments := make([]vibeSegment, 0)
145 var currentDuration float64
146 rewritten := rewritePlaylistLines(body, func(line string) string {
147 line = strings.TrimSpace(line)
148 if strings.HasPrefix(line, "#EXTINF:") {
149 currentDuration = parseExtInfDuration(line)
150 return line
151 }
152 if line == "" || strings.HasPrefix(line, "#") {
153 return line
154 }
155 segmentURL := resolvePlaylistURL(variantURL, line)
156 index := len(segments)
157 segments = append(segments, vibeSegment{duration: currentDuration, url: segmentURL})
158 return fmt.Sprintf("%s/stream/%s/%s/seg/%d", p.baseURL, sessionID, variantName, index)
159 })
160
161 vibeProxyMu.Lock()
162 session.variants[variantName] = segments
163 vibeProxyMu.Unlock()
164
165 writePlaylist(w, rewritten)
166}
167
168func (p *vibeProxy) serveSegment(w http.ResponseWriter, r *http.Request, session *vibeSession, variantName, indexText string) {
169 index, err := strconv.Atoi(indexText)
170 if err != nil || index < 0 {
171 http.NotFound(w, r)
172 return
173 }
174
175 vibeProxyMu.Lock()
176 segments := session.variants[variantName]
177 vibeProxyMu.Unlock()
178 if index >= len(segments) {
179 http.NotFound(w, r)
180 return
181 }
182
183 data, err := fetchBytes(segments[index].url, session.referer)
184 if err != nil {
185 http.Error(w, err.Error(), http.StatusBadGateway)
186 return
187 }
188 body := stripPNGWrapper(data)
189 w.Header().Set("Content-Type", "video/mp2t")
190 w.Header().Set("Content-Length", strconv.Itoa(len(body)))
191 _, _ = w.Write(body)
192}
193
194func rewritePlaylistLines(playlist string, mapLine func(string) string) string {
195 lines := strings.Split(strings.ReplaceAll(playlist, "\r\n", "\n"), "\n")
196 for i, line := range lines {
197 lines[i] = mapLine(line)
198 }
199 return strings.Join(lines, "\n")
200}
201
202func parseExtInfDuration(line string) float64 {
203 line = strings.TrimPrefix(strings.TrimSpace(line), "#EXTINF:")
204 if idx := strings.Index(line, ","); idx >= 0 {
205 line = line[:idx]
206 }
207 value, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
208 if err != nil {
209 return 0
210 }
211 return value
212}
213
214func stripPNGWrapper(data []byte) []byte {
215 idx := bytes.Index(data, pngIENDMarker)
216 if idx < 0 {
217 return data
218 }
219 return data[idx+len(pngIENDMarker):]
220}
221
222func writePlaylist(w http.ResponseWriter, body string) {
223 w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
224 _, _ = io.WriteString(w, body)
225}
226
227func randomSessionID() (string, error) {
228 buf := make([]byte, 8)
229 if _, err := rand.Read(buf); err != nil {
230 return "", err
231 }
232 return hex.EncodeToString(buf), nil
233}
234
235func resetVibeProxyForTest() {
236 vibeProxyMu.Lock()
237 defer vibeProxyMu.Unlock()
238 if vibeProxyServer != nil && vibeProxyServer.server != nil {
239 _ = vibeProxyServer.server.Close()
240 }
241 vibeProxyServer = nil
242}