video.go 9.9 KB

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