share_poster.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/PuerkitoBio/goquery"
  7. "hongze/hongze_yb/global"
  8. "hongze/hongze_yb/models/tables/yb_poster_config"
  9. "hongze/hongze_yb/models/tables/yb_poster_resource"
  10. "hongze/hongze_yb/models/tables/yb_suncode_pars"
  11. "hongze/hongze_yb/services/alarm_msg"
  12. "hongze/hongze_yb/services/wx_app"
  13. "hongze/hongze_yb/utils"
  14. "io/ioutil"
  15. "net/http"
  16. "os"
  17. "strings"
  18. "time"
  19. )
  20. var (
  21. ServerUrl = "http://127.0.0.1:5008/"
  22. VoiceBroadcastShareImgSource = "voice_broadcast_share_img"
  23. )
  24. // SharePosterReq 分享海报请求体
  25. type SharePosterReq struct {
  26. CodePage string `json:"code_page" description:"太阳码page"`
  27. CodeScene string `json:"code_scene" description:"太阳码scene"`
  28. Source string `json:"source" description:"来源"`
  29. Version string `json:"version" description:"海报版本号" `
  30. Pars string `json:"pars" description:"海报动态信息"`
  31. }
  32. type Html2ImgResp struct {
  33. Code int `json:"code"`
  34. Msg string `json:"msg"`
  35. Data string `json:"data"`
  36. }
  37. // postHtml2Img 请求htm2img接口
  38. func postHtml2Img(param map[string]interface{}) (resp *Html2ImgResp, err error) {
  39. // 目前仅此处调用该接口,暂不加授权、校验等
  40. postUrl := ServerUrl + "htm2img"
  41. postData, err := json.Marshal(param)
  42. if err != nil {
  43. return
  44. }
  45. result, err := Html2ImgHttpPost(postUrl, string(postData), "application/json")
  46. if err != nil {
  47. return
  48. }
  49. if err = json.Unmarshal(result, &resp); err != nil {
  50. return
  51. }
  52. return resp, nil
  53. }
  54. // Html2ImgHttpPost post请求
  55. func Html2ImgHttpPost(url, postData string, params ...string) ([]byte, error) {
  56. body := ioutil.NopCloser(strings.NewReader(postData))
  57. client := &http.Client{}
  58. req, err := http.NewRequest("POST", url, body)
  59. if err != nil {
  60. return nil, err
  61. }
  62. contentType := "application/x-www-form-urlencoded;charset=utf-8"
  63. if len(params) > 0 && params[0] != "" {
  64. contentType = params[0]
  65. }
  66. req.Header.Set("Content-Type", contentType)
  67. resp, err := client.Do(req)
  68. if err != nil {
  69. return nil, err
  70. }
  71. defer resp.Body.Close()
  72. b, err := ioutil.ReadAll(resp.Body)
  73. fmt.Println("HttpPost:" + string(b))
  74. return b, err
  75. }
  76. // CreateAndUploadSunCode 生成太阳码并上传OSS
  77. func CreateAndUploadSunCode(page, scene, version string) (imgUrl string, err error) {
  78. if page == "" {
  79. err = errors.New("page不能为空")
  80. return
  81. }
  82. path := fmt.Sprint(page, "?", scene)
  83. exist, err := yb_poster_resource.GetPosterByCondition(path, "qrcode", version)
  84. if err != nil && err != utils.ErrNoRow {
  85. return
  86. }
  87. if exist != nil && exist.ImgURL != "" {
  88. return exist.ImgURL, nil
  89. }
  90. // scene超过32位会生成失败,md5处理至32位
  91. sceneMD5 := "a=1"
  92. if scene != "" {
  93. sceneMD5 = utils.MD5(scene)
  94. }
  95. picByte, err := wx_app.GetSunCode(page, sceneMD5)
  96. if err != nil {
  97. return
  98. }
  99. // 生成图片
  100. localPath := "./static/img"
  101. fileName := utils.GetRandStringNoSpecialChar(28) + ".png"
  102. fpath := fmt.Sprint(localPath, "/", fileName)
  103. f, err := os.Create(fpath)
  104. if err != nil {
  105. return
  106. }
  107. if _, err = f.Write(picByte); err != nil {
  108. return
  109. }
  110. defer func() {
  111. f.Close()
  112. os.Remove(fpath)
  113. }()
  114. // 上传OSS
  115. fileDir := "images/yb/suncode/"
  116. imgUrl, err = UploadAliyunToDir(fileName, fpath, fileDir)
  117. if err != nil {
  118. return
  119. }
  120. // 记录二维码信息
  121. newPoster := &yb_poster_resource.YbPosterResource{
  122. Path: path,
  123. ImgURL: imgUrl,
  124. Type: "qrcode",
  125. Version: version,
  126. CreateTime: time.Now(),
  127. }
  128. err = newPoster.Create()
  129. if err != nil {
  130. return
  131. }
  132. // 记录参数md5
  133. if scene != "" {
  134. newPars := &yb_suncode_pars.YbSuncodePars{
  135. Scene: scene,
  136. SceneKey: sceneMD5,
  137. CreateTime: time.Now(),
  138. }
  139. err = newPars.Create()
  140. }
  141. return
  142. }
  143. // CreatePosterFromSourceV2 生成分享海报(通过配置获取相关信息)
  144. func CreatePosterFromSourceV2(codePage, codeScene, source, version, pars string) (imgUrl string, err error) {
  145. var errMsg string
  146. defer func() {
  147. if err != nil {
  148. global.LOG.Critical(fmt.Sprintf("CreatePosterFromSource: source=%s, pars:%s, errMsg:%s", source, pars, errMsg))
  149. reqSlice := make([]string, 0)
  150. reqSlice = append(reqSlice, fmt.Sprint("CodePage:", codePage, "\n"))
  151. reqSlice = append(reqSlice, fmt.Sprint("CodeScene:", codeScene, "\n"))
  152. reqSlice = append(reqSlice, fmt.Sprint("Source:", source, "\n"))
  153. reqSlice = append(reqSlice, fmt.Sprint("Version:", version, "\n"))
  154. reqSlice = append(reqSlice, fmt.Sprint("Pars:", pars, "\n"))
  155. go alarm_msg.SendAlarmMsg("CreatePosterFromSource生成分享海报失败, Msg:"+errMsg+";Err:"+err.Error()+"\n;Req:\n"+strings.Join(reqSlice, ";"), 3)
  156. }
  157. }()
  158. if codePage == "" || source == "" || pars == "" {
  159. errMsg = "参数有误"
  160. err = errors.New(errMsg)
  161. return
  162. }
  163. path := fmt.Sprint(codePage, "?", codeScene)
  164. // 非列表来源获取历史图片,无则生成
  165. if !strings.Contains(source, "list") && source != "price_driven" {
  166. poster, tmpErr := yb_poster_resource.GetPosterByCondition(path, "poster", version)
  167. if tmpErr != nil && tmpErr != utils.ErrNoRow {
  168. err = tmpErr
  169. return
  170. }
  171. if poster != nil && poster.ImgURL != "" {
  172. imgUrl = poster.ImgURL
  173. return
  174. }
  175. }
  176. ybPosterConfig, err := yb_poster_config.GetBySource(source)
  177. if err != nil {
  178. return
  179. }
  180. width := ybPosterConfig.Width
  181. height := ybPosterConfig.Hight
  182. //生成太阳码
  183. sunCodeUrl, err := CreateAndUploadSunCode(codePage, codeScene, version)
  184. if err != nil {
  185. return
  186. }
  187. //sunCodeUrl := ``
  188. // 填充html内容
  189. contentStr, newHeight, err := fillContent2HtmlV2(source, pars, sunCodeUrl, height, *ybPosterConfig)
  190. if err != nil {
  191. errMsg = "html内容有误"
  192. return
  193. }
  194. global.LOG.Critical(contentStr)
  195. //return
  196. // 请求python服务htm2img
  197. htm2ImgReq := make(map[string]interface{})
  198. htm2ImgReq["html_content"] = contentStr
  199. htm2ImgReq["width"] = width
  200. htm2ImgReq["height"] = newHeight
  201. res, err := postHtml2Img(htm2ImgReq)
  202. if err != nil || res == nil {
  203. errMsg = "html转图片请求失败"
  204. return
  205. }
  206. if res.Code != 200 {
  207. errMsg = "html转图片请求失败"
  208. err = errors.New("html转图片失败: " + res.Msg)
  209. return
  210. }
  211. imgUrl = res.Data
  212. // 记录海报信息
  213. newPoster := &yb_poster_resource.YbPosterResource{
  214. Path: path,
  215. ImgURL: imgUrl,
  216. Type: "poster",
  217. Version: version,
  218. CreateTime: time.Now(),
  219. }
  220. err = newPoster.Create()
  221. return
  222. }
  223. // HtmlReplaceConfig html替换配置
  224. type HtmlReplaceConfig struct {
  225. TemplateStr string `json:"template_str"`
  226. ReplaceStr string `json:"replace_str"`
  227. }
  228. // DefaultValueConfig 默认值的配置
  229. type DefaultValueConfig struct {
  230. Key string `json:"key"`
  231. UseOtherKey string `json:"use_other_key"`
  232. Value string `json:"value"`
  233. ConditionKey string `json:"condition_key"`
  234. }
  235. // fillContent2Html 填充HTML动态内容
  236. func fillContent2HtmlV2(source, pars, sunCodeUrl string, height float64, ybPosterConfig yb_poster_config.YbPosterConfig) (contentStr string, newHeight float64, err error) {
  237. paramsMap := make(map[string]string)
  238. if err = json.Unmarshal([]byte(pars), &paramsMap); err != nil {
  239. return
  240. }
  241. //fmt.Println(paramsMap)
  242. //html替换规则
  243. htmlReplaceConfigList := make([]HtmlReplaceConfig, 0)
  244. if err = json.Unmarshal([]byte(ybPosterConfig.HTMLReplaceConfig), &htmlReplaceConfigList); err != nil {
  245. return
  246. }
  247. newHeight = height
  248. contentStr = ybPosterConfig.HTMLTemplate
  249. // 默认数据替换
  250. defaultValueConfigMap := make([]DefaultValueConfig, 0)
  251. if ybPosterConfig.DefaultValueConfig != `` {
  252. if err = json.Unmarshal([]byte(ybPosterConfig.DefaultValueConfig), &defaultValueConfigMap); err != nil {
  253. return
  254. }
  255. }
  256. // 列表的动态内容不完整的用默认内容的填充
  257. //var emptyTime1, emptyTime2 bool
  258. conditionKeyValMap := make(map[string]string)
  259. for _, v := range defaultValueConfigMap {
  260. if v.ConditionKey == `` {
  261. continue
  262. }
  263. conditionKeyVal, ok := conditionKeyValMap[v.ConditionKey]
  264. if !ok {
  265. conditionKeyVal = paramsMap[v.ConditionKey]
  266. conditionKeyValMap[v.ConditionKey] = conditionKeyVal
  267. }
  268. if conditionKeyVal == `` {
  269. paramsMap[v.Key] = v.Value
  270. if v.UseOtherKey != `` {
  271. if tmpVal, ok := paramsMap[v.UseOtherKey]; ok {
  272. paramsMap[v.Key] = tmpVal
  273. }
  274. }
  275. }
  276. }
  277. // 填充指定内容
  278. switch source {
  279. case "report_detail": //需要将简介处理下
  280. reportAbstract := paramsMap["report_abstract"]
  281. doc, tmpErr := goquery.NewDocumentFromReader(strings.NewReader(reportAbstract))
  282. if tmpErr != nil {
  283. err = tmpErr
  284. return
  285. }
  286. abstract := ""
  287. doc.Find("p").Each(func(i int, s *goquery.Selection) {
  288. phtml, tmpErr := s.Html()
  289. if tmpErr != nil {
  290. err = tmpErr
  291. return
  292. }
  293. st := s.Text()
  294. if st != "" && st != "<br>" && st != "<br style=\"max-width: 100%;\">" && !strings.Contains(phtml, "iframe") {
  295. abstract = abstract + "<p>" + phtml + "</p>"
  296. }
  297. })
  298. paramsMap["report_abstract"] = abstract
  299. case "activity_list":
  300. bgColorMap := map[string]string{
  301. "未开始": "#E3B377",
  302. "进行中": "#3385FF",
  303. "已结束": "#A2A2A2",
  304. }
  305. statusItemMap := map[string]string{
  306. "未开始": "block",
  307. "进行中": "none",
  308. "已结束": "none",
  309. }
  310. offlineMap := map[string]string{
  311. "线上会议": "none",
  312. "线下沙龙": "block",
  313. }
  314. onlineMap := map[string]string{
  315. "线上会议": "block",
  316. "线下沙龙": "none",
  317. }
  318. listTitle := paramsMap["list_title"]
  319. status1 := paramsMap["status_1"]
  320. if status1 != "未开始" {
  321. newHeight = 1715
  322. }
  323. status2 := paramsMap["status_2"]
  324. paramsMap["list_title"] = "弘则FICC周度电话会安排"
  325. paramsMap["bg_color_1"] = bgColorMap[status1]
  326. paramsMap["show_item_1"] = statusItemMap[status1]
  327. paramsMap["show_offline_1"] = offlineMap[listTitle]
  328. paramsMap["show_online_1"] = onlineMap[listTitle]
  329. paramsMap["bg_color_2"] = bgColorMap[status2]
  330. paramsMap["show_item_2"] = statusItemMap[status2]
  331. paramsMap["show_offline_2"] = offlineMap[listTitle]
  332. paramsMap["show_online_2"] = onlineMap[listTitle]
  333. // 用默认内容填充的活动时间字体颜色调至看不见
  334. color1 := "#999"
  335. color2 := "#999"
  336. if paramsMap["empty_time_1"] == "true" {
  337. color1 = "#fff"
  338. }
  339. if paramsMap["empty_time_2"] == "true" {
  340. color2 = "#fff"
  341. }
  342. paramsMap["time_color_1"] = color1
  343. paramsMap["time_color_2"] = color2
  344. }
  345. contentStr = strings.Replace(contentStr, "{{SUN_CODE}}", sunCodeUrl, 1)
  346. for _, v := range htmlReplaceConfigList {
  347. tmpVal, ok := paramsMap[v.ReplaceStr]
  348. if !ok {
  349. tmpVal = ``
  350. }
  351. contentStr = strings.Replace(contentStr, v.TemplateStr, tmpVal, 1)
  352. }
  353. return
  354. }
  355. // GetDynamicShareImg 生成动态分享图
  356. func GetDynamicShareImg(source, pars string) (imgUrl string, err error) {
  357. if source == "" {
  358. err = errors.New("图片来源有误")
  359. return
  360. }
  361. imgConfig, e := yb_poster_config.GetBySource(source)
  362. if e != nil {
  363. err = errors.New("获取图片配置失败")
  364. return
  365. }
  366. // 填充html内容
  367. content, newHeight, e := fillContent2HtmlV2(source, pars, "", imgConfig.Hight, *imgConfig)
  368. if e != nil {
  369. err = errors.New("html内容有误")
  370. return
  371. }
  372. htm2ImgReq := make(map[string]interface{})
  373. htm2ImgReq["html_content"] = content
  374. htm2ImgReq["width"] = imgConfig.Width
  375. htm2ImgReq["height"] = newHeight
  376. res, e := postHtml2Img(htm2ImgReq)
  377. if e != nil || res == nil {
  378. err = errors.New("html转图片请求失败")
  379. return
  380. }
  381. if res.Code != 200 {
  382. err = errors.New("html转图片请求失败: " + res.Msg)
  383. return
  384. }
  385. imgUrl = res.Data
  386. return
  387. }