video.go 9.7 KB

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