video.go 8.8 KB

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