audio.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package controllers
  2. import (
  3. "encoding/binary"
  4. "encoding/json"
  5. "eta/eta_mini_crm_ht/models"
  6. "eta/eta_mini_crm_ht/models/request"
  7. "eta/eta_mini_crm_ht/models/response"
  8. "eta/eta_mini_crm_ht/services"
  9. "eta/eta_mini_crm_ht/services/elastic"
  10. "eta/eta_mini_crm_ht/utils"
  11. "fmt"
  12. "github.com/rdlucklib/rdluck_tools/paging"
  13. "github.com/tcolgate/mp3"
  14. "mime/multipart"
  15. "os"
  16. "path"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. var (
  22. audioType = map[string]int{
  23. ".mp3": 1,
  24. ".m4a": 1,
  25. }
  26. )
  27. type AudioController struct {
  28. BaseAuthController
  29. }
  30. // UploadAudio @Title 上传视频
  31. // @Description 上传视频
  32. // @Param File query file true "文件"
  33. // @Success 200 {object} models.ReportAuthorResp
  34. // @router /uploadAudio [post]
  35. func (this *AudioController) UploadAudio() {
  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_AUDIO_SIZE)
  49. if err != nil {
  50. size = 100
  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 := audioType[lowCaseExt]; !ok {
  60. br.Msg = "音频格式不正确"
  61. br.ErrMsg = "音频上传失败,Err:" + err.Error()
  62. return
  63. }
  64. var duration int
  65. if lowCaseExt == ".m4a" {
  66. }
  67. if lowCaseExt == ".mp3" {
  68. duration, err = mp3Duration(f)
  69. }
  70. if err != nil {
  71. br.Msg = "音频上传失败"
  72. br.ErrMsg = "解析音频时常失败,Err:" + err.Error()
  73. return
  74. }
  75. dateDir := time.Now().Format("20060102")
  76. uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
  77. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  78. if err != nil {
  79. br.Msg = "存储目录创建失败"
  80. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  81. return
  82. }
  83. randStr := utils.GetRandStringNoSpecialChar(28)
  84. fileName := randStr + ext
  85. fpath := uploadDir + "/" + fileName
  86. err = this.SaveToFile("File", fpath)
  87. if err != nil {
  88. br.Msg = "音频上传失败"
  89. br.ErrMsg = "音频上传失败,Err:" + err.Error()
  90. return
  91. }
  92. audioUploadDir := utils.RESOURCE_DIR + "audio/"
  93. savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
  94. audioName := utils.GetRandStringNoSpecialChar(28)
  95. savePdfToOssPath += audioName + ext
  96. defer func() {
  97. err = os.Remove(fpath)
  98. fmt.Sprintf("删除文件失败:%v", err)
  99. }()
  100. ossClient := services.NewOssClient()
  101. if ossClient == nil {
  102. br.Msg = "音频上传失败"
  103. br.ErrMsg = "初始化OSS服务失败"
  104. return
  105. }
  106. mp3Url, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
  107. if err != nil {
  108. br.Msg = "音频上传失败"
  109. br.ErrMsg = "音频上传失败,Err:" + err.Error()
  110. return
  111. }
  112. base := path.Base(h.Filename)
  113. resp := new(response.MediaUploadResp)
  114. resp.Url = mp3Url
  115. resp.FileName = base
  116. resp.DurationMillisecond = duration
  117. br.Data = resp
  118. br.Msg = "上传成功"
  119. br.Ret = 200
  120. br.Success = true
  121. }
  122. func mp3Duration(file multipart.File) (duration int, err error) {
  123. mp3File := mp3.NewDecoder(file)
  124. var totalDuration time.Duration
  125. skipped := 0
  126. for {
  127. frame := mp3.Frame{}
  128. if err = mp3File.Decode(&frame, &skipped); err != nil {
  129. break
  130. }
  131. totalDuration += frame.Duration()
  132. }
  133. duration = int(totalDuration.Milliseconds())
  134. return
  135. }
  136. func m4aDuration(file multipart.File) (duration int, err error) {
  137. var info = make([]byte, 0x10)
  138. var boxHeader BoxHeader
  139. var offset int64 = 0
  140. // 获取moov结构偏移
  141. for {
  142. _, err = file.ReadAt(info, offset)
  143. if err != nil {
  144. return
  145. }
  146. boxHeader = getHeaderBoxInfo(info)
  147. fourccType := getFourccType(boxHeader)
  148. if fourccType == "moov" {
  149. break
  150. }
  151. // 有一部分mp4 mdat尺寸过大需要特殊处理
  152. if fourccType == "mdat" {
  153. if boxHeader.Size == 1 {
  154. offset += int64(boxHeader.Size64)
  155. continue
  156. }
  157. }
  158. offset += int64(boxHeader.Size)
  159. }
  160. // 获取moov结构开头一部分
  161. moovStartBytes := make([]byte, 0x100)
  162. _, err = file.ReadAt(moovStartBytes, offset)
  163. if err != nil {
  164. return
  165. }
  166. // 定义timeScale与Duration偏移
  167. timeScaleOffset := 0x1C
  168. durationOffest := 0x20
  169. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  170. Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
  171. duration = int(Duration * 1000 / timeScale)
  172. return
  173. }
  174. // AddAudio @Title 新增音频
  175. // @Description 新增音频
  176. // @Param File query file true "文件"
  177. // @Success 200 {object} models.ReportAuthorResp
  178. // @router /addAudio [post]
  179. func (this *AudioController) AddAudio() {
  180. br := new(models.BaseResponse).Init()
  181. defer func() {
  182. this.Data["json"] = br
  183. this.ServeJSON()
  184. }()
  185. var req request.AudioReq
  186. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  187. br.Msg = "参数解析失败"
  188. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  189. return
  190. }
  191. if req.AudioName == "" {
  192. br.Msg = "音频名称为空"
  193. return
  194. }
  195. if req.AnalystId == 0 {
  196. br.Msg = "研究员ID为空"
  197. return
  198. }
  199. if req.AnalystName == "" {
  200. br.Msg = "研究员名称为空"
  201. return
  202. }
  203. if req.DurationMillisecond == 0 {
  204. br.Msg = "音频时长为空"
  205. return
  206. }
  207. if req.SrcUrl == "" {
  208. br.Msg = "音频地址为空"
  209. return
  210. }
  211. var err error
  212. audioInsert := &models.Media{
  213. AuthorId: req.AnalystId,
  214. AuthorName: req.AnalystName,
  215. MediaType: models.Audio,
  216. Src: req.SrcUrl,
  217. MediaName: req.AudioName,
  218. SourceType: req.SrcUrl[strings.LastIndex(req.SrcUrl, ".")+1:],
  219. MediaPlayMilliseconds: req.DurationMillisecond,
  220. PermissionIds: req.PermissionIds,
  221. SendStatus: models.UNSEND,
  222. PublishedTime: time.Now(),
  223. Deleted: 0,
  224. CreatedTime: time.Now(),
  225. }
  226. err = models.InsertMedia(audioInsert)
  227. if err != nil {
  228. br.Msg = "添加失败"
  229. br.ErrMsg = "音频新增失败,Err:" + err.Error()
  230. return
  231. }
  232. //audioInsert.Id = int(insertId)
  233. // 添加es
  234. go func(audio *models.ESMedia) {
  235. docId := strconv.Itoa(audio.MediaId)
  236. err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
  237. if err != nil {
  238. utils.FileLog.Info("音频记录es新增失败,Err:" + err.Error())
  239. return
  240. }
  241. utils.FileLog.Info("音频记录es新增成功, pdfId:" + docId)
  242. }(audioInsert.ToView())
  243. // 创建消息
  244. _, _ = services.CreateMeta(audioInsert.AuthorName, audioInsert.AuthorId, audioInsert.Id, audioInsert.PublishedTime.Format(time.DateTime), models.AudioSourceType)
  245. br.Msg = "添加成功"
  246. br.Ret = 200
  247. br.Success = true
  248. }
  249. // @Title 编辑音频
  250. //
  251. // @Description 编辑音频
  252. // @Success 200 {object} models.ReportAuthorResp
  253. // @router /editAudio [post]
  254. func (this *AudioController) EditAudio() {
  255. br := new(models.BaseResponse).Init()
  256. defer func() {
  257. this.Data["json"] = br
  258. this.ServeJSON()
  259. }()
  260. var req request.AudioReq
  261. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  262. br.Msg = "参数解析失败"
  263. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  264. return
  265. }
  266. if req.AudioId <= 0 {
  267. br.Msg = "音频ID为空"
  268. return
  269. }
  270. if req.AudioName == "" {
  271. br.Msg = "音频名称为空"
  272. return
  273. }
  274. if req.AnalystId == 0 {
  275. br.Msg = "研究员ID为空"
  276. return
  277. }
  278. if req.AnalystName == "" {
  279. br.Msg = "研究员名称为空"
  280. return
  281. }
  282. if req.DurationMillisecond == 0 {
  283. br.Msg = "音频时长为空"
  284. return
  285. }
  286. if req.SrcUrl == "" {
  287. br.Msg = "音频地址为空"
  288. return
  289. }
  290. var err error
  291. audioEdit := &models.Media{
  292. Id: req.AudioId,
  293. AuthorId: req.AnalystId,
  294. AuthorName: req.AnalystName,
  295. MediaType: models.Audio,
  296. Src: req.SrcUrl,
  297. MediaName: req.AudioName,
  298. SourceType: "mp3",
  299. MediaPlayMilliseconds: req.DurationMillisecond,
  300. PermissionIds: req.PermissionIds,
  301. }
  302. _, err = models.UpdateMedia(audioEdit)
  303. if err != nil {
  304. br.Msg = "更新失败"
  305. br.ErrMsg = "音频更新失败,Err:" + err.Error()
  306. return
  307. }
  308. // 添加es
  309. go func(audio *models.ESMedia) {
  310. docId := strconv.Itoa(audio.MediaId)
  311. err = elastic.EsAddOrEditMedia(utils.MEDIA_INDEX, docId, audio)
  312. if err != nil {
  313. utils.FileLog.Info("音频记录es更新失败,Err:" + err.Error())
  314. return
  315. }
  316. utils.FileLog.Info("音频记录es更新成功, pdfId:" + docId)
  317. }(audioEdit.ToView())
  318. br.Msg = "编辑成功"
  319. br.Ret = 200
  320. br.Success = true
  321. }
  322. // DeleteAudio
  323. // @Title 删除音频
  324. //
  325. // @Description 删除音频
  326. // @Success 200 {object} models.ReportAuthorResp
  327. // @router /deleteAudio [post]
  328. func (this *AudioController) DeleteAudio() {
  329. br := new(models.BaseResponse).Init()
  330. defer func() {
  331. this.Data["json"] = br
  332. this.ServeJSON()
  333. }()
  334. var req request.AudioReq
  335. if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
  336. br.Msg = "参数解析失败"
  337. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  338. return
  339. }
  340. if req.AudioId <= 0 {
  341. br.Msg = "音频ID为空"
  342. return
  343. }
  344. var err error
  345. audioDelete := &models.Media{
  346. Id: req.AudioId,
  347. Deleted: 1,
  348. }
  349. err = models.DeleteMedia(audioDelete)
  350. if err != nil {
  351. br.Msg = "删除失败"
  352. br.ErrMsg = "音频删除失败,Err:" + err.Error()
  353. return
  354. }
  355. // 添加es
  356. go func(audio *models.ESMedia) {
  357. docId := strconv.Itoa(audio.MediaId)
  358. err = elastic.EsDeleteData(utils.MEDIA_INDEX, docId)
  359. if err != nil {
  360. utils.FileLog.Info("音频记录es删除失败,Err:" + err.Error())
  361. return
  362. }
  363. utils.FileLog.Info("音频记录es删除成功, pdfId:" + docId)
  364. }(audioDelete.ToView())
  365. br.Msg = "删除成功"
  366. br.Ret = 200
  367. br.Success = true
  368. }
  369. // AudioList
  370. // @Title 研报列表
  371. // @Description pdf研报列表
  372. // @Param PageSize query int true "每页数据条数"
  373. // @Param CurrentIndex query int true "当前页页码,从1开始"
  374. // @Param ClassifyIds query string true "二级分类id,可多选用英文,隔开"
  375. // @Param KeyWord query string true "报告标题/创建人"
  376. // @Param SortType query string true "排序方式"
  377. // @Success 200 {object} models.ReportAuthorResp
  378. // @router /audioList [get]
  379. func (this *AudioController) AudioList() {
  380. br := new(models.BaseResponse).Init()
  381. defer func() {
  382. this.Data["json"] = br
  383. this.ServeJSON()
  384. }()
  385. pageSize, _ := this.GetInt("PageSize")
  386. currentIndex, _ := this.GetInt("CurrentIndex")
  387. sortType := this.GetString("SortType")
  388. KeyWord := this.GetString("KeyWord")
  389. var condition string
  390. var pars []interface{}
  391. if pageSize <= 0 {
  392. pageSize = utils.PageSize20
  393. }
  394. if currentIndex <= 0 {
  395. currentIndex = 1
  396. }
  397. if KeyWord != "" {
  398. condition += " AND media_name like '%" + KeyWord + "%'"
  399. }
  400. sortCondition := " ORDER BY published_time "
  401. if sortType == "" {
  402. sortType = "DESC"
  403. }
  404. sortCondition = sortCondition + sortType
  405. total, err := models.GetMediaCountByCondition(models.Audio, condition, pars)
  406. if err != nil {
  407. br.Msg = "获取音频列表失败"
  408. br.ErrMsg = "获取音频列表统计失败,Err:" + err.Error()
  409. return
  410. }
  411. startSize := utils.StartIndex(currentIndex, pageSize)
  412. reportList, err := models.GetMediaByCondition(models.Audio, condition, sortCondition, pars, startSize, pageSize)
  413. if err != nil {
  414. br.Msg = "获取音频列表失败"
  415. br.ErrMsg = "获取音频列表失败,Err:" + err.Error()
  416. return
  417. }
  418. var reportViewList []*models.MediaView
  419. for _, report := range reportList {
  420. reportView := report.ToMediaView()
  421. reportViewList = append(reportViewList, reportView)
  422. }
  423. page := paging.GetPaging(currentIndex, pageSize, total)
  424. resp := new(response.MediaListResp)
  425. resp.List = reportViewList
  426. resp.Paging = page
  427. br.Ret = 200
  428. br.Success = true
  429. br.Data = resp
  430. br.Msg = "获取成功"
  431. }