Initial commit
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package m3u8
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
cacheEnkey []byte
|
||||
initOnce sync.Once
|
||||
initErr error
|
||||
)
|
||||
|
||||
// 安全初始化 m3u8 key(文件缺失时不再 panic,交由调用方降级)
|
||||
func initEnkey() {
|
||||
initOnce.Do(func() {
|
||||
data, err := ioutil.ReadFile("conf/m3u8.key")
|
||||
if err != nil {
|
||||
initErr = err
|
||||
return
|
||||
}
|
||||
if len(data) == 0 {
|
||||
initErr = fmt.Errorf("conf/m3u8.key is empty")
|
||||
return
|
||||
}
|
||||
cacheEnkey = data
|
||||
})
|
||||
}
|
||||
|
||||
// Enkey 密匙 key
|
||||
func Enkey(ctx context.Context) (buffer *bytes.Buffer, err error) {
|
||||
initEnkey()
|
||||
if initErr != nil {
|
||||
return nil, initErr
|
||||
}
|
||||
if len(cacheEnkey) == 0 {
|
||||
return nil, fmt.Errorf("m3u8 key not loaded")
|
||||
}
|
||||
buffer = bytes.NewBuffer(cacheEnkey)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package m3u8
|
||||
|
||||
import (
|
||||
//"sz-app-server/pub/common/utils"
|
||||
|
||||
"time"
|
||||
"videoweb/pub/common/utils"
|
||||
|
||||
"github.com/grafov/m3u8"
|
||||
)
|
||||
|
||||
// makeMediaPlayList 根据from,重新生成播放列表
|
||||
func makeMediaPlayList(from *m3u8.MediaPlaylist, cdnDomain string, dirPath string, keyUri string, authKey string) (media *m3u8.MediaPlaylist, err error) {
|
||||
media, err = m3u8.NewMediaPlaylist(0, from.Count())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
base := utils.JoinUrlPath(cdnDomain, dirPath)
|
||||
now := time.Now()
|
||||
|
||||
for _, segment := range from.Segments {
|
||||
if segment == nil {
|
||||
continue
|
||||
}
|
||||
sg := new(m3u8.MediaSegment)
|
||||
sg.URI = utils.JoinUrlPath(base, segment.URI)
|
||||
if len(authKey) > 0 {
|
||||
//生成鉴权url
|
||||
urlPath := utils.JoinUrlPath(dirPath, segment.URI)
|
||||
urlAuth := generateUrlAuth(now, urlPath, authKey)
|
||||
sg.URI = sg.URI + urlAuth
|
||||
}
|
||||
sg.Title = segment.Title
|
||||
sg.Duration = segment.Duration
|
||||
if err = media.AppendSegment(sg); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = media.SetDefaultKey("AES-128", keyUri, "", "", "")
|
||||
media.Close()
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package m3u8
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"videoweb/pub/common/enum/redisconst"
|
||||
"videoweb/pub/common/errors"
|
||||
"videoweb/pub/common/http"
|
||||
"videoweb/pub/common/log"
|
||||
"videoweb/pub/common/utils"
|
||||
"videoweb/pub/redis"
|
||||
"videoweb/pub/storage/proxy"
|
||||
|
||||
"github.com/grafov/m3u8"
|
||||
)
|
||||
|
||||
const (
|
||||
keyUri = "/enkey"
|
||||
webkeyUri = "/api/web/enkey"
|
||||
h5KeyUri = "/enkey"
|
||||
AuthKey = "fT5xSg4hltHpzVy6aV9rVECDJ1J1pN"
|
||||
)
|
||||
|
||||
// resolveTsAuthKey 优先使用传入的 tsAuthKey,为空则回退默认 AuthKey。
|
||||
func resolveTsAuthKey(tsAuthKey string) string {
|
||||
if key := strings.TrimSpace(tsAuthKey); key != "" {
|
||||
return key
|
||||
}
|
||||
return AuthKey
|
||||
}
|
||||
|
||||
var headerMediaPlayList *m3u8.MediaPlaylist
|
||||
|
||||
// TransFormWithSafely 被检查权限的播放列表
|
||||
// 主要检查用户是否有观看该视频的权限
|
||||
func TransFormWithSafely(req *Req, cdnDomain, origDomain string, web bool, tsAuthKey string) (*m3u8.MediaPlaylist, *bytes.Buffer, error) {
|
||||
if req.Name == "" {
|
||||
return nil, nil, errors.MakeWithMsg(errors.M3u8FileName, "file name is empty")
|
||||
}
|
||||
if cdnDomain == "" || origDomain == "" {
|
||||
return nil, nil, errors.MakeWithMsg(errors.DomainErr, "cdnDomain or origDomain is empty")
|
||||
}
|
||||
|
||||
return transform(req.Name, cdnDomain, origDomain, web, tsAuthKey)
|
||||
}
|
||||
|
||||
// transform m3u8文件转换,将不正确的m3u8文件,替换为正确的m3u8文件
|
||||
func transform(name string, cdnDomain, origDomain string, web bool, tsAuthKey string) (media *m3u8.MediaPlaylist, buff *bytes.Buffer, err error) {
|
||||
m3u8reader, err := readFromRedis(name, origDomain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p, t, err := m3u8.DecodeFrom(m3u8reader, false)
|
||||
if err != nil {
|
||||
err = errors.MakeWithErr(errors.M3u8Read, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 处理媒资库 桶1(v1) 桶2(v2) 桶3(v3)
|
||||
mediaVerson := proxy.AppendsMediaS3Version(name)
|
||||
if len(mediaVerson) > 0 {
|
||||
name = mediaVerson + name
|
||||
}
|
||||
|
||||
authKey := resolveTsAuthKey(tsAuthKey)
|
||||
keyurl := keyUri
|
||||
if web {
|
||||
keyurl = webkeyUri
|
||||
}
|
||||
|
||||
switch t {
|
||||
case m3u8.MEDIA:
|
||||
pl := p.(*m3u8.MediaPlaylist)
|
||||
dirPath := utils.PathForInfo(name).Dir
|
||||
media, err = makeMediaPlayList(pl, cdnDomain, dirPath, keyurl, authKey)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buff = media.Encode()
|
||||
case m3u8.MASTER:
|
||||
mpl := p.(*m3u8.MasterPlaylist)
|
||||
buff = mpl.Encode()
|
||||
default:
|
||||
err = errors.MakeWithMsg(errors.M3u8FileName, fmt.Sprintf("invalid m3u8 type %d", t))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func readFromCDN(name, domain string) (reader io.Reader, err error) {
|
||||
requestUrl := utils.JoinUrlPath(domain, name)
|
||||
resp, err := http.GetLargeFile(requestUrl, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
msg := fmt.Sprintf("read m3u8 fail, url: %s, status code %d", requestUrl, resp.StatusCode)
|
||||
err = errors.MakeWithMsg(errors.M3u8Read, msg)
|
||||
return
|
||||
}
|
||||
reader = bytes.NewReader(resp.Data)
|
||||
return
|
||||
}
|
||||
|
||||
// 从redis缓存中读取
|
||||
func readFromRedis(name, domain string) (reader io.Reader, err error) {
|
||||
m3u8Key := redisconst.MediaM3U8Key(name)
|
||||
data, err := redis.GetBytes(m3u8Key)
|
||||
if err == nil && len(data) > 0 {
|
||||
reader = bytes.NewReader(data)
|
||||
return
|
||||
}
|
||||
requestUrl := utils.JoinUrlPath(domain, name)
|
||||
resp, err := http.GetLargeFile(requestUrl, nil)
|
||||
if err != nil {
|
||||
fmt.Println("requestUrl111", requestUrl)
|
||||
return
|
||||
}
|
||||
fmt.Println("requestUrl", requestUrl, resp.StatusCode)
|
||||
if resp.StatusCode != 200 {
|
||||
msg := fmt.Sprintf("read m3u8 fail, url: %s, status code %d", requestUrl, resp.StatusCode)
|
||||
err = errors.MakeWithMsg(errors.M3u8Read, msg)
|
||||
return
|
||||
}
|
||||
if err := redis.Set(m3u8Key, resp.Data,
|
||||
redisconst.MediaM3U8CacheExpire); err != nil {
|
||||
log.Info("m3u8:readFromRedis redis set err", log.E(err))
|
||||
}
|
||||
reader = bytes.NewReader(resp.Data)
|
||||
return
|
||||
}
|
||||
|
||||
func GetHeaderMediaSegUrls() []string {
|
||||
urls := make([]string, 0)
|
||||
if headerMediaPlayList == nil {
|
||||
return urls
|
||||
}
|
||||
for _, segment := range headerMediaPlayList.Segments {
|
||||
if segment == nil {
|
||||
continue
|
||||
}
|
||||
urls = append(urls, segment.URI)
|
||||
}
|
||||
return urls
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package m3u8
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
"videoweb/pub/common/errors"
|
||||
"videoweb/pub/common/utils"
|
||||
"videoweb/pub/pubdef"
|
||||
"videoweb/pub/storage/proxy"
|
||||
|
||||
"github.com/grafov/m3u8"
|
||||
)
|
||||
|
||||
// transform m3u8文件转换,将不正确的m3u8文件,替换为正确的m3u8文件
|
||||
// apiType(1:app,2:h5app,3:web)
|
||||
func TransformEx(name string, cdnDomain, origDomain string, apiType int, authKey string) (
|
||||
media *m3u8.MediaPlaylist, buff *bytes.Buffer, err error) {
|
||||
|
||||
if name == "" {
|
||||
err = errors.MakeWithMsg(errors.M3u8FileName, "m3u8 file name is empty")
|
||||
return
|
||||
}
|
||||
if cdnDomain == "" || origDomain == "" {
|
||||
err = errors.MakeWithMsg(errors.DomainErr, "cdnDomain or origDomain is empty")
|
||||
return
|
||||
}
|
||||
// 处理媒资库 桶1(v1) 桶2(v2) 桶3(v3)
|
||||
mediaVerson := proxy.AppendsMediaS3Version(name)
|
||||
if len(mediaVerson) > 0 {
|
||||
name = mediaVerson + name
|
||||
}
|
||||
authKey = resolveTsAuthKey(authKey)
|
||||
|
||||
//log.Info("Test", log.Any("name", name), log.Any("cdnDomain", cdnDomain), log.Any("origDomain", origDomain), log.Any("authKey", authKey))
|
||||
m3u8reader, err := readFromRedis(name, origDomain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p, t, err := m3u8.DecodeFrom(m3u8reader, false)
|
||||
if err != nil {
|
||||
err = errors.MakeWithErr(errors.M3u8Read, err)
|
||||
return
|
||||
}
|
||||
apiPath := keyUri
|
||||
if apiType == 2 {
|
||||
apiPath = h5KeyUri
|
||||
} else if apiType == 3 {
|
||||
apiPath = webkeyUri
|
||||
}
|
||||
|
||||
switch t {
|
||||
case m3u8.MEDIA:
|
||||
pl := p.(*m3u8.MediaPlaylist)
|
||||
dirPath := utils.PathForInfo(name).Dir
|
||||
media, err = makeTSList(pl, cdnDomain, dirPath, apiPath, authKey)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buff = media.Encode()
|
||||
case m3u8.MASTER:
|
||||
mpl := p.(*m3u8.MasterPlaylist)
|
||||
buff = mpl.Encode()
|
||||
default:
|
||||
err = errors.MakeWithMsg(errors.M3u8FileName, fmt.Sprintf("invalid m3u8 type %d", t))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// makeTSList 根据from,重新生成播放列表
|
||||
func makeTSList(from *m3u8.MediaPlaylist, cdnDomain string,
|
||||
dirPath string, apiPath string, authKey string) (
|
||||
media *m3u8.MediaPlaylist, err error) {
|
||||
media, err = m3u8.NewMediaPlaylist(from.WinSize(), from.Count())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
base := utils.JoinUrlPath(cdnDomain, dirPath)
|
||||
for _, segment := range from.Segments {
|
||||
if segment == nil {
|
||||
continue
|
||||
}
|
||||
sg := new(m3u8.MediaSegment)
|
||||
sg.URI = utils.JoinUrlPath(base, segment.URI)
|
||||
if len(authKey) > 0 {
|
||||
//生成鉴权url
|
||||
urlPath := utils.JoinUrlPath(dirPath, segment.URI)
|
||||
urlAuth := generateUrlAuth(now, urlPath, authKey)
|
||||
sg.URI = sg.URI + urlAuth
|
||||
}
|
||||
sg.Title = segment.Title
|
||||
sg.Duration = segment.Duration
|
||||
if err = media.AppendSegment(sg); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = media.SetDefaultKey("AES-128", apiPath, "", "", "")
|
||||
media.Close()
|
||||
return
|
||||
}
|
||||
|
||||
// 生成鉴权url
|
||||
func generateUrlAuth(now time.Time, path string, authKey string) string {
|
||||
timestamp := now.Unix()
|
||||
signStr := fmt.Sprintf("%s-%d-0-0-%s", path, timestamp, authKey)
|
||||
md5Str := getMD5Sign(signStr)
|
||||
// TS CDN 鉴权参数后追加应用标识,便于流量统计。
|
||||
urlAuth := fmt.Sprintf("?md=%d-0-0-%s&c=%d", timestamp, md5Str, pubdef.AppId)
|
||||
return urlAuth
|
||||
}
|
||||
|
||||
// 生成鉴权url 七牛云
|
||||
func generateUrlAuthQiniu(now time.Time, path string, authKey string) string {
|
||||
timestamp := strconv.FormatInt(now.Add(2*time.Hour).Unix(), 16)
|
||||
base64 := path
|
||||
signStr := authKey + base64 + timestamp
|
||||
md5Str := getMD5Sign(signStr)
|
||||
urlAuth := fmt.Sprintf("?sign=%s&t=%s", md5Str, timestamp)
|
||||
return urlAuth
|
||||
}
|
||||
|
||||
// getMD5Sign 得到签名
|
||||
func getMD5Sign(buf string) string {
|
||||
md5Ctx := md5.New()
|
||||
md5Ctx.Write([]byte(buf))
|
||||
cipherStr := md5Ctx.Sum(nil)
|
||||
nsign := hex.EncodeToString(cipherStr)
|
||||
return nsign
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package m3u8
|
||||
|
||||
type Req struct {
|
||||
Token string `json:"token" form:"token"`
|
||||
VId int64 `json:"vId" form:"vId"`
|
||||
Name string `json:"name" form:"name"`
|
||||
NeedHeader bool `json:"needHeader" form:"needHeader"`
|
||||
}
|
||||
|
||||
type PostVideoReq struct {
|
||||
Token string `json:"token" form:"token"`
|
||||
Name string `json:"name" form:"name" binding:"required" comment:"must be set"`
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package m3u8
|
||||
|
||||
//sErr "sz-app-server/pub/common/errors"
|
||||
|
||||
// func CheckParams(req *Req) (err error) {
|
||||
// if req.Token == "" {
|
||||
// err = sErr.MakeWithMsg(sErr.NoToken, "no token")
|
||||
// return
|
||||
// }
|
||||
// if req.VId <= 0 {
|
||||
// err = sErr.MakeWithMsg(sErr.VideoId, "invalid video id")
|
||||
// return
|
||||
// }
|
||||
// if req.Name == "" {
|
||||
// err = sErr.MakeWithMsg(sErr.VideoName, "invalid name")
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
Reference in New Issue
Block a user