123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605 |
- package controllers
- import (
- "encoding/binary"
- "encoding/json"
- "eta/eta_mini_crm_ht/models"
- "eta/eta_mini_crm_ht/models/request"
- "eta/eta_mini_crm_ht/models/response"
- "eta/eta_mini_crm_ht/services"
- "eta/eta_mini_crm_ht/services/elastic"
- "eta/eta_mini_crm_ht/utils"
- "fmt"
- "github.com/rdlucklib/rdluck_tools/paging"
- "io"
- "os"
- "path"
- "strconv"
- "time"
- )
- var (
- videoType = map[string]int{
- "mp4": 1,
- "m4a": 1,
- }
- )
- type VideoController struct {
- BaseAuthController
- }
- // UploadVideo @Title 上传视频
- // @Description 上传视频
- // @Param File query file true "文件"
- // @Success 200 {object} models.ReportAuthorResp
- // @router /uploadVideo [post]
- func (this *VideoController) UploadVideo() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- f, h, err := this.GetFile("File")
- if err != nil {
- br.Msg = "获取资源信息失败"
- br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
- return
- }
- defer f.Close()
- size, err := strconv.Atoi(utils.UPLOAD_VIDEO_SIZE)
- if err != nil {
- size = 1024
- }
- if h.Size > 1024*1024*int64(size) {
- br.Msg = fmt.Sprintf("视频大小不能超过%dM", size)
- br.ErrMsg = "视频上传失败,Err:" + err.Error()
- return
- }
- ext := path.Ext(h.Filename)
- if _, ok := videoType[ext]; !ok {
- br.Msg = "视频格式不正确"
- br.ErrMsg = "视频上传失败,Err:" + err.Error()
- return
- }
- dateDir := time.Now().Format("20060102")
- uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
- err = os.MkdirAll(uploadDir, utils.DIR_MOD)
- if err != nil {
- br.Msg = "存储目录创建失败"
- br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
- return
- }
- randStr := utils.GetRandStringNoSpecialChar(28)
- fileName := randStr + ext
- fpath := uploadDir + "/" + fileName
- err = this.SaveToFile("File", fpath)
- if err != nil {
- br.Msg = "视频上传失败"
- br.ErrMsg = "视频上传失败,Err:" + err.Error()
- return
- }
- duration, err := GetMP4Duration(f)
- if err != nil {
- br.Msg = "视频上传失败"
- br.ErrMsg = "获取视频时长失败,Err:" + err.Error()
- return
- }
- audioUploadDir := utils.RESOURCE_DIR + "video/"
- savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
- audioName := utils.GetRandStringNoSpecialChar(28)
- savePdfToOssPath += audioName + ext
- defer func() {
- err = os.Remove(fpath)
- fmt.Sprintf("删除文件失败:%v", err)
- }()
- ossClient := services.NewOssClient()
- if ossClient == nil {
- br.Msg = "视频上传失败"
- br.ErrMsg = "初始化OSS服务失败"
- return
- }
- videoUrl, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
- if err != nil {
- br.Msg = "视频上传失败"
- br.ErrMsg = "视频上传失败,Err:" + err.Error()
- return
- }
- base := path.Base(h.Filename)
- resp := new(response.MediaUploadResp)
- resp.Url = videoUrl
- resp.FileName = base
- resp.DurationMillisecond = duration * 1000
- br.Data = resp
- br.Msg = "上传成功"
- br.Ret = 200
- br.Success = true
- }
- // AddVideo @Title 新增音频
- // @Description 新增音频
- // @Param File query file true "文件"
- // @Success 200 {object} models.ReportAuthorResp
- // @router /addVideo [post]
- func (this *VideoController) AddVideo() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- var req request.VideoReq
- if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
- br.Msg = "参数解析失败"
- br.ErrMsg = "参数解析失败,Err:" + err.Error()
- return
- }
- if req.VideoName == "" {
- br.Msg = "视频名称为空"
- return
- }
- if req.AnalystId == 0 {
- br.Msg = "研究员ID为空"
- return
- }
- if req.AnalystName == "" {
- br.Msg = "研究员名称为空"
- return
- }
- if req.SrcUrl == "" {
- br.Msg = "视频地址为空"
- return
- }
- if req.DurationMillisecond == 0 {
- br.Msg = "视频时长为空"
- return
- }
- if req.CoverSrc == "" {
- br.Msg = "封面为空"
- return
- }
- var err error
- audioInsert := &models.Media{
- AuthorId: req.AnalystId,
- AuthorName: req.AnalystName,
- MediaType: models.Video,
- Src: req.SrcUrl,
- CoverSrc: req.CoverSrc,
- MediaName: req.VideoName,
- SourceType: "mp4",
- MediaPlayMilliseconds: req.DurationMillisecond,
- PermissionIds: req.PermissionIds,
- PublishedTime: time.Now(),
- SendStatus: models.UNSEND,
- Deleted: 0,
- CreatedTime: time.Now(),
- }
- err = models.InsertMedia(audioInsert)
- if err != nil {
- br.Msg = "添加失败"
- br.ErrMsg = "音频新增失败,Err:" + err.Error()
- return
- }
- // 添加es
- go func(audio *models.ESMedia) {
- docId := strconv.Itoa(audio.MediaId)
- err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
- if err != nil {
- utils.FileLog.Info("音频记录es新增失败,Err:" + err.Error())
- return
- }
- utils.FileLog.Info("音频记录es新增成功, pdfId:" + docId)
- }(audioInsert.ToView())
- // 创建消息
- _, _ = services.CreateMeta(audioInsert.AuthorName, audioInsert.AuthorId, audioInsert.Id, audioInsert.PublishedTime.Format(time.DateTime), models.VideoSourceType)
- br.Msg = "添加成功"
- br.Ret = 200
- br.Success = true
- }
- // EditVideo @Title 编辑音频
- //
- // @Description 编辑音频
- // @Success 200 {object} models.ReportAuthorResp
- // @router /editVideo [post]
- func (this *VideoController) EditVideo() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- var req request.VideoReq
- if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
- br.Msg = "参数解析失败"
- br.ErrMsg = "参数解析失败,Err:" + err.Error()
- return
- }
- if req.VideoId <= 0 {
- br.Msg = "视频ID为空"
- return
- }
- if req.VideoName == "" {
- br.Msg = "视频名称为空"
- return
- }
- if req.AnalystId == 0 {
- br.Msg = "研究员ID为空"
- return
- }
- if req.AnalystName == "" {
- br.Msg = "研究员名称为空"
- return
- }
- if req.SrcUrl == "" {
- br.Msg = "视频地址为空"
- return
- }
- if req.DurationMillisecond == 0 {
- br.Msg = "视频时长为空"
- return
- }
- if req.CoverSrc == "" {
- br.Msg = "封面为空"
- return
- }
- var err error
- audioEdit := &models.Media{
- Id: req.VideoId,
- AuthorId: req.AnalystId,
- AuthorName: req.AnalystName,
- MediaType: models.Video,
- CoverSrc: req.CoverSrc,
- Src: req.SrcUrl,
- SourceType: "mp4",
- MediaName: req.VideoName,
- MediaPlayMilliseconds: req.DurationMillisecond,
- PermissionIds: req.PermissionIds,
- }
- //coverSrc
- _, err = models.UpdateMedia(audioEdit)
- if err != nil {
- br.Msg = "更新失败"
- br.ErrMsg = "视频更新失败,Err:" + err.Error()
- return
- }
- go func(audio *models.ESMedia) {
- docId := strconv.Itoa(audio.MediaId)
- err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
- if err != nil {
- utils.FileLog.Info("视频记录es更新失败,Err:" + err.Error())
- return
- }
- utils.FileLog.Info("视频记录es更新成功, pdfId:" + docId)
- }(audioEdit.ToView())
- br.Msg = "编辑成功"
- br.Ret = 200
- br.Success = true
- }
- // DeleteVideo
- // @Title 删除音频
- //
- // @Description 删除音频
- // @Success 200 {object} models.ReportAuthorResp
- // @router /deleteVideo [post]
- func (this *VideoController) DeleteVideo() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- var req request.VideoReq
- if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
- br.Msg = "参数解析失败"
- br.ErrMsg = "参数解析失败,Err:" + err.Error()
- return
- }
- if req.VideoId <= 0 {
- br.Msg = "视频ID为空"
- return
- }
- var err error
- audioDelete := &models.Media{
- Id: req.VideoId,
- Deleted: 1,
- }
- err = models.DeleteMedia(audioDelete)
- if err != nil {
- br.Msg = "删除失败"
- br.ErrMsg = "视频删除失败,Err:" + err.Error()
- return
- }
- // 添加es
- go func(audio *models.ESMedia) {
- docId := strconv.Itoa(audio.MediaId)
- err = elastic.EsDeleteData(utils.MEDIA_INDEX, docId)
- if err != nil {
- utils.FileLog.Info("视频记录es删除失败,Err:" + err.Error())
- return
- }
- utils.FileLog.Info("视频记录es删除成功, pdfId:" + docId)
- }(audioDelete.ToView())
- br.Msg = "删除成功"
- br.Ret = 200
- br.Success = true
- }
- // VideoList
- // @Title 研报列表
- // @Description pdf研报列表
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param ClassifyIds query string true "二级分类id,可多选用英文,隔开"
- // @Param KeyWord query string true "报告标题/创建人"
- // @Param SortType query string true "排序方式"
- // @Success 200 {object} models.ReportAuthorResp
- // @router /videoList [get]
- func (this *VideoController) VideoList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- sortType := this.GetString("SortType")
- KeyWord := this.GetString("KeyWord")
- var condition string
- var pars []interface{}
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- if KeyWord != "" {
- condition += " AND media_name like '%" + KeyWord + "%'"
- }
- sortCondition := " ORDER BY published_time "
- if sortType == "" {
- sortType = "DESC"
- }
- sortCondition = sortCondition + sortType
- total, err := models.GetMediaCountByCondition(models.Video, condition, pars)
- if err != nil {
- br.Msg = "获取视频列表失败"
- br.ErrMsg = "获取视频列表统计失败,Err:" + err.Error()
- return
- }
- startSize := utils.StartIndex(currentIndex, pageSize)
- List, err := models.GetMediaByCondition(models.Video, condition, sortCondition, pars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取视频列表失败"
- br.ErrMsg = "获取视频列表失败,Err:" + err.Error()
- return
- }
- var reportViewList []*models.MediaView
- for _, report := range List {
- reportView := report.ToMediaView()
- reportViewList = append(reportViewList, reportView)
- }
- page := paging.GetPaging(currentIndex, pageSize, total)
- resp := new(response.MediaListResp)
- resp.List = reportViewList
- resp.Paging = page
- br.Ret = 200
- br.Success = true
- br.Data = resp
- br.Msg = "获取成功"
- }
- // UploadFile @Title 上传图片
- // @Description 上传视频
- // @Param File query file true "文件"
- // @Success 200 {object} models.ReportAuthorResp
- // @router /uploadFile [post]
- func (this *VideoController) UploadFile() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- f, h, err := this.GetFile("File")
- if err != nil {
- br.Msg = "获取资源信息失败"
- br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
- return
- }
- defer f.Close()
- size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
- if err != nil {
- size = 100
- }
- if h.Size > 1024*1024*int64(size) {
- br.Msg = fmt.Sprintf("图片大小不能超过%dK", size)
- br.ErrMsg = "图片上传失败,Err:" + err.Error()
- return
- }
- ext := path.Ext(h.Filename)
- dateDir := time.Now().Format("20060102")
- uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
- err = os.MkdirAll(uploadDir, utils.DIR_MOD)
- if err != nil {
- br.Msg = "存储目录创建失败"
- br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
- return
- }
- randStr := utils.GetRandStringNoSpecialChar(28)
- fileName := randStr + ext
- fpath := uploadDir + "/" + fileName
- err = this.SaveToFile("File", fpath)
- if err != nil {
- br.Msg = "图片上传失败"
- br.ErrMsg = "图片上传失败,Err:" + err.Error()
- return
- }
- audioUploadDir := utils.RESOURCE_DIR + "img/"
- savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
- audioName := utils.GetRandStringNoSpecialChar(28)
- savePdfToOssPath += audioName + ext
- defer func() {
- err = os.Remove(fpath)
- fmt.Sprintf("删除文件失败:%v", err)
- }()
- ossClient := services.NewOssClient()
- if ossClient == nil {
- br.Msg = "图片上传失败"
- br.ErrMsg = "初始化OSS服务失败"
- return
- }
- imageUrl, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
- if err != nil {
- br.Msg = "图片上传失败"
- br.ErrMsg = "图片上传失败,Err:" + err.Error()
- return
- }
- base := path.Base(h.Filename)
- resp := new(response.MediaUploadResp)
- resp.Url = imageUrl
- resp.FileName = base
- br.Data = resp
- br.Msg = "上传成功"
- br.Ret = 200
- br.Success = true
- }
- // BoxHeader represents the header of an ISO BMFF box.
- type BoxHeader struct {
- Size uint32
- Type [4]byte
- Size64 uint64
- }
- // getHeaderBoxInfo parses the box header from the provided byte slice.
- func getHeaderBoxInfo(data []byte) BoxHeader {
- var header BoxHeader
- header.Size = binary.BigEndian.Uint32(data[0:4])
- copy(header.Type[:], data[4:8])
- if header.Size == 1 {
- header.Size64 = binary.BigEndian.Uint64(data[8:16])
- }
- return header
- }
- // getFourccType returns the FourCC type as a string.
- func getFourccType(header BoxHeader) string {
- return string(header.Type[:])
- }
- // readBox reads the entire box data from the reader at the given offset.
- func readBox(reader io.ReaderAt, offset int64, size uint64) ([]byte, error) {
- boxData := make([]byte, size)
- _, err := reader.ReadAt(boxData, offset)
- if err != nil {
- return nil, err
- }
- return boxData, nil
- }
- // findBox recursively finds a box of the specified type within the given box data.
- func findBox(boxData []byte, boxType string) ([]byte, error) {
- var offset uint32 = 0
- for offset < uint32(len(boxData)) {
- header := getHeaderBoxInfo(boxData[offset:])
- size := uint64(header.Size)
- if header.Size == 1 {
- size = header.Size64
- }
- if getFourccType(header) == boxType {
- return boxData[offset : offset+uint32(size)], nil
- }
- offset += uint32(size)
- }
- return nil, fmt.Errorf("box type %s not found", boxType)
- }
- // GetMP4Duration reads the duration of an MP4 or M4A file from the provided reader.
- func GetMP4Duration(reader io.ReaderAt) (lengthOfTime int, err error) {
- var info = make([]byte, 0x10)
- var boxHeader BoxHeader
- var offset int64 = 0
- // 获取moov结构偏移
- for {
- _, err = reader.ReadAt(info, offset)
- if err == io.EOF {
- fmt.Println("Reached EOF without finding moov box.")
- return 0, fmt.Errorf("moov box not found")
- }
- if err != nil {
- return 0, fmt.Errorf("error reading at offset %d: %w", offset, err)
- }
- boxHeader = getHeaderBoxInfo(info)
- fourccType := getFourccType(boxHeader)
- if fourccType == "moov" {
- fmt.Println("Found moov box at offset", offset)
- break
- }
- nextOffset := int64(boxHeader.Size)
- if fourccType == "mdat" && boxHeader.Size == 1 {
- nextOffset = int64(boxHeader.Size64)
- }
- if nextOffset == 0 {
- return 0, fmt.Errorf("box size is zero, which is invalid and likely means a parsing error")
- }
- offset += nextOffset
- }
- // 读取moov盒子数据
- moovBoxData, err := readBox(reader, offset, uint64(boxHeader.Size))
- if err != nil {
- return 0, fmt.Errorf("error reading moov box at offset %d: %w", offset, err)
- }
- // 在moov盒子中查找mvhd或tkhd盒子
- mvhdBox, err := findBox(moovBoxData, "mvhd")
- if err != nil {
- tkhdBox, err := findBox(moovBoxData, "tkhd")
- if err != nil {
- return 0, fmt.Errorf("neither mvhd nor tkhd box found in moov box")
- }
- mvhdBox = tkhdBox
- }
- // 解析mvhd或tkhd盒子中的timeScale和duration
- var timeScaleOffset, durationOffset uint32
- if getFourccType(getHeaderBoxInfo(mvhdBox)) == "mvhd" {
- timeScaleOffset = 0x1C
- durationOffset = 0x20
- } else if getFourccType(getHeaderBoxInfo(mvhdBox)) == "tkhd" {
- timeScaleOffset = 0x14
- durationOffset = 0x18
- } else {
- return 0, fmt.Errorf("unsupported box type in moov box")
- }
- timeScale := binary.BigEndian.Uint32(mvhdBox[timeScaleOffset : timeScaleOffset+4])
- duration := binary.BigEndian.Uint32(mvhdBox[durationOffset : durationOffset+4])
- fmt.Printf("timeScale: %d, duration: %d\n", timeScale, duration)
- if timeScale == 0 {
- return 0, fmt.Errorf("timeScale is zero, division by zero is not possible")
- }
- lengthOfTime = int(duration / timeScale)
- return
- }
|