audio.go 12 KB

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