video.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.ReportDetail) (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 := ``
  95. //上传到阿里云 和 minio
  96. if utils.ObjectStorageClient == "minio" {
  97. uploadUrl, err = UploadAudioToMinIo(saveName, savePath)
  98. if err != nil {
  99. err = errors.New("UploadAudioAliyun Err:" + err.Error())
  100. return
  101. }
  102. } else {
  103. uploadUrl, err = UploadAudioAliyun(saveName, savePath)
  104. if err != nil {
  105. err = errors.New("UploadAudioAliyun Err:" + err.Error())
  106. return
  107. }
  108. }
  109. fileBody, err := ioutil.ReadFile(savePath)
  110. videoSize := len(fileBody)
  111. sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
  112. sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)
  113. playSeconds, err := mp3duration.Calculate(savePath)
  114. if playSeconds <= 0 {
  115. playSeconds, err = utils.GetVideoPlaySeconds(savePath)
  116. if err != nil {
  117. err = errors.New("GetVideoPlaySeconds Err:" + err.Error())
  118. return
  119. }
  120. }
  121. if playSeconds > 0 {
  122. if utils.FileIsExist(savePath) {
  123. os.Remove(savePath)
  124. }
  125. }
  126. err = models.ModifyReportVideo(report.Id, uploadUrl, videoName, sizeStr, playSeconds)
  127. return
  128. }
  129. func GetChineseCount(str1 string) []string {
  130. fontArr := make([]string, 0)
  131. str := ""
  132. count := 0
  133. for _, char := range str1 {
  134. str += string(char)
  135. if unicode.Is(unicode.Han, char) {
  136. count++
  137. if count >= 1700 {
  138. fontArr = append(fontArr, str)
  139. str = ""
  140. count = 0
  141. }
  142. }
  143. }
  144. fontArr = append(fontArr, str)
  145. return fontArr
  146. }
  147. // BoxHeader 信息头
  148. type BoxHeader struct {
  149. Size uint32
  150. FourccType [4]byte
  151. Size64 uint64
  152. }
  153. // GetMP4Duration 获取视频时长,以秒计
  154. func GetMP4Duration(reader io.ReaderAt) (lengthOfTime uint32, err error) {
  155. var info = make([]byte, 0x10)
  156. var boxHeader BoxHeader
  157. var offset int64 = 0
  158. // 获取moov结构偏移
  159. for {
  160. _, err = reader.ReadAt(info, offset)
  161. if err != nil {
  162. return
  163. }
  164. boxHeader = getHeaderBoxInfo(info)
  165. fourccType := getFourccType(boxHeader)
  166. if fourccType == "moov" {
  167. break
  168. }
  169. // 有一部分mp4 mdat尺寸过大需要特殊处理
  170. if fourccType == "mdat" {
  171. if boxHeader.Size == 1 {
  172. offset += int64(boxHeader.Size64)
  173. continue
  174. }
  175. }
  176. offset += int64(boxHeader.Size)
  177. }
  178. // 获取moov结构开头一部分
  179. moovStartBytes := make([]byte, 0x100)
  180. _, err = reader.ReadAt(moovStartBytes, offset)
  181. if err != nil {
  182. return
  183. }
  184. // 定义timeScale与Duration偏移
  185. timeScaleOffset := 0x1C
  186. durationOffest := 0x20
  187. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  188. Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
  189. lengthOfTime = Duration / timeScale
  190. return
  191. }
  192. // getHeaderBoxInfo 获取头信息
  193. func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
  194. buf := bytes.NewBuffer(data)
  195. binary.Read(buf, binary.BigEndian, &boxHeader)
  196. return
  197. }
  198. // getFourccType 获取信息头类型
  199. func getFourccType(boxHeader BoxHeader) (fourccType string) {
  200. fourccType = string(boxHeader.FourccType[:])
  201. return
  202. }
  203. // CreateReportVideo 生成报告video
  204. func CreateReportVideo(reportTitle, reportContent, reportTime string) (uploadUrl, videoName, sizeStr string, playSeconds float64, err error) {
  205. defer func() {
  206. if err != nil {
  207. utils.FileLog.Error("CreateReportVideo Err:%s", err.Error())
  208. go alarm_msg.SendAlarmMsg("CreateReportVideo, reportTitle:"+reportTitle+", Err:"+err.Error(), 3)
  209. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "CreateReportVideo, reportTitle:" + reportTitle +", Err:"+err.Error(), utils.EmailSendToUsers)
  210. }
  211. }()
  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. saveName := utils.GetRandStringNoSpecialChar(16) + ".mp3"
  262. savePath := "./" + saveName
  263. //if utils.FileIsExist(savePath) {
  264. // os.Remove(savePath)
  265. //}
  266. contentArr := GetChineseCount(videoContent)
  267. for _, v := range contentArr {
  268. newText := v
  269. param.Data.Text = base64.StdEncoding.EncodeToString([]byte(newText))
  270. result, tmpErr := json.Marshal(param)
  271. if tmpErr != nil {
  272. return
  273. }
  274. err = GetXfVideo(result, savePath, xfReq)
  275. if err != nil {
  276. err = errors.New("GetXfVideo Err:" + err.Error())
  277. utils.FileLog.Error("GetXfVideo err", err.Error())
  278. return
  279. }
  280. time.Sleep(5 * time.Second)
  281. }
  282. //上传到阿里云 和 minio
  283. if utils.ObjectStorageClient == "minio" {
  284. uploadUrl, err = UploadAudioToMinIo(saveName, savePath)
  285. if err != nil {
  286. err = errors.New("UploadAudioAliyun Err:" + err.Error())
  287. return
  288. }
  289. } else {
  290. uploadUrl, err = UploadAudioAliyun(saveName, savePath)
  291. if err != nil {
  292. err = errors.New("UploadAudioAliyun Err:" + err.Error())
  293. return
  294. }
  295. }
  296. fileBody, err := ioutil.ReadFile(savePath)
  297. videoSize := len(fileBody)
  298. sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
  299. sizeStr = utils.SubFloatToFloatStr(sizeFloat, 2)
  300. playSeconds, err = mp3duration.Calculate(savePath)
  301. if playSeconds <= 0 {
  302. playSeconds, err = utils.GetVideoPlaySeconds(savePath)
  303. if err != nil {
  304. err = errors.New("GetVideoPlaySeconds Err:" + err.Error())
  305. return
  306. }
  307. }
  308. if playSeconds > 0 {
  309. if utils.FileIsExist(savePath) {
  310. os.Remove(savePath)
  311. }
  312. }
  313. return
  314. }