video.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. package controllers
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "eta/eta_mini_crm_ht/models"
  7. "eta/eta_mini_crm_ht/models/request"
  8. "eta/eta_mini_crm_ht/models/response"
  9. "eta/eta_mini_crm_ht/services"
  10. "eta/eta_mini_crm_ht/utils"
  11. "eta/eta_mini_crm_ht/utils/elastic"
  12. "eta/eta_mini_crm_ht/utils/oss"
  13. "fmt"
  14. "github.com/rdlucklib/rdluck_tools/paging"
  15. "io"
  16. "os"
  17. "path"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. var (
  23. videoType = map[string]int{
  24. ".mp4": 1,
  25. }
  26. )
  27. type VideoController struct {
  28. BaseAuthController
  29. }
  30. // UploadVideo @Title 上传视频
  31. // @Description 上传视频
  32. // @Param File query file true "文件"
  33. // @Success 200 {object} models.ReportAuthorResp
  34. // @router /uploadVideo [post]
  35. func (this *VideoController) UploadVideo() {
  36. br := new(models.BaseResponse).Init()
  37. defer func() {
  38. this.Data["json"] = br
  39. this.ServeJSON()
  40. }()
  41. f, h, err := this.GetFile("File")
  42. if err != nil {
  43. br.Msg = "获取资源信息失败"
  44. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  45. return
  46. }
  47. defer f.Close()
  48. size, err := strconv.Atoi(utils.UPLOAD_VIDEO_SIZE)
  49. if err != nil {
  50. size = 1024
  51. }
  52. if h.Size > 1024*1024*int64(size) {
  53. br.Msg = fmt.Sprintf("视频大小不能超过%dM", size)
  54. br.ErrMsg = "视频上传失败,Err:" + err.Error()
  55. return
  56. }
  57. ext := path.Ext(h.Filename)
  58. lowCaseExt := strings.ToLower(ext)
  59. if _, ok := videoType[lowCaseExt]; !ok {
  60. br.Msg = "视频格式不正确"
  61. br.ErrMsg = "视频上传失败,Err:" + err.Error()
  62. return
  63. }
  64. dateDir := time.Now().Format("20060102")
  65. uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
  66. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  67. if err != nil {
  68. br.Msg = "存储目录创建失败"
  69. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  70. return
  71. }
  72. randStr := utils.GetRandStringNoSpecialChar(28)
  73. fileName := randStr + ext
  74. fpath := uploadDir + "/" + fileName
  75. err = this.SaveToFile("File", fpath)
  76. if err != nil {
  77. br.Msg = "视频上传失败"
  78. br.ErrMsg = "视频上传失败,Err:" + err.Error()
  79. return
  80. }
  81. duration, err := GetMP4Duration(f)
  82. if err != nil {
  83. br.Msg = "视频上传失败"
  84. br.ErrMsg = "获取视频时长失败,Err:" + err.Error()
  85. return
  86. }
  87. audioUploadDir := utils.RESOURCE_DIR + "video/"
  88. savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
  89. audioName := utils.GetRandStringNoSpecialChar(28)
  90. savePdfToOssPath += audioName + ext
  91. defer func() {
  92. err = os.Remove(fpath)
  93. fmt.Sprintf("删除文件失败:%v", err)
  94. }()
  95. ossClient := oss.NewOssClient()
  96. if ossClient == nil {
  97. br.Msg = "视频上传失败"
  98. br.ErrMsg = "初始化OSS服务失败"
  99. return
  100. }
  101. mp3Url, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
  102. if err != nil {
  103. br.Msg = "视频上传失败"
  104. br.ErrMsg = "视频上传失败,Err:" + err.Error()
  105. return
  106. }
  107. base := path.Base(h.Filename)
  108. resp := new(response.MediaUploadResp)
  109. resp.Url = mp3Url
  110. resp.FileName = base
  111. resp.DurationMillisecond = duration * 1000
  112. br.Data = resp
  113. br.Msg = "上传成功"
  114. br.Ret = 200
  115. br.Success = true
  116. }
  117. // AddVideo @Title 新增音频
  118. // @Description 新增音频
  119. // @Param File query file true "文件"
  120. // @Success 200 {object} models.ReportAuthorResp
  121. // @router /addVideo [post]
  122. func (this *VideoController) AddVideo() {
  123. br := new(models.BaseResponse).Init()
  124. defer func() {
  125. this.Data["json"] = br
  126. this.ServeJSON()
  127. }()
  128. var req request.VideoReq
  129. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  130. br.Msg = "参数解析失败"
  131. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  132. return
  133. }
  134. if req.VideoName == "" {
  135. br.Msg = "视频名称为空"
  136. return
  137. }
  138. if req.AnalystId == 0 {
  139. br.Msg = "研究员ID为空"
  140. return
  141. }
  142. if req.AnalystName == "" {
  143. br.Msg = "研究员名称为空"
  144. return
  145. }
  146. if req.SrcUrl == "" {
  147. br.Msg = "视频地址为空"
  148. return
  149. }
  150. if req.DurationMillisecond == 0 {
  151. br.Msg = "视频时长为空"
  152. return
  153. }
  154. if req.CoverSrc == "" {
  155. br.Msg = "封面为空"
  156. return
  157. }
  158. var err error
  159. audioInsert := &models.Media{
  160. AuthorId: req.AnalystId,
  161. AuthorName: req.AnalystName,
  162. MediaType: models.Video,
  163. Src: req.SrcUrl,
  164. CoverSrc: req.CoverSrc,
  165. MediaName: req.VideoName,
  166. SourceType: "mp4",
  167. MediaPlayMilliseconds: req.DurationMillisecond,
  168. PermissionIds: req.PermissionIds,
  169. PublishedTime: time.Now(),
  170. SendStatus: models.UNSEND,
  171. Deleted: 0,
  172. CreatedTime: time.Now(),
  173. }
  174. err = models.InsertMedia(audioInsert)
  175. if err != nil {
  176. br.Msg = "添加失败"
  177. br.ErrMsg = "音频新增失败,Err:" + err.Error()
  178. return
  179. }
  180. // 添加es
  181. go func(audio *models.ESMedia) {
  182. docId := strconv.Itoa(audio.MediaId)
  183. err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
  184. if err != nil {
  185. utils.FileLog.Info("音频记录es新增失败,Err:" + err.Error())
  186. return
  187. }
  188. utils.FileLog.Info("音频记录es新增成功, pdfId:" + docId)
  189. }(audioInsert.ToView())
  190. // 创建消息
  191. _, _ = services.CreateMeta(audioInsert.AuthorName, audioInsert.AuthorId, audioInsert.Id, audioInsert.PublishedTime.Format(time.DateTime), models.VideoSourceType)
  192. br.Msg = "添加成功"
  193. br.Ret = 200
  194. br.Success = true
  195. }
  196. // EditVideo @Title 编辑音频
  197. //
  198. // @Description 编辑音频
  199. // @Success 200 {object} models.ReportAuthorResp
  200. // @router /editVideo [post]
  201. func (this *VideoController) EditVideo() {
  202. br := new(models.BaseResponse).Init()
  203. defer func() {
  204. this.Data["json"] = br
  205. this.ServeJSON()
  206. }()
  207. var req request.VideoReq
  208. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  209. br.Msg = "参数解析失败"
  210. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  211. return
  212. }
  213. if req.VideoId <= 0 {
  214. br.Msg = "视频ID为空"
  215. return
  216. }
  217. if req.VideoName == "" {
  218. br.Msg = "视频名称为空"
  219. return
  220. }
  221. if req.AnalystId == 0 {
  222. br.Msg = "研究员ID为空"
  223. return
  224. }
  225. if req.AnalystName == "" {
  226. br.Msg = "研究员名称为空"
  227. return
  228. }
  229. if req.SrcUrl == "" {
  230. br.Msg = "视频地址为空"
  231. return
  232. }
  233. if req.DurationMillisecond == 0 {
  234. br.Msg = "视频时长为空"
  235. return
  236. }
  237. if req.CoverSrc == "" {
  238. br.Msg = "封面为空"
  239. return
  240. }
  241. var err error
  242. audioEdit := &models.Media{
  243. Id: req.VideoId,
  244. AuthorId: req.AnalystId,
  245. AuthorName: req.AnalystName,
  246. MediaType: models.Video,
  247. CoverSrc: req.CoverSrc,
  248. Src: req.SrcUrl,
  249. SourceType: "mp4",
  250. MediaName: req.VideoName,
  251. MediaPlayMilliseconds: req.DurationMillisecond,
  252. PermissionIds: req.PermissionIds,
  253. }
  254. //coverSrc
  255. _, err = models.UpdateMedia(audioEdit)
  256. if err != nil {
  257. br.Msg = "更新失败"
  258. br.ErrMsg = "视频更新失败,Err:" + err.Error()
  259. return
  260. }
  261. go func(audio *models.ESMedia) {
  262. docId := strconv.Itoa(audio.MediaId)
  263. err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
  264. if err != nil {
  265. utils.FileLog.Info("视频记录es更新失败,Err:" + err.Error())
  266. return
  267. }
  268. utils.FileLog.Info("视频记录es更新成功, pdfId:" + docId)
  269. }(audioEdit.ToView())
  270. br.Msg = "编辑成功"
  271. br.Ret = 200
  272. br.Success = true
  273. }
  274. // DeleteVideo
  275. // @Title 删除音频
  276. //
  277. // @Description 删除音频
  278. // @Success 200 {object} models.ReportAuthorResp
  279. // @router /deleteVideo [post]
  280. func (this *VideoController) DeleteVideo() {
  281. br := new(models.BaseResponse).Init()
  282. defer func() {
  283. this.Data["json"] = br
  284. this.ServeJSON()
  285. }()
  286. var req request.VideoReq
  287. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  288. br.Msg = "参数解析失败"
  289. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  290. return
  291. }
  292. if req.VideoId <= 0 {
  293. br.Msg = "视频ID为空"
  294. return
  295. }
  296. var err error
  297. audioDelete := &models.Media{
  298. Id: req.VideoId,
  299. Deleted: 1,
  300. }
  301. err = models.DeleteMedia(audioDelete)
  302. if err != nil {
  303. br.Msg = "删除失败"
  304. br.ErrMsg = "视频删除失败,Err:" + err.Error()
  305. return
  306. }
  307. // 添加es
  308. go func(audio *models.ESMedia) {
  309. docId := strconv.Itoa(audio.MediaId)
  310. err = elastic.EsDeleteData(utils.MEDIA_INDEX, docId)
  311. if err != nil {
  312. utils.FileLog.Info("视频记录es删除失败,Err:" + err.Error())
  313. return
  314. }
  315. utils.FileLog.Info("视频记录es删除成功, pdfId:" + docId)
  316. }(audioDelete.ToView())
  317. br.Msg = "删除成功"
  318. br.Ret = 200
  319. br.Success = true
  320. }
  321. // VideoList
  322. // @Title 研报列表
  323. // @Description pdf研报列表
  324. // @Param PageSize query int true "每页数据条数"
  325. // @Param CurrentIndex query int true "当前页页码,从1开始"
  326. // @Param ClassifyIds query string true "二级分类id,可多选用英文,隔开"
  327. // @Param KeyWord query string true "报告标题/创建人"
  328. // @Param SortType query string true "排序方式"
  329. // @Success 200 {object} models.ReportAuthorResp
  330. // @router /videoList [get]
  331. func (this *VideoController) VideoList() {
  332. br := new(models.BaseResponse).Init()
  333. defer func() {
  334. this.Data["json"] = br
  335. this.ServeJSON()
  336. }()
  337. pageSize, _ := this.GetInt("PageSize")
  338. currentIndex, _ := this.GetInt("CurrentIndex")
  339. sortType := this.GetString("SortType")
  340. KeyWord := this.GetString("KeyWord")
  341. var condition string
  342. var pars []interface{}
  343. if pageSize <= 0 {
  344. pageSize = utils.PageSize20
  345. }
  346. if currentIndex <= 0 {
  347. currentIndex = 1
  348. }
  349. if KeyWord != "" {
  350. condition += " AND media_name like '%" + KeyWord + "%'"
  351. }
  352. sortCondition := " ORDER BY published_time "
  353. if sortType == "" {
  354. sortType = "DESC"
  355. }
  356. sortCondition = sortCondition + sortType
  357. total, err := models.GetMediaCountByCondition(models.Video, condition, pars)
  358. if err != nil {
  359. br.Msg = "获取视频列表失败"
  360. br.ErrMsg = "获取视频列表统计失败,Err:" + err.Error()
  361. return
  362. }
  363. startSize := utils.StartIndex(currentIndex, pageSize)
  364. List, err := models.GetMediaByCondition(models.Video, condition, sortCondition, pars, startSize, pageSize)
  365. if err != nil {
  366. br.Msg = "获取视频列表失败"
  367. br.ErrMsg = "获取视频列表失败,Err:" + err.Error()
  368. return
  369. }
  370. var reportViewList []*models.MediaView
  371. for _, report := range List {
  372. reportView := report.ToMediaView()
  373. reportViewList = append(reportViewList, reportView)
  374. }
  375. page := paging.GetPaging(currentIndex, pageSize, total)
  376. resp := new(response.MediaListResp)
  377. resp.List = reportViewList
  378. resp.Paging = page
  379. br.Ret = 200
  380. br.Success = true
  381. br.Data = resp
  382. br.Msg = "获取成功"
  383. }
  384. type BoxHeader struct {
  385. Size uint32
  386. FourccType [4]byte
  387. Size64 uint64
  388. }
  389. // GetMP4Duration 获取视频时长,以秒计
  390. func GetMP4Duration(reader io.ReaderAt) (lengthOfTime int, err error) {
  391. var info = make([]byte, 0x10)
  392. var boxHeader BoxHeader
  393. var offset int64 = 0
  394. // 获取moov结构偏移
  395. for {
  396. _, err = reader.ReadAt(info, offset)
  397. if err == io.EOF {
  398. fmt.Println("Reached EOF without finding moov box.")
  399. return 0, fmt.Errorf("moov box not found")
  400. }
  401. if err != nil {
  402. return 0, fmt.Errorf("error reading at offset %d: %w", offset, err)
  403. }
  404. boxHeader = getHeaderBoxInfo(info)
  405. fourccType := getFourccType(boxHeader)
  406. if fourccType == "moov" {
  407. fmt.Println("Found moov box at offset", offset)
  408. break
  409. }
  410. nextOffset := int64(boxHeader.Size)
  411. if fourccType == "mdat" && boxHeader.Size == 1 {
  412. nextOffset = int64(boxHeader.Size64)
  413. }
  414. if nextOffset == 0 {
  415. return 0, fmt.Errorf("box size is zero, which is invalid and likely means a parsing error")
  416. }
  417. offset += nextOffset
  418. }
  419. // 获取moov结构开头一部分
  420. moovStartBytes := make([]byte, 0x100)
  421. _, err = reader.ReadAt(moovStartBytes, offset)
  422. if err != nil {
  423. return 0, fmt.Errorf("error reading moov box at offset %d: %w", offset, err)
  424. }
  425. // 定义timeScale与Duration偏移
  426. timeScaleOffset := 0x1C
  427. durationOffset := 0x20
  428. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  429. duration := binary.BigEndian.Uint32(moovStartBytes[durationOffset : durationOffset+4])
  430. fmt.Printf("timeScale: %d, duration: %d\n", timeScale, duration)
  431. if timeScale == 0 {
  432. return 0, fmt.Errorf("timeScale is zero, division by zero is not possible")
  433. }
  434. lengthOfTime = int(duration / timeScale)
  435. return
  436. }
  437. // getHeaderBoxInfo 获取头信息
  438. func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
  439. buf := bytes.NewBuffer(data)
  440. binary.Read(buf, binary.BigEndian, &boxHeader)
  441. if boxHeader.Size == 1 { // Large Size
  442. binary.Read(buf, binary.BigEndian, &boxHeader.Size64)
  443. }
  444. return
  445. }
  446. // UploadFile @Title 上传图片
  447. // @Description 上传视频
  448. // @Param File query file true "文件"
  449. // @Success 200 {object} models.ReportAuthorResp
  450. // @router /uploadFile [post]
  451. func (this *VideoController) UploadFile() {
  452. br := new(models.BaseResponse).Init()
  453. defer func() {
  454. this.Data["json"] = br
  455. this.ServeJSON()
  456. }()
  457. f, h, err := this.GetFile("File")
  458. if err != nil {
  459. br.Msg = "获取资源信息失败"
  460. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  461. return
  462. }
  463. if !utils.CheckImageFormat(h.Filename, f, h) {
  464. br.Msg = "图片上传失败"
  465. br.ErrMsg = "图片上传失败,不支持的文件格式"
  466. return
  467. }
  468. defer f.Close()
  469. size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
  470. if err != nil {
  471. size = 100
  472. }
  473. if h.Size > 1024*1024*int64(size) {
  474. br.Msg = fmt.Sprintf("图片大小不能超过%dK", size)
  475. br.ErrMsg = "图片上传失败,Err:" + err.Error()
  476. return
  477. }
  478. ext := path.Ext(h.Filename)
  479. dateDir := time.Now().Format("20060102")
  480. uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
  481. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  482. if err != nil {
  483. br.Msg = "存储目录创建失败"
  484. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  485. return
  486. }
  487. randStr := utils.GetRandStringNoSpecialChar(28)
  488. fileName := randStr + ext
  489. fpath := uploadDir + "/" + fileName
  490. err = this.SaveToFile("File", fpath)
  491. if err != nil {
  492. br.Msg = "图片上传失败"
  493. br.ErrMsg = "图片上传失败,Err:" + err.Error()
  494. return
  495. }
  496. audioUploadDir := utils.RESOURCE_DIR + "img/"
  497. savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
  498. audioName := utils.GetRandStringNoSpecialChar(28)
  499. savePdfToOssPath += audioName + ext
  500. defer func() {
  501. err = os.Remove(fpath)
  502. fmt.Sprintf("删除文件失败:%v", err)
  503. }()
  504. ossClient := oss.NewOssClient()
  505. if ossClient == nil {
  506. br.Msg = "图片上传失败"
  507. br.ErrMsg = "初始化OSS服务失败"
  508. return
  509. }
  510. mp3Url, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
  511. if err != nil {
  512. br.Msg = "图片上传失败"
  513. br.ErrMsg = "图片上传失败,Err:" + err.Error()
  514. return
  515. }
  516. base := path.Base(h.Filename)
  517. resp := new(response.MediaUploadResp)
  518. resp.Url = mp3Url
  519. resp.FileName = base
  520. br.Data = resp
  521. br.Msg = "上传成功"
  522. br.Ret = 200
  523. br.Success = true
  524. }
  525. type Chunk struct {
  526. Filename string
  527. UniqueCode string
  528. ChunkNumber int
  529. TotalChunks int
  530. Data []byte
  531. }
  532. var chunksMap = make(map[string][]Chunk)
  533. // getFourccType 获取信息头类型
  534. func getFourccType(boxHeader BoxHeader) (fourccType string) {
  535. return string(boxHeader.FourccType[:])
  536. }