video.go 7.8 KB

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