video.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. }
  28. }()
  29. conf, e := models.GetBusinessConf()
  30. if e != nil {
  31. err = fmt.Errorf("获取基础配置失败, Err: " + e.Error())
  32. return
  33. }
  34. if conf[models.BusinessConfUseXf] != "true" {
  35. return
  36. }
  37. if conf[models.BusinessConfXfAppid] == "" || conf[models.BusinessConfXfApiKey] == "" || conf[models.BusinessConfXfApiSecret] == "" || conf[models.BusinessConfXfVcn] == "" {
  38. return
  39. }
  40. var xfReq XfParams
  41. xfReq.XfAPPID = conf[models.BusinessConfXfAppid]
  42. xfReq.XfAPIKey = conf[models.BusinessConfXfApiKey]
  43. xfReq.XfAPISecret = conf[models.BusinessConfXfApiSecret]
  44. createTime := report.CreateTime.Format("0102")
  45. videoName := report.Title + "(" + createTime + ")"
  46. content := html.UnescapeString(report.Content)
  47. content = strings.Replace(content, "Powered", "", -1)
  48. content = strings.Replace(content, "by", "", -1)
  49. content = strings.Replace(content, "Froala", "", -1)
  50. content = strings.Replace(content, "Editor", "", -1)
  51. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  52. if err != nil {
  53. return
  54. }
  55. param := new(models.XfSendParam)
  56. param.Common.AppId = conf[models.BusinessConfXfAppid]
  57. param.Business.Aue = "lame"
  58. param.Business.Sfl = 1
  59. param.Business.Auf = "audio/L16;rate=16000"
  60. param.Business.Vcn = conf[models.BusinessConfXfVcn]
  61. param.Business.Speed = 50
  62. param.Business.Volume = 100
  63. param.Business.Pitch = 50
  64. param.Business.Bgs = 0
  65. param.Business.Tte = "UTF8"
  66. param.Business.Reg = "2"
  67. param.Business.Rdn = "0"
  68. param.Data.Status = 2
  69. videoContent := doc.Text()
  70. saveName := utils.GetRandStringNoSpecialChar(16) + ".mp3"
  71. savePath := "./" + saveName
  72. defer func() {
  73. if utils.FileIsExist(savePath) {
  74. os.Remove(savePath)
  75. }
  76. }()
  77. videoContent = strings.TrimSpace(videoContent)
  78. if videoContent == `` {
  79. return
  80. }
  81. contentArr := GetChineseCount(videoContent)
  82. for _, v := range contentArr {
  83. newText := v
  84. param.Data.Text = base64.StdEncoding.EncodeToString([]byte(newText))
  85. result, err := json.Marshal(param)
  86. if err != nil {
  87. return err
  88. }
  89. err = GetXfVideo(result, savePath, xfReq)
  90. if err != nil {
  91. err = errors.New("GetXfVideo Err:" + err.Error())
  92. utils.FileLog.Error("GetXfVideo err", err.Error())
  93. return err
  94. }
  95. time.Sleep(5 * time.Second)
  96. }
  97. uploadUrl := ``
  98. ossClient := NewOssClient()
  99. if ossClient == nil {
  100. err = fmt.Errorf("初始化OSS服务失败")
  101. return
  102. }
  103. uploadUrl, err = ossClient.UploadFile(saveName, savePath, "")
  104. if err != nil {
  105. err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
  106. return
  107. }
  108. fileBody, err := os.ReadFile(savePath)
  109. videoSize := len(fileBody)
  110. sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
  111. sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)
  112. playSeconds, err := mp3duration.Calculate(savePath)
  113. if playSeconds <= 0 {
  114. playSeconds, err = utils.GetVideoPlaySeconds(savePath)
  115. if err != nil {
  116. err = errors.New("GetVideoPlaySeconds Err:" + err.Error())
  117. return
  118. }
  119. }
  120. err = models.ModifyReportVideo(report.Id, uploadUrl, videoName, sizeStr, playSeconds)
  121. return
  122. }
  123. func GetChineseCount(str1 string) []string {
  124. fontArr := make([]string, 0)
  125. str := ""
  126. count := 0
  127. for _, char := range str1 {
  128. str += string(char)
  129. if unicode.Is(unicode.Han, char) {
  130. count++
  131. if count >= 1700 {
  132. fontArr = append(fontArr, str)
  133. str = ""
  134. count = 0
  135. }
  136. }
  137. }
  138. fontArr = append(fontArr, str)
  139. return fontArr
  140. }
  141. type BoxHeader struct {
  142. Size uint32
  143. FourccType [4]byte
  144. Size64 uint64
  145. }
  146. func GetMP4Duration(reader io.ReaderAt) (lengthOfTime uint32, err error) {
  147. var info = make([]byte, 0x10)
  148. var boxHeader BoxHeader
  149. var offset int64 = 0
  150. for {
  151. _, err = reader.ReadAt(info, offset)
  152. if err != nil {
  153. return
  154. }
  155. boxHeader = getHeaderBoxInfo(info)
  156. fourccType := getFourccType(boxHeader)
  157. if fourccType == "moov" {
  158. break
  159. }
  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. moovStartBytes := make([]byte, 0x100)
  169. _, err = reader.ReadAt(moovStartBytes, offset)
  170. if err != nil {
  171. return
  172. }
  173. timeScaleOffset := 0x1C
  174. durationOffest := 0x20
  175. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  176. Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
  177. lengthOfTime = Duration / timeScale
  178. return
  179. }
  180. func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
  181. buf := bytes.NewBuffer(data)
  182. binary.Read(buf, binary.BigEndian, &boxHeader)
  183. return
  184. }
  185. func getFourccType(boxHeader BoxHeader) (fourccType string) {
  186. fourccType = string(boxHeader.FourccType[:])
  187. return
  188. }
  189. func CreateReportVideo(reportTitle, reportContent, reportTime string) (uploadUrl, videoName, sizeStr string, playSeconds float64, err error) {
  190. defer func() {
  191. if err != nil {
  192. utils.FileLog.Error("CreateReportVideo Err:%s", err.Error())
  193. go alarm_msg.SendAlarmMsg("CreateReportVideo, reportTitle:"+reportTitle+", Err:"+err.Error(), 3)
  194. }
  195. }()
  196. reportContent = strings.TrimSpace(reportContent)
  197. if reportContent == `` {
  198. return
  199. }
  200. conf, e := models.GetBusinessConf()
  201. if e != nil {
  202. err = fmt.Errorf("获取基础配置失败, Err: " + e.Error())
  203. return
  204. }
  205. if conf[models.BusinessConfUseXf] != "true" {
  206. return
  207. }
  208. if conf[models.BusinessConfXfAppid] == "" || conf[models.BusinessConfXfApiKey] == "" || conf[models.BusinessConfXfApiSecret] == "" || conf[models.BusinessConfXfVcn] == "" {
  209. return
  210. }
  211. var xfReq XfParams
  212. xfReq.XfAPPID = conf[models.BusinessConfXfAppid]
  213. xfReq.XfAPIKey = conf[models.BusinessConfXfApiKey]
  214. xfReq.XfAPISecret = conf[models.BusinessConfXfApiSecret]
  215. ct, err := time.Parse(utils.FormatDateTime, reportTime)
  216. if err != nil {
  217. return
  218. }
  219. createTime := ct.Format("0102")
  220. videoName = reportTitle + "(" + createTime + ")"
  221. content := html.UnescapeString(reportContent)
  222. content = strings.Replace(content, "Powered", "", -1)
  223. content = strings.Replace(content, "by", "", -1)
  224. content = strings.Replace(content, "Froala", "", -1)
  225. content = strings.Replace(content, "Editor", "", -1)
  226. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  227. if err != nil {
  228. return
  229. }
  230. param := new(models.XfSendParam)
  231. param.Common.AppId = conf[models.BusinessConfXfAppid]
  232. param.Business.Aue = "lame"
  233. param.Business.Sfl = 1
  234. param.Business.Auf = "audio/L16;rate=16000"
  235. param.Business.Vcn = conf[models.BusinessConfXfVcn]
  236. param.Business.Speed = 50
  237. param.Business.Volume = 100
  238. param.Business.Pitch = 50
  239. param.Business.Bgs = 0
  240. param.Business.Tte = "UTF8"
  241. param.Business.Reg = "2"
  242. param.Business.Rdn = "0"
  243. param.Data.Status = 2
  244. videoContent := doc.Text()
  245. videoContent = strings.TrimSpace(videoContent)
  246. if videoContent == `` {
  247. return
  248. }
  249. saveName := utils.GetRandStringNoSpecialChar(16) + ".mp3"
  250. savePath := "./" + saveName
  251. defer func() {
  252. if utils.FileIsExist(savePath) {
  253. os.Remove(savePath)
  254. }
  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. ossClient := NewOssClient()
  273. if ossClient == nil {
  274. err = fmt.Errorf("初始化OSS服务失败")
  275. return
  276. }
  277. uploadUrl, err = ossClient.UploadFile(saveName, savePath, "")
  278. if err != nil {
  279. err = fmt.Errorf("文件上传失败, Err: %s", 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. return
  295. }