-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbyr.go
84 lines (78 loc) · 1.92 KB
/
byr.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
log "github.com/tominescu/double-golang/simplelog"
)
var gCurlTimeMap = make(map[string]int64)
func byrApiHandler(w http.ResponseWriter, r *http.Request) {
log.Info("Request URL:%s", r.URL)
url := "http://tv.byr.cn:8888" + r.URL.Path
log.Debug("Curl url: %s", url)
resp, err := http.Get(url)
if err != nil {
http.Error(w, err.Error(), 503)
return
}
defer resp.Body.Close()
if strings.HasSuffix(r.URL.Path, "index.m3u8") {
go CurlCount(r.URL.Path)
}
MyCopy(w, resp.Body)
}
func CurlCount(path string) {
ts := gCurlTimeMap[path]
now := time.Now().Unix()
if now-ts >= 25 {
gCurlTimeMap[path] = now
url := fmt.Sprintf("http://tv.byr.cn/player_count/res.gif?play_url=http://tv.byr.cn:8888%s&refer=http://tv.byr.cn/tv-show&title=BYR-IPTV", path)
log.Debug("Curl count url: %s", url)
resp, err := http.Get(url)
if err != nil {
log.Warn("curl count url: %s error: %s", url, err)
} else {
resp.Body.Close()
}
if len(gCurlTimeMap) > 1000 {
gCurlTimeMap = make(map[string]int64)
}
}
}
func byrHandler(w http.ResponseWriter, r *http.Request) {
log.Info("Request URL:%s", r.URL)
err := r.ParseForm()
if err != nil {
http.Error(w, http.StatusText(503), 503)
return
}
id := r.Form.Get("id")
if id == "" {
http.Error(w, http.StatusText(503), 503)
return
}
url := "http://tv.byr.cn/tv-show-detail/" + id
resp, err := http.Get(url)
if err != nil {
http.Error(w, err.Error(), 503)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), 503)
return
}
re := regexp.MustCompile(`http://.*/index.m3u8`)
hls := re.Find(body)
if len(hls) < 8 {
http.Error(w, "Cant't find m3u8 url", 503)
return
}
dst := strings.Replace(string(hls), "http://tv.byr.cn:8888", "http://"+r.Host, 1)
w.Header().Set("Location", dst)
http.Error(w, http.StatusText(302), 302)
}