video.go 9.0 KB

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