internal/providers/anipub/validate.go

270 lines · 7849 bytes

12 symbols in this file
  1package anipub
  2
  3import (
  4	"fmt"
  5	"io"
  6	"net/http"
  7	"net/url"
  8	"strconv"
  9	"strings"
 10
 11	"github.com/wraient/curd/internal/curdhost"
 12)
 13
 14// decoySegmentMarkers identify ad/decoy segments that the megap.kotocdn.site
 15// CDN injects into resolved HLS playlists. These segments are 1x1 PNGs (or
 16// 302 redirects to them) served from ByteDance ad infrastructure; mpv can
 17// never decode them, so playback never starts and the player sits on its idle
 18// "Drop files or URLs to play here." screen.
 19var decoySegmentMarkers = []string{
 20	"ibyteimg.com",
 21	"byteimg.com",
 22	"ad-site-i18n",
 23}
 24
 25// maxPlaylistBytes bounds how much of a manifest we download during validation.
 26const maxPlaylistBytes = 2 << 20
 27
 28// isMegaplayCDNHost reports whether the stream is hosted by the megaplay CDN,
 29// which is the only CDN this validation is scoped to.
 30func isMegaplayCDNHost(host string) bool {
 31	host = strings.ToLower(strings.TrimSpace(host))
 32	return host == "kotocdn.site" || host == "megap.kotocdn.site" || strings.HasSuffix(host, ".kotocdn.site")
 33}
 34
 35// validateResolvedStream inspects a resolved anipub stream URL before it is
 36// handed to the media player. When the megaplay CDN is serving an ad-injected
 37// decoy playlist (or a fully decoy one), an error is returned so the caller
 38// can fall back to another provider instead of opening an idle mpv window.
 39func validateResolvedStream(rawURL string) error {
 40	streamURL, err := url.Parse(strings.TrimSpace(rawURL))
 41	if err != nil || streamURL.Scheme == "" || streamURL.Host == "" {
 42		return fmt.Errorf("invalid anipub stream url %q", rawURL)
 43	}
 44	if !isMegaplayCDNHost(streamURL.Host) {
 45		return nil
 46	}
 47
 48	v := &hlsStreamValidator{
 49		client:   curdhost.HTTPClient(),
 50		referrer: megaplayBaseURL + "/",
 51	}
 52
 53	masterBody, err := v.fetch(streamURL.String())
 54	if err != nil {
 55		return fmt.Errorf("anipub stream manifest fetch failed: %w", err)
 56	}
 57	if !strings.Contains(masterBody, "#EXTM3U") {
 58		return fmt.Errorf("anipub stream manifest %q is not an HLS playlist", rawURL)
 59	}
 60
 61	mediaURL, err := selectMediaPlaylistURL(streamURL, masterBody)
 62	if err != nil {
 63		return err
 64	}
 65	mediaBody, err := v.fetch(mediaURL)
 66	if err != nil {
 67		return fmt.Errorf("anipub stream media playlist fetch failed: %w", err)
 68	}
 69
 70	segments := parsePlaylistSegments(mediaBody)
 71	if len(segments) == 0 {
 72		return fmt.Errorf("anipub stream %q has no media segments", rawURL)
 73	}
 74
 75	decoyCount := 0
 76	for _, segment := range segments {
 77		if isDecoySegmentURI(segment) {
 78			decoyCount++
 79		}
 80	}
 81	if decoyCount == len(segments) {
 82		return fmt.Errorf("anipub stream %q is an ad-injected decoy: all %d segments are ad/decoy content", rawURL, len(segments))
 83	}
 84	if decoyRatio := float64(decoyCount) / float64(len(segments)); decoyRatio >= 0.5 {
 85		return fmt.Errorf("anipub stream %q is an ad-injected decoy: %d/%d segments are ad/decoy content", rawURL, decoyCount, len(segments))
 86	}
 87
 88	// The first non-decoy segment may still redirect to ad/decoy content, so
 89	// probe its magic bytes before trusting the playlist.
 90	for _, segment := range segments {
 91		if isDecoySegmentURI(segment) {
 92			continue
 93		}
 94		if data := v.fetchRange(segment, 0, 15); looksLikeDecoySegment(data) {
 95			return fmt.Errorf("anipub stream %q first media segment is not video content", rawURL)
 96		}
 97		break
 98	}
 99
100	return nil
101}
102
103// hlsStreamValidator fetches manifests and probe bytes for a stream.
104type hlsStreamValidator struct {
105	client   *http.Client
106	referrer string
107}
108
109func (v *hlsStreamValidator) fetch(rawURL string) (string, error) {
110	if v.client == nil {
111		return "", fmt.Errorf("http client not configured")
112	}
113	req, err := http.NewRequest(http.MethodGet, rawURL, nil)
114	if err != nil {
115		return "", err
116	}
117	req.Header.Set("User-Agent", userAgent)
118	req.Header.Set("Referer", v.referrer)
119	req.Header.Set("Accept", "application/vnd.apple.mpegurl, application/x-mpegURL, */*")
120
121	resp, err := v.client.Do(req)
122	if err != nil {
123		return "", err
124	}
125	defer resp.Body.Close()
126
127	if !curdhost.HTTPStatusOK(resp.StatusCode) {
128		body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
129		return "", curdhost.HTTPStatusError("megaplay hls manifest", resp.StatusCode, body)
130	}
131	body, err := io.ReadAll(io.LimitReader(resp.Body, maxPlaylistBytes))
132	if err != nil {
133		return "", err
134	}
135	return string(body), nil
136}
137
138// fetchRange requests the first few bytes of a segment so its magic bytes can
139// be inspected. Errors are swallowed: an unavailable probe must not reject a
140// stream that mpv could still play.
141func (v *hlsStreamValidator) fetchRange(rawURL string, start, end int) []byte {
142	if v.client == nil {
143		return nil
144	}
145	req, err := http.NewRequest(http.MethodGet, rawURL, nil)
146	if err != nil {
147		return nil
148	}
149	req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
150	req.Header.Set("User-Agent", userAgent)
151	req.Header.Set("Referer", v.referrer)
152
153	resp, err := v.client.Do(req)
154	if err != nil {
155		return nil
156	}
157	defer resp.Body.Close()
158	if !curdhost.HTTPStatusOK(resp.StatusCode) {
159		return nil
160	}
161
162	buf := make([]byte, end-start+1)
163	n, _ := io.ReadFull(resp.Body, buf)
164	return buf[:n]
165}
166
167// selectMediaPlaylistURL picks the highest-bandwidth variant from a master
168// playlist, or returns the master URL itself when it is a media playlist.
169func selectMediaPlaylistURL(masterURL *url.URL, body string) (string, error) {
170	if !strings.Contains(body, "#EXT-X-STREAM-INF") {
171		return masterURL.String(), nil
172	}
173
174	bestBandwidth := -1
175	bestURI := ""
176	lines := strings.Split(body, "\n")
177	for i := 0; i < len(lines); i++ {
178		line := strings.TrimSpace(lines[i])
179		if !strings.HasPrefix(line, "#EXT-X-STREAM-INF") {
180			continue
181		}
182		bandwidth := parseBandwidth(line)
183		if bandwidth <= bestBandwidth {
184			continue
185		}
186		for j := i + 1; j < len(lines); j++ {
187			next := strings.TrimSpace(lines[j])
188			if next == "" || strings.HasPrefix(next, "#") {
189				continue
190			}
191			bestBandwidth = bandwidth
192			bestURI = next
193			break
194		}
195	}
196	if bestURI == "" {
197		return "", fmt.Errorf("no variant playlist found in master playlist")
198	}
199	ref, err := url.Parse(bestURI)
200	if err != nil {
201		return "", fmt.Errorf("invalid variant playlist uri %q: %w", bestURI, err)
202	}
203	resolved := masterURL.ResolveReference(ref)
204	return resolved.String(), nil
205}
206
207func parseBandwidth(infLine string) int {
208	upper := strings.ToUpper(infLine)
209	idx := strings.Index(upper, "BANDWIDTH=")
210	if idx < 0 {
211		return 0
212	}
213	rest := upper[idx+len("BANDWIDTH="):]
214	if comma := strings.IndexByte(rest, ','); comma >= 0 {
215		rest = rest[:comma]
216	}
217	value, err := strconv.Atoi(strings.TrimSpace(rest))
218	if err != nil {
219		return 0
220	}
221	return value
222}
223
224// parsePlaylistSegments extracts media segment URIs from a playlist body.
225func parsePlaylistSegments(body string) []string {
226	var segments []string
227	for _, raw := range strings.Split(body, "\n") {
228		line := strings.TrimSpace(raw)
229		if line == "" || strings.HasPrefix(line, "#") {
230			continue
231		}
232		segments = append(segments, line)
233	}
234	return segments
235}
236
237func isDecoySegmentURI(raw string) bool {
238	lower := strings.ToLower(raw)
239	for _, marker := range decoySegmentMarkers {
240		if strings.Contains(lower, marker) {
241			return true
242		}
243	}
244	return false
245}
246
247// looksLikeDecoySegment reports whether probe bytes look like an image, an
248// HTML error page, or other non-video content instead of an HLS media segment.
249func looksLikeDecoySegment(data []byte) bool {
250	if len(data) < 4 {
251		return false
252	}
253	if data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G' {
254		return true
255	}
256	if data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
257		return true
258	}
259	if string(data[:4]) == "GIF8" {
260		return true
261	}
262	if len(data) >= 12 && string(data[:4]) == "RIFF" && string(data[8:12]) == "WEBP" {
263		return true
264	}
265	lower := strings.ToLower(string(data))
266	if strings.HasPrefix(lower, "<") || strings.Contains(lower, "<html") || strings.Contains(lower, "<!doctype") {
267		return true
268	}
269	return false
270}