mptv3/main.go
2025-08-23 12:16:04 +03:00

153 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"strings"
"golang.org/x/net/html"
)
type MPVRequest struct {
Command []string `json:"command"`
}
type MPVResponsePlayback struct {
Data float32 `json:"data"`
}
type MPV struct {
cmd *exec.Cmd
socketPath string
}
func NewMPV(streamUrl string, socketPath string) MPV {
return MPV{
cmd: exec.Command("mpv", fmt.Sprintf("--input-ipc-server=%s", socketPath), streamUrl),
socketPath: socketPath,
}
}
func (mpv *MPV) Spawn() error {
mpv.cmd.Stdout = io.Discard
mpv.cmd.Stderr = os.Stderr
return mpv.cmd.Start()
}
func (mpv *MPV) Stop() error {
return mpv.cmd.Process.Kill()
}
func (mpv *MPV) ExecuteIPC(req *MPVRequest) ([]byte, error) {
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqBytes = append(reqBytes, byte('\n'))
conn, err := net.Dial("unix", mpv.socketPath)
if err != nil {
return nil, err
}
defer conn.Close()
_, err = conn.Write(reqBytes)
if err != nil {
return nil, err
}
resBytes := make([]byte, 1024)
n, err := conn.Read(resBytes)
if err != nil {
return nil, err
}
return resBytes[:n], nil
}
func (mpv *MPV) InquirePlayback() (float32, error) {
resBytes, err := mpv.ExecuteIPC(&MPVRequest{
Command: []string{"get_property", "playback-time"},
})
if err != nil {
return 0, err
}
var res MPVResponsePlayback
if err = json.Unmarshal(resBytes, &res); err != nil {
return 0, err
}
return res.Data, nil
}
const PARSE_JSON_OFFSET = 25
func ParseWebMedia(url string) (string, error) {
res, err := http.Get(url)
if err != nil {
return "", err
}
defer res.Body.Close()
scripts := make([]string, 0)
var processNode func(*html.Node)
processNode = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "script" {
if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
scripts = append(scripts, n.FirstChild.Data)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
processNode(c)
}
}
node, err := html.Parse(res.Body)
if err != nil {
return "", err
}
processNode(node)
var streamChannels string
for _, script := range scripts {
if strings.Contains(script, "var streamChannels") {
streamChannels = script
}
}
if streamChannels == "" {
return "", fmt.Errorf("failed to find streamChannels")
}
return streamChannels[25:], err
}
var testUrl string
func main() {
flag.StringVar(&testUrl, "test-url", "", "test url")
flag.Parse()
// mpv := NewMPV(testUrl, "/tmp/mptv3.sock")
// mpv.Spawn()
// defer mpv.Stop()
// for {
// time.Sleep(time.Second * 2)
// _, err := mpv.InquirePlayback()
// fmt.Println(err)
// }
json, _ := ParseWebMedia(testUrl)
fmt.Println(json)
}