作者 yangfu

增加 aliyun 视频点播接入

package v1
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/controllers"
"opp/internal/aliyun"
"opp/internal/utils"
"opp/protocol"
"opp/services/file"
"path/filepath"
"strings"
)
... ... @@ -37,3 +41,24 @@ func (this *FileController) DownLoad() {
}
msg = protocol.NewReturnResponse(rsp, err)
}
//GetPlayInfo 获取播放信息
// @router /getPlayInfo [post]
func (this *FileController) GetPlayInfo() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *aliyun.GetPlayInfoRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(file.GetPlayInfo(header, request))
}
... ...
... ... @@ -2,8 +2,10 @@ package v1
import (
"bytes"
"encoding/json"
"fmt"
"opp/controllers"
"opp/internal/aliyun"
"opp/protocol"
"opp/services/upload"
... ... @@ -94,3 +96,24 @@ func (this *UploadController) Video() {
}
msg = protocol.NewReturnResponse(rsp, err)
}
//创建视频上传凭证 CreateUploadVideo
// @router /createUploadVideo [post]
func (this *UploadController) CreateUploadVideo() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *aliyun.CreateUploadVideoRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(upload.CreateUploadVideo(header, request))
}
... ...
... ... @@ -3,6 +3,7 @@ module opp
go 1.12
require (
github.com/aliyun/alibaba-cloud-sdk-go v1.60.348
github.com/astaxie/beego v1.10.0
github.com/disintegration/imaging v1.6.2
github.com/go-sql-driver/mysql v1.4.1
... ...
package aliyun
const (
RegionID = "cn-shanghai"
AccessKeyID = "LTAI4FhiZ3UktC6N1u3H5GFC"
AccessKeySecret = "UyspWwdni55CYQ02hUCint4qY2jNYO"
)
const (
FileImage = "image"
FileVoice = "voice"
FileVideo = "video"
)
... ...
package aliyun
//创建视频上传凭证
/*CreateUploadVideo */
type CreateUploadVideoRequest struct {
}
type CreateUploadVideoResponse struct {
RequestId string `json:"requestId"`
VideoId string `json:"videoId"`
UploadAddress string `json:"uploadAddress"`
UploadAuth string `json:"uploadAuth"`
}
/*GetPlayInfo 获取播放信息*/
type GetPlayInfoRequest struct {
VideoId string `json:"videoId" xml:"VideoId"`
}
// GetPlayInfoResponse is the response struct for api GetPlayInfo
type GetPlayInfoResponse struct {
//*responses.BaseResponse
//RequestId string `json:"RequestId" xml:"RequestId"`
VideoBase VideoBase `json:"VideoBase" xml:"VideoBase"`
PlayInfoList PlayInfoListInGetPlayInfo `json:"PlayInfoList" xml:"PlayInfoList"`
}
// VideoBase is a nested struct in vod response
type VideoBase struct {
OutputType string `json:"OutputType" xml:"OutputType"`
CoverURL string `json:"CoverURL" xml:"CoverURL"`
Duration string `json:"Duration" xml:"Duration"`
Status string `json:"Status" xml:"Status"`
Title string `json:"Title" xml:"Title"`
VideoId string `json:"VideoId" xml:"VideoId"`
MediaType string `json:"MediaType" xml:"MediaType"`
CreationTime string `json:"CreationTime" xml:"CreationTime"`
TranscodeMode string `json:"TranscodeMode" xml:"TranscodeMode"`
//ThumbnailList ThumbnailListInGetPlayInfo `json:"ThumbnailList" xml:"ThumbnailList"`
}
type PlayInfoListInGetPlayInfo struct {
PlayInfo []PlayInfo `json:"PlayInfo" xml:"PlayInfo"`
}
// PlayInfo is a nested struct in vod response
type PlayInfo struct {
JobId string `json:"JobId" xml:"JobId"`
Format string `json:"Format" xml:"Format"`
PreprocessStatus string `json:"PreprocessStatus" xml:"PreprocessStatus"`
EncryptType string `json:"EncryptType" xml:"EncryptType"`
Fps string `json:"Fps" xml:"Fps"`
ModificationTime string `json:"ModificationTime" xml:"ModificationTime"`
NarrowBandType string `json:"NarrowBandType" xml:"NarrowBandType"`
Bitrate string `json:"Bitrate" xml:"Bitrate"`
Encrypt int64 `json:"Encrypt" xml:"Encrypt"`
Rand string `json:"Rand" xml:"Rand"`
CreationTime string `json:"CreationTime" xml:"CreationTime"`
StreamType string `json:"StreamType" xml:"StreamType"`
Height int64 `json:"Height" xml:"Height"`
WatermarkId string `json:"WatermarkId" xml:"WatermarkId"`
Duration string `json:"Duration" xml:"Duration"`
Complexity string `json:"Complexity" xml:"Complexity"`
Width int64 `json:"Width" xml:"Width"`
Size int64 `json:"Size" xml:"Size"`
Status string `json:"Status" xml:"Status"`
Definition string `json:"Definition" xml:"Definition"`
Plaintext string `json:"Plaintext" xml:"Plaintext"`
PlayURL string `json:"PlayURL" xml:"PlayURL"`
Specification string `json:"Specification" xml:"Specification"`
}
... ...
package aliyun
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/services/vod"
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
comm_time "gitlab.fjmaimaimai.com/mmm-go/gocomm/time"
"path"
"time"
)
//客户端
func DefaultVodClient() (client *vod.Client, err error) {
return InitVodClient(AccessKeyID, AccessKeySecret)
}
//初始化客户端
func InitVodClient(accessKeyId string, accessKeySecret string) (client *vod.Client, err error) {
// 点播服务接入区域
regionId := RegionID
// 创建授权对象
credential := &credentials.AccessKeyCredential{
accessKeyId,
accessKeySecret,
}
// 自定义config
config := sdk.NewConfig()
config.AutoRetry = true // 失败是否自动重试
config.MaxRetryTime = 3 // 最大重试次数
config.Timeout = 3000000000 // 连接超时,单位:纳秒;默认为3秒
// 创建vodClient实例
return vod.NewClientWithOptions(regionId, config, credential)
}
//获取视频上传地址和凭证,并创建视频信息
func CreateUploadVideo(client *vod.Client) (response *CreateUploadVideoResponse, err error) {
request := vod.CreateCreateUploadVideoRequest()
request.Title = getFileName(FileVideo, "video_file.mp4")
request.FileName = getFileName(FileVideo, "video_file.mp4")
//request.CoverURL = "http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"
//request.Tags = "tag1,tag2"
request.AcceptFormat = "JSON"
rsp, err := client.CreateUploadVideo(request)
if err != nil {
return
}
response = &CreateUploadVideoResponse{
RequestId: rsp.RequestId,
VideoId: rsp.VideoId,
UploadAddress: rsp.UploadAddress,
UploadAuth: rsp.UploadAuth,
}
return
}
//获取播放信息
func GetPlayInfo(client *vod.Client, videoId string) (response *vod.GetPlayInfoResponse, err error) {
request := vod.CreateGetPlayInfoRequest()
request.VideoId = videoId
request.AcceptFormat = "JSON"
return client.GetPlayInfo(request)
}
//fileType: video voice image
func getFileName(fileType string, filename string) string {
date := comm_time.GetTimeByYyyymmdd()
subfix := path.Ext(filename)
prefix := fmt.Sprintf("%v_%v", time.Now().Unix(), common.RandomString(32))
filename = fmt.Sprintf("%v%v", prefix, subfix)
sourcePath := fmt.Sprintf("%v/%v/%v/%v/%v", beego.BConfig.AppName, beego.BConfig.RunMode, fileType, date, filename)
return sourcePath
}
... ...
package utils
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
... ... @@ -85,3 +87,12 @@ func JsonUnmarshal(jsonData string, v interface{}) {
log.Error("json.unmarshal error data:", jsonData, e)
}
}
//深度拷贝
func DeepCopy(dst, src interface{}) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return gob.NewDecoder(&buf).Decode(dst)
}
... ...
package utils
import "testing"
func Test_DeepCopy(t *testing.T) {
type User1 struct {
Name string
Age int
Address string
}
type User2 struct {
Name string
Age int
Job string
}
var src = User1{Name: "foo", Age: 10, Address: "bar"}
var dst *User2
if err := DeepCopy(&dst, src); err != nil {
t.Fatal(err)
}
if src.Name != dst.Name {
t.Fatal("deep copy fail.")
}
//t.Log(src,"\n",dst)
}
... ...
... ... @@ -5,7 +5,7 @@ import "mime/multipart"
const (
FileImage = "image"
FileVoice = "voice"
FileVideo ="video"
FileVideo = "video"
)
/*Image */
... ...
... ... @@ -393,6 +393,14 @@ func init() {
beego.GlobalControllerRouter["opp/controllers/v1:UploadController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UploadController"],
beego.ControllerComments{
Method: "CreateUploadVideo",
Router: `/createUploadVideo`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:UploadController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UploadController"],
beego.ControllerComments{
Method: "Image",
Router: `/image`,
AllowHTTPMethods: []string{"post"},
... ...
... ... @@ -23,6 +23,7 @@ func init() {
beego.NSNamespace("message", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.MessageController{})),
beego.NSNamespace("department", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.DepartmentController{})),
beego.NSNamespace("config", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.ConfigController{})),
beego.NSNamespace("file", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.FileController{})),
)
beego.AddNamespace(nsV1)
... ...
package file
import (
"github.com/prometheus/common/log"
"opp/internal/aliyun"
"opp/internal/utils"
"opp/protocol"
)
//GetPlayInfo 获取播放信息
func GetPlayInfo(header *protocol.RequestHeader, request *aliyun.GetPlayInfoRequest) (rsp *aliyun.GetPlayInfoResponse, err error) {
var ()
client, e := aliyun.DefaultVodClient()
if e != nil {
log.Error(e)
err = e
return
}
response, e := aliyun.GetPlayInfo(client, request.VideoId)
if e != nil {
log.Error(e)
err = e
return
}
rsp = &aliyun.GetPlayInfoResponse{}
if err = utils.DeepCopy(&rsp, response); err != nil {
log.Error(err)
return
}
return
}
... ...
... ... @@ -5,6 +5,7 @@ import (
"github.com/disintegration/imaging"
"io"
"mime/multipart"
"opp/internal/aliyun"
"os"
"path"
"path/filepath"
... ... @@ -133,3 +134,16 @@ func GetSortFileKeys(files map[string][]*multipart.FileHeader) (keys []string) {
sort.Strings(keys)
return
}
//创建视频上传凭证
func CreateUploadVideo(header *protocol.RequestHeader, request *aliyun.CreateUploadVideoRequest) (rsp *aliyun.CreateUploadVideoResponse, err error) {
var ()
client, e := aliyun.DefaultVodClient()
if e != nil {
log.Error(e)
err = e
return
}
rsp, err = aliyun.CreateUploadVideo(client)
return
}
... ...