internal/providers/anipub/megaplay.go

157 lines · 4550 bytes

8 symbols in this file
  1package anipub
  2
  3import (
  4	"crypto/aes"
  5	"crypto/cipher"
  6	"encoding/base64"
  7	"encoding/json"
  8	"fmt"
  9	"net/url"
 10	"regexp"
 11	"strconv"
 12	"strings"
 13
 14	"github.com/wraient/curd/internal/providers"
 15)
 16
 17var (
 18	videoPathRE = regexp.MustCompile(`/video/(\d+)/(sub|dub)`)
 19	dataIDRE    = regexp.MustCompile(`data-id="(\d+)"`)
 20)
 21
 22func resolveMegaplayStream(videoLink, mode string) (string, string, error) {
 23	videoLink = strings.TrimSpace(videoLink)
 24	if videoLink == "" {
 25		return "", "", fmt.Errorf("empty video link")
 26	}
 27
 28	embedID, linkMode, err := parseVideoLink(videoLink)
 29	if err != nil {
 30		return "", "", err
 31	}
 32	mode = providers.NormalizeTranslationType(mode)
 33	if mode == "dub" {
 34		linkMode = "dub"
 35	} else {
 36		linkMode = "sub"
 37	}
 38
 39	streamPage := fmt.Sprintf("%s/stream/s-2/%s/%s", megaplayBaseURL, embedID, linkMode)
 40	html, err := fetchString(streamPage, baseURL+"/")
 41	if err != nil {
 42		return "", "", err
 43	}
 44
 45	dataID := dataIDRE.FindStringSubmatch(html)
 46	if len(dataID) < 2 {
 47		return "", "", fmt.Errorf("megaplay data-id not found")
 48	}
 49
 50	sourcesURL := fmt.Sprintf("%s/stream/getSources?id=%s", megaplayBaseURL, dataID[1])
 51	var payload megaplaySourcesResponse
 52	if err := fetchJSON(sourcesURL, streamPage, &payload); err != nil {
 53		return "", "", err
 54	}
 55
 56	streamURL := strings.TrimSpace(payload.Sources.File)
 57	if streamURL == "" && strings.TrimSpace(payload.Enc) != "" {
 58		// Megaplay moved the stream URL into an AES-CBC encrypted "enc"
 59		// field. Decrypt it the same way their web player does.
 60		decrypted, err := decryptMegaplayEnc(payload.Enc)
 61		if err != nil {
 62			return "", "", fmt.Errorf("decrypt megaplay stream: %w", err)
 63		}
 64		streamURL = decrypted
 65	}
 66	if streamURL == "" {
 67		return "", "", fmt.Errorf("megaplay stream url missing")
 68	}
 69	subtitle := pickSubtitleTrack(payload, mode)
 70	return streamURL, subtitle, nil
 71}
 72
 73// megaplayEncKey and megaplayEncIV mirror the AES-CBC parameters in
 74// megaplay.buzz's web player (lib/newclient.min.js). If they rotate the
 75// bundle, this breaks and the values need re-extracting from the new JS.
 76var (
 77	megaplayEncKey = []byte("i?LMTAx0Q6,:}50U")
 78	megaplayEncIV  = []byte("W0;27ToaUpl_P%'c")
 79)
 80
 81// decryptMegaplayEnc decrypts the "enc" field of a megaplay getSources
 82// response and returns the stream file URL inside.
 83func decryptMegaplayEnc(enc string) (string, error) {
 84	s := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(enc), "-", "+"), "_", "/")
 85	if m := len(s) % 4; m != 0 {
 86		s += strings.Repeat("=", 4-m)
 87	}
 88	ciphertext, err := base64.StdEncoding.DecodeString(s)
 89	if err != nil {
 90		return "", fmt.Errorf("decode megaplay payload: %w", err)
 91	}
 92	if len(ciphertext) == 0 || len(ciphertext)%aes.BlockSize != 0 {
 93		return "", fmt.Errorf("invalid megaplay payload length %d", len(ciphertext))
 94	}
 95	key := make([]byte, 32)
 96	copy(key, megaplayEncKey)
 97	block, err := aes.NewCipher(key)
 98	if err != nil {
 99		return "", err
100	}
101	plain := make([]byte, len(ciphertext))
102	cipher.NewCBCDecrypter(block, megaplayEncIV).CryptBlocks(plain, ciphertext)
103	pad := int(plain[len(plain)-1])
104	if pad <= 0 || pad > aes.BlockSize || pad > len(plain) {
105		return "", fmt.Errorf("invalid megaplay padding")
106	}
107	plain = plain[:len(plain)-pad]
108
109	var payload struct {
110		File string `json:"file"`
111	}
112	if err := json.Unmarshal(plain, &payload); err != nil {
113		return "", fmt.Errorf("parse decrypted megaplay payload: %w", err)
114	}
115	if strings.TrimSpace(payload.File) == "" {
116		return "", fmt.Errorf("decrypted megaplay payload has no file")
117	}
118	return strings.TrimSpace(payload.File), nil
119}
120
121func parseVideoLink(videoLink string) (embedID, mode string, err error) {
122	parsed, err := url.Parse(videoLink)
123	if err != nil {
124		return "", "", fmt.Errorf("parse video link: %w", err)
125	}
126	matches := videoPathRE.FindStringSubmatch(parsed.Path)
127	if len(matches) < 3 {
128		return "", "", fmt.Errorf("unsupported video link %q", videoLink)
129	}
130	embedID = matches[1]
131	mode = matches[2]
132	if _, err := strconv.Atoi(embedID); err != nil {
133		return "", "", fmt.Errorf("invalid embed id %q", embedID)
134	}
135	return embedID, mode, nil
136}
137
138func pickSubtitleTrack(payload megaplaySourcesResponse, mode string) string {
139	if mode == "dub" {
140		return ""
141	}
142	var fallback string
143	for _, track := range payload.Tracks {
144		file := strings.TrimSpace(track.File)
145		if file == "" || !strings.EqualFold(strings.TrimSpace(track.Kind), "captions") {
146			continue
147		}
148		label := strings.ToLower(strings.TrimSpace(track.Label))
149		if track.Default || strings.Contains(label, "english") {
150			return file
151		}
152		if fallback == "" {
153			fallback = file
154		}
155	}
156	return fallback
157}