video.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package services
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/binary"
  6. "encoding/json"
  7. "errors"
  8. "eta/eta_api/models"
  9. "eta/eta_api/services/alarm_msg"
  10. "eta/eta_api/utils"
  11. "fmt"
  12. "github.com/PuerkitoBio/goquery"
  13. "github.com/kgiannakakis/mp3duration/src/mp3duration"
  14. "html"
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "strings"
  19. "time"
  20. "unicode"
  21. )
  22. func CreateVideo(report *models.Report) (err error) {
  23. defer func() {
  24. if err != nil {
  25. utils.FileLog.Error("CreateVideo Err:%s", err.Error())
  26. go alarm_msg.SendAlarmMsg("CreateVideo, Err:"+err.Error(), 3)
  27. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "Err:"+err.Error(), utils.EmailSendToUsers)
  28. }
  29. }()
  30. // 获取基础配置, 若未配置则直接返回
  31. conf, e := models.GetBusinessConf()
  32. if e != nil {
  33. err = fmt.Errorf("获取基础配置失败, Err: " + e.Error())
  34. return
  35. }
  36. if conf[models.BusinessConfUseXf] != "true" {
  37. return
  38. }
  39. if conf[models.BusinessConfXfAppid] == "" || conf[models.BusinessConfXfApiKey] == "" || conf[models.BusinessConfXfApiSecret] == "" || conf[models.BusinessConfXfVcn] == "" {
  40. return
  41. }
  42. var xfReq XfParams
  43. xfReq.XfAPPID = conf[models.BusinessConfXfAppid]
  44. xfReq.XfAPIKey = conf[models.BusinessConfXfApiKey]
  45. xfReq.XfAPISecret = conf[models.BusinessConfXfApiSecret]
  46. ct, err := time.Parse(utils.FormatDateTime, report.CreateTime)
  47. createTime := ct.Format("0102")
  48. videoName := report.Title + "(" + createTime + ")"
  49. content := html.UnescapeString(report.Content)
  50. content = strings.Replace(content, "Powered", "", -1)
  51. content = strings.Replace(content, "by", "", -1)
  52. content = strings.Replace(content, "Froala", "", -1)
  53. content = strings.Replace(content, "Editor", "", -1)
  54. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  55. if err != nil {
  56. return
  57. }
  58. param := new(models.XfSendParam)
  59. param.Common.AppId = conf[models.BusinessConfXfAppid]
  60. param.Business.Aue = "lame"
  61. param.Business.Sfl = 1
  62. param.Business.Auf = "audio/L16;rate=16000"
  63. param.Business.Vcn = conf[models.BusinessConfXfVcn]
  64. param.Business.Speed = 50
  65. param.Business.Volume = 100
  66. param.Business.Pitch = 50
  67. param.Business.Bgs = 0
  68. param.Business.Tte = "UTF8"
  69. param.Business.Reg = "2"
  70. param.Business.Rdn = "0"
  71. param.Data.Status = 2
  72. videoContent := doc.Text()
  73. saveName := utils.GetRandStringNoSpecialChar(16) + ".mp3"
  74. savePath := "./" + saveName
  75. defer func() {
  76. if utils.FileIsExist(savePath) {
  77. os.Remove(savePath)
  78. }
  79. }()
  80. // 如果没有文本内容,那么就不生成了
  81. videoContent = strings.TrimSpace(videoContent)
  82. if videoContent == `` {
  83. return
  84. }
  85. contentArr := GetChineseCount(videoContent)
  86. for _, v := range contentArr {
  87. newText := v
  88. param.Data.Text = base64.StdEncoding.EncodeToString([]byte(newText))
  89. result, err := json.Marshal(param)
  90. if err != nil {
  91. return err
  92. }
  93. err = GetXfVideo(result, savePath, xfReq)
  94. if err != nil {
  95. err = errors.New("GetXfVideo Err:" + err.Error())
  96. utils.FileLog.Error("GetXfVideo err", err.Error())
  97. return err
  98. }
  99. time.Sleep(5 * time.Second)
  100. }
  101. uploadUrl := ``
  102. ossClient := NewOssClient()
  103. if ossClient == nil {
  104. err = fmt.Errorf("初始化OSS服务失败")
  105. return
  106. }
  107. uploadUrl, err = ossClient.UploadFile(saveName, savePath, "")
  108. if err != nil {
  109. err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
  110. return
  111. }
  112. fileBody, err := os.ReadFile(savePath)
  113. videoSize := len(fileBody)
  114. sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
  115. sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)
  116. playSeconds, err := mp3duration.Calculate(savePath)
  117. if playSeconds <= 0 {
  118. playSeconds, err = utils.GetVideoPlaySeconds(savePath)
  119. if err != nil {
  120. err = errors.New("GetVideoPlaySeconds Err:" + err.Error())
  121. return
  122. }
  123. }
  124. // 修改报告的音频信息
  125. err = models.ModifyReportVideo(report.Id, uploadUrl, videoName, sizeStr, playSeconds)
  126. return
  127. }
  128. func GetChineseCount(str1 string) []string {
  129. fontArr := make([]string, 0)
  130. str := ""
  131. count := 0
  132. for _, char := range str1 {
  133. str += string(char)
  134. if unicode.Is(unicode.Han, char) {
  135. count++
  136. if count >= 1700 {
  137. fontArr = append(fontArr, str)
  138. str = ""
  139. count = 0
  140. }
  141. }
  142. }
  143. fontArr = append(fontArr, str)
  144. return fontArr
  145. }
  146. // BoxHeader 信息头
  147. type BoxHeader struct {
  148. Size uint32
  149. FourccType [4]byte
  150. Size64 uint64
  151. }
  152. // GetMP4Duration 获取视频时长,以秒计
  153. func GetMP4Duration(reader io.ReaderAt) (lengthOfTime uint32, err error) {
  154. var info = make([]byte, 0x10)
  155. var boxHeader BoxHeader
  156. var offset int64 = 0
  157. // 获取moov结构偏移
  158. for {
  159. _, err = reader.ReadAt(info, offset)
  160. if err != nil {
  161. return
  162. }
  163. boxHeader = getHeaderBoxInfo(info)
  164. fourccType := getFourccType(boxHeader)
  165. if fourccType == "moov" {
  166. break
  167. }
  168. // 有一部分mp4 mdat尺寸过大需要特殊处理
  169. if fourccType == "mdat" {
  170. if boxHeader.Size == 1 {
  171. offset += int64(boxHeader.Size64)
  172. continue
  173. }
  174. }
  175. offset += int64(boxHeader.Size)
  176. }
  177. // 获取moov结构开头一部分
  178. moovStartBytes := make([]byte, 0x100)
  179. _, err = reader.ReadAt(moovStartBytes, offset)
  180. if err != nil {
  181. return
  182. }
  183. // 定义timeScale与Duration偏移
  184. timeScaleOffset := 0x1C
  185. durationOffest := 0x20
  186. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  187. Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
  188. lengthOfTime = Duration / timeScale
  189. return
  190. }
  191. // getHeaderBoxInfo 获取头信息
  192. func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
  193. buf := bytes.NewBuffer(data)
  194. binary.Read(buf, binary.BigEndian, &boxHeader)
  195. return
  196. }
  197. // getFourccType 获取信息头类型
  198. func getFourccType(boxHeader BoxHeader) (fourccType string) {
  199. fourccType = string(boxHeader.FourccType[:])
  200. return
  201. }
  202. // CreateReportVideo 生成报告video
  203. func CreateReportVideo(reportTitle, reportContent, reportTime string) (uploadUrl, videoName, sizeStr string, playSeconds float64, err error) {
  204. defer func() {
  205. if err != nil {
  206. utils.FileLog.Error("CreateReportVideo Err:%s", err.Error())
  207. go alarm_msg.SendAlarmMsg("CreateReportVideo, reportTitle:"+reportTitle+", Err:"+err.Error(), 3)
  208. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "CreateReportVideo, reportTitle:" + reportTitle +", Err:"+err.Error(), utils.EmailSendToUsers)
  209. }
  210. }()
  211. // 如果没有文本内容,那么就不生成了
  212. reportContent = strings.TrimSpace(reportContent)
  213. if reportContent == `` {
  214. return
  215. }
  216. // 获取基础配置, 若未配置则直接返回
  217. conf, e := models.GetBusinessConf()
  218. if e != nil {
  219. err = fmt.Errorf("获取基础配置失败, Err: " + e.Error())
  220. return
  221. }
  222. if conf[models.BusinessConfUseXf] != "true" {
  223. return
  224. }
  225. if conf[models.BusinessConfXfAppid] == "" || conf[models.BusinessConfXfApiKey] == "" || conf[models.BusinessConfXfApiSecret] == "" || conf[models.BusinessConfXfVcn] == "" {
  226. return
  227. }
  228. var xfReq XfParams
  229. xfReq.XfAPPID = conf[models.BusinessConfXfAppid]
  230. xfReq.XfAPIKey = conf[models.BusinessConfXfApiKey]
  231. xfReq.XfAPISecret = conf[models.BusinessConfXfApiSecret]
  232. ct, err := time.Parse(utils.FormatDateTime, reportTime)
  233. if err != nil {
  234. return
  235. }
  236. createTime := ct.Format("0102")
  237. videoName = reportTitle + "(" + createTime + ")"
  238. content := html.UnescapeString(reportContent)
  239. content = strings.Replace(content, "Powered", "", -1)
  240. content = strings.Replace(content, "by", "", -1)
  241. content = strings.Replace(content, "Froala", "", -1)
  242. content = strings.Replace(content, "Editor", "", -1)
  243. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  244. if err != nil {
  245. return
  246. }
  247. param := new(models.XfSendParam)
  248. param.Common.AppId = conf[models.BusinessConfXfAppid]
  249. param.Business.Aue = "lame"
  250. param.Business.Sfl = 1
  251. param.Business.Auf = "audio/L16;rate=16000"
  252. param.Business.Vcn = conf[models.BusinessConfXfVcn]
  253. param.Business.Speed = 50
  254. param.Business.Volume = 100
  255. param.Business.Pitch = 50
  256. param.Business.Bgs = 0
  257. param.Business.Tte = "UTF8"
  258. param.Business.Reg = "2"
  259. param.Business.Rdn = "0"
  260. param.Data.Status = 2
  261. videoContent := doc.Text()
  262. // 如果没有文本内容,那么就不生成了
  263. videoContent = strings.TrimSpace(videoContent)
  264. if videoContent == `` {
  265. return
  266. }
  267. saveName := utils.GetRandStringNoSpecialChar(16) + ".mp3"
  268. savePath := "./" + saveName
  269. defer func() {
  270. if utils.FileIsExist(savePath) {
  271. os.Remove(savePath)
  272. }
  273. }()
  274. contentArr := GetChineseCount(videoContent)
  275. for _, v := range contentArr {
  276. newText := v
  277. param.Data.Text = base64.StdEncoding.EncodeToString([]byte(newText))
  278. result, tmpErr := json.Marshal(param)
  279. if tmpErr != nil {
  280. return
  281. }
  282. err = GetXfVideo(result, savePath, xfReq)
  283. if err != nil {
  284. err = errors.New("GetXfVideo Err:" + err.Error())
  285. utils.FileLog.Error("GetXfVideo err", err.Error())
  286. return
  287. }
  288. time.Sleep(5 * time.Second)
  289. }
  290. fmt.Println("savePath:" + savePath)
  291. //上传到阿里云 和 minio
  292. //if utils.ObjectStorageClient == "minio" {
  293. // uploadUrl, err = UploadAudioToMinIo(saveName, savePath)
  294. // if err != nil {
  295. // err = errors.New("UploadAudioAliyun Err:" + err.Error())
  296. // return
  297. // }
  298. //} else {
  299. // uploadUrl, err = UploadAudioAliyun(saveName, savePath)
  300. // if err != nil {
  301. // err = errors.New("UploadAudioAliyun Err:" + err.Error())
  302. // return
  303. // }
  304. //}
  305. ossClient := NewOssClient()
  306. if ossClient == nil {
  307. err = fmt.Errorf("初始化OSS服务失败")
  308. return
  309. }
  310. uploadUrl, err = ossClient.UploadFile(saveName, savePath, "")
  311. if err != nil {
  312. err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
  313. return
  314. }
  315. fileBody, err := ioutil.ReadFile(savePath)
  316. videoSize := len(fileBody)
  317. sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
  318. sizeStr = utils.SubFloatToFloatStr(sizeFloat, 2)
  319. playSeconds, err = mp3duration.Calculate(savePath)
  320. if playSeconds <= 0 {
  321. playSeconds, err = utils.GetVideoPlaySeconds(savePath)
  322. if err != nil {
  323. err = errors.New("GetVideoPlaySeconds Err:" + err.Error())
  324. return
  325. }
  326. }
  327. return
  328. }