123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584 |
- package cygx
- import (
- "encoding/json"
- "errors"
- "fmt"
- "hongze/hz_crm_api/models"
- "hongze/hz_crm_api/models/cygx"
- "hongze/hz_crm_api/services"
- "hongze/hz_crm_api/services/alarm_msg"
- "hongze/hz_crm_api/utils"
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "strconv"
- "strings"
- "time"
- )
- var (
- ServerUrl = "http://127.0.0.1:5008/"
- Cygx_activity_sigin_html = "cygx_activity_sigin_html"
- Cygx_mp3_html = "cygx_mp3_html"
- Cygx_mp4_html = "cygx_mp4_html"
- Cygx_mp3_yx_html = "cygx_mp3_yx_html"
- Cygx_mp4_yx_html = "cygx_mp4_yx_html"
- )
- type Html2ImgResp struct {
- Code int `json:"code"`
- Msg string `json:"msg"`
- Data string `json:"data"`
- }
- // postHtml2Img 请求htm2img接口
- func postHtml2Img(param map[string]interface{}) (resp *Html2ImgResp, err error) {
- // 目前仅此处调用该接口,暂不加授权、校验等
- postUrl := ServerUrl + "htm2img"
- postData, err := json.Marshal(param)
- if err != nil {
- return
- }
- result, err := Html2ImgHttpPost(postUrl, string(postData), "application/json")
- if err != nil {
- return
- }
- if err = json.Unmarshal(result, &resp); err != nil {
- return
- }
- return resp, nil
- }
- // Html2ImgHttpPost post请求
- func Html2ImgHttpPost(url, postData string, params ...string) ([]byte, error) {
- body := ioutil.NopCloser(strings.NewReader(postData))
- client := &http.Client{}
- req, err := http.NewRequest("POST", url, body)
- if err != nil {
- return nil, err
- }
- contentType := "application/x-www-form-urlencoded;charset=utf-8"
- if len(params) > 0 && params[0] != "" {
- contentType = params[0]
- }
- req.Header.Set("Content-Type", contentType)
- resp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- b, err := ioutil.ReadAll(resp.Body)
- fmt.Println("HttpPost:" + string(b))
- return b, err
- }
- //func init() {
- // MakeActivitySigninImg(2161)
- //}
- // MakeActivitySigninImg 生成太阳码并上传OSS
- func MakeActivitySigninImg(activityId int) (imgUrl string, err error) {
- var msg string
- defer func() {
- if err != nil || msg != "" {
- fmt.Println(err)
- utils.FileLog.Info("MakeActivitySigninImg Err:", err.Error())
- go alarm_msg.SendAlarmMsg("扫码签到日志记录,失败,活动ID:"+strconv.Itoa(activityId)+err.Error()+";msg:"+msg, 3)
- }
- }()
- activityInfo, e := cygx.GetAddActivityInfoById(activityId)
- if e != nil {
- err = errors.New("活动不存在, Err: " + e.Error())
- return
- }
- if activityInfo == nil {
- return
- }
- if activityInfo.ActivityTypeId != 5 && activityInfo.ActivityTypeId != 6 && activityInfo.ActivityTypeId != 8 {
- return
- }
- itemToken, err := models.GetWxToken(utils.WxCygxAppId, utils.WxCygxAppSecret)
- if err != nil {
- return
- }
- if itemToken.AccessToken == "" {
- msg = "accessToken is empty"
- return
- }
- var envVersion string
- var resourceUrl string
- if utils.RunMode == "release" {
- envVersion = "release"
- } else {
- envVersion = "trial"
- }
- url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
- method := "POST"
- payload := strings.NewReader(`{
- "page":"` + utils.WX_MSG_PATH_ACTIVITY_SIGNIN + `",
- "scene":"` + strconv.Itoa(activityId) + `",
- "env_version":"` + envVersion + `",
- "check_path":false,
- "auto_color":true
- }`)
- client := &http.Client{}
- req, err := http.NewRequest(method, url, payload)
- if err != nil {
- msg = "获取微信二维码失败,Err:" + err.Error()
- return
- }
- req.Header.Add("Content-Type", "application/json")
- postBody, err := client.Do(req)
- if err != nil {
- msg = "获取微信二维码失败,Err:" + err.Error()
- return
- }
- defer postBody.Body.Close()
- uploadDir := "static/img/share/"
- uuid := utils.GetRandStringNoSpecialChar(28)
- if !utils.FileIsExist(uploadDir) {
- err = os.MkdirAll(uploadDir, 0755)
- if err != nil {
- msg = "生成文件夹失败,Err:" + err.Error()
- return
- }
- }
- imagePath := uploadDir + uuid + ".jpg"
- switch header := postBody.Header.Get("Content-Type"); {
- case strings.HasPrefix(header, "application/json"):
- tokenResp := ReturnBodyRule{}
- decoder := json.NewDecoder(postBody.Body)
- if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
- msg = "获取微信二维码失败,Err:" + decodeErr.Error()
- return
- }
- case strings.HasPrefix(header, "image"):
- reply, e := ioutil.ReadAll(postBody.Body)
- if e != nil {
- err = e
- msg = "获取微信二维码失败,Err:" + err.Error()
- return
- }
- imageContent, e := os.Create(imagePath)
- if e != nil {
- err = e
- msg = "获取微信二维码失败,Err:" + err.Error()
- return
- }
- writeStringRes, e := io.WriteString(imageContent, string(reply))
- if e != nil {
- err = e
- fmt.Println(writeStringRes)
- return
- }
- closeErr := imageContent.Close()
- if closeErr != nil {
- err = closeErr
- return
- }
- randStr := utils.GetRandStringNoSpecialChar(28)
- fileName := randStr + ".jpg"
- savePath := uploadDir + time.Now().Format("200601/20060102/")
- savePath += fileName
- //上传到阿里云
- err = services.UploadFileToAliyun(fileName, imagePath, savePath)
- if err != nil {
- fmt.Println("文件上传失败,Err:" + err.Error())
- return
- }
- fileHost := "https://hzstatic.hzinsights.com/"
- resourceUrl = fileHost + savePath
- defer func() {
- os.Remove(imagePath)
- }()
- default:
- msg = "生成二维码失败"
- return
- }
- detailConfig, e := cygx.GetCygxConfigDetailByCode(Cygx_activity_sigin_html)
- if e != nil {
- err = errors.New("GetCygxConfigDetailByCode 获取配置签到码格式信息失败, Err: " + e.Error())
- return
- }
- configValue := detailConfig.ConfigValue
- configValue = strings.Replace(configValue, "{{TITLE}}", activityInfo.ActivityName, -1)
- configValue = strings.Replace(configValue, "{{IMG}}", resourceUrl, -1)
- configValue = strings.Replace(configValue, "{{PLEASE}}", "请扫码确认签到", -1)
- configValue = strings.Replace(configValue, "{{SHOWTEXT}}", "将签到成功页面出示给接待人员", -1)
- htm2ImgReq := make(map[string]interface{})
- htm2ImgReq["html_content"] = configValue
- htm2ImgReq["width"] = 1364
- htm2ImgReq["height"] = 2060
- res, err := postHtml2Img(htm2ImgReq)
- if err != nil || res == nil {
- msg = "html转图片请求失败"
- return
- }
- if res.Code != 200 {
- msg = "html转图片请求失败"
- err = errors.New("html转图片失败: " + res.Msg)
- return
- }
- imgUrl = res.Data
- // 记录海报信息
- err = cygx.UpdateCygxActivitySigninImg(imgUrl, activityId)
- if err != nil {
- return
- }
- item := new(cygx.CygxActivityPoster)
- item.ActivityId = activityId
- item.ImgXcx = resourceUrl
- item.ImgPoster = imgUrl
- item.CreateTime = time.Now()
- err = cygx.AddCygxActivityPoster(item)
- return
- }
- // 生成音视频分享封面图
- func MakeCygxMp3HtmlImg(videoDuration string, chartPermissionId int) (imgUrl string, err error) {
- var msg string
- defer func() {
- if err != nil || msg != "" {
- fmt.Println(err)
- go alarm_msg.SendAlarmMsg("生成音视频分享封面图,失败 MakeCygxMp3HtmlImg:"+err.Error()+";msg:"+msg, 3)
- }
- }()
- var configCode string
- if chartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
- configCode = Cygx_mp3_yx_html
- } else {
- configCode = Cygx_mp3_html
- }
- detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
- if e != nil {
- err = errors.New("GetCygxConfigDetailByCode 获取配置生成音视频分享封面图格式信息失败, Err: " + e.Error())
- return
- }
- // 处理时长带有小数点的字符串
- slice := strings.Split(videoDuration, ".")
- for k, v := range slice {
- if k != 0 {
- continue
- }
- videoDuration = v
- }
- //先转换时长展示样式再替换
- secondNum, _ := strconv.Atoi(videoDuration)
- videoDuration = utils.HideSecondsToMs(secondNum)
- configValue := detailConfig.ConfigValue
- configValue = strings.Replace(configValue, "{{TIME}}", videoDuration, -1)
- htm2ImgReq := make(map[string]interface{})
- htm2ImgReq["html_content"] = configValue
- htm2ImgReq["width"] = 1364
- htm2ImgReq["height"] = 2060
- res, err := postHtml2Img(htm2ImgReq)
- if err != nil || res == nil {
- msg = "html转图片请求失败"
- return
- }
- if res.Code != 200 {
- msg = "html转图片请求失败"
- err = errors.New("html转图片失败: " + res.Msg)
- return
- }
- imgUrl = res.Data
- return
- }
- // 生成音视频分享封面图
- func MakeCygxMp4HtmlImg(videoDuration string, chartPermissionId int) (imgUrl string, err error) {
- var msg string
- defer func() {
- if err != nil || msg != "" {
- fmt.Println(err)
- go alarm_msg.SendAlarmMsg("生成音视频分享封面图,失败 MakeCygxMp4HtmlImg:"+err.Error()+";msg:"+msg, 3)
- }
- }()
- var configCode string
- if chartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
- configCode = Cygx_mp4_yx_html
- } else {
- configCode = Cygx_mp4_html
- }
- detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
- if e != nil {
- err = errors.New("GetCygxConfigDetailByCode 获取配置生成音视频分享封面图格式信息失败, Err: " + e.Error())
- return
- }
- // 处理时长带有小数点的字符串
- slice := strings.Split(videoDuration, ".")
- for k, v := range slice {
- if k != 0 {
- continue
- }
- videoDuration = v
- }
- //先转换时长展示样式再替换
- secondNum, _ := strconv.Atoi(videoDuration)
- videoDuration = utils.HideSecondsToMs(secondNum)
- configValue := detailConfig.ConfigValue
- configValue = strings.Replace(configValue, "{{TIME}}", videoDuration, -1)
- htm2ImgReq := make(map[string]interface{})
- htm2ImgReq["html_content"] = configValue
- htm2ImgReq["width"] = 1364
- htm2ImgReq["height"] = 2060
- res, err := postHtml2Img(htm2ImgReq)
- if err != nil || res == nil {
- msg = "html转图片请求失败"
- return
- }
- if res.Code != 200 {
- msg = "html转图片请求失败"
- err = errors.New("html转图片失败: " + res.Msg)
- return
- }
- imgUrl = res.Data
- return
- }
- //func init() {
- // //MakeActivityMomentsImg(2850)
- // var condition string
- // var pars []interface{}
- // condition = " AND chart_permission_id = 31 AND publish_status = 1 AND active_state = 1 ORDER BY activity_id DESC "
- // list, errList := cygx.GetActivityListAll(condition, pars, 0, 9999)
- // if errList != nil {
- // fmt.Println(errList)
- // return
- // }
- // fmt.Println("list", len(list))
- //
- // //return
- // for _, v := range list {
- // MakeActivityMomentsImg(v.ActivityId)
- // }
- //
- //}
- // 生成活动分享到朋友圈的图片
- func MakeActivityMomentsImg(activityId int) {
- var err error
- //time.Sleep(3*time.Second) // 有时候同时添加多个活动,延迟三秒
- defer func() {
- if err != nil {
- fmt.Println("err:", err)
- go alarm_msg.SendAlarmMsg("生成活动分享到朋友圈的图片失败,MakeActivityMomentsImg Err:"+err.Error()+"活动ID"+strconv.Itoa(activityId), 3)
- }
- }()
- detail, e := cygx.GetAddActivityInfoById(activityId)
- if e != nil {
- err = errors.New("GetCygxReportSelectionInfoById, Err: " + e.Error())
- return
- }
- // 不是研选活动不生成图片
- if detail.ChartPermissionId != utils.CHART_PERMISSION_ID_YANXUAN {
- return
- }
- var configCode string
- if detail.IsResearchPoints == 1 {
- configCode = "activity_moments_img_points_html" // 扣点活动
- } else {
- configCode = "activity_moments_img_html" // 非扣点活动
- }
- detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
- if e != nil {
- err = errors.New("GetCygxConfigDetailByCode 获取生成活动分享到朋友圈的图片格式信息失败, Err: " + e.Error())
- return
- }
- configValue := detailConfig.ConfigValue
- configValue = strings.Replace(configValue, "{{Title}}", detail.ActivityName, -1)
- configValue = strings.Replace(configValue, "{{ActivityTypeName}}", detail.ActivityTypeName, -1)
- configValue = strings.Replace(configValue, "{{Label}}", detail.Label, -1)
- configValue = strings.Replace(configValue, "{{ActivityTimeText}}", detail.ActivityTimeText, -1)
- htm2ImgReq := make(map[string]interface{})
- htm2ImgReq["html_content"] = configValue
- htm2ImgReq["width"] = 2250
- htm2ImgReq["height"] = 3813
- res, err := postHtml2Img(htm2ImgReq)
- if err != nil || res == nil {
- err = errors.New("html转图片失败: ")
- return
- }
- if res.Code != 200 {
- err = errors.New("html转图片失败: " + res.Msg)
- return
- }
- imgUrl := res.Data
- // 记录海报信息
- err = cygx.UpdateCygxActivityMomentsImg(imgUrl, activityId)
- if err != nil {
- return
- }
- }
- // MakeMfyxActivitySigninImg 生成mfyx太阳码并上传OSS
- //func MakeMfyxActivitySigninImg(activityId int) (imgUrl string, err error) {
- // var msg string
- // defer func() {
- // if err != nil || msg != "" {
- // fmt.Println(err)
- // utils.FileLog.Info("MakeMfyxActivitySigninImg Err:", err.Error())
- // go alarm_msg.SendAlarmMsg("扫码签到日志记录,失败,活动ID:"+strconv.Itoa(activityId)+err.Error()+";msg:"+msg, 3)
- // }
- // }()
- // activityInfo, e := cygx.GetAddActivityInfoById(activityId)
- // if e != nil {
- // err = errors.New("活动不存在, Err: " + e.Error())
- // return
- // }
- // if activityInfo == nil {
- // return
- // }
- // if activityInfo.ActivityTypeId != 5 && activityInfo.ActivityTypeId != 6 && activityInfo.ActivityTypeId != 8 {
- // return
- // }
- // itemToken, err := models.GetWxToken(utils.WxMfyxAppId, utils.WxMfyxAppSecret)
- // if err != nil {
- // return
- // }
- // if itemToken.AccessToken == "" {
- // msg = "accessToken is empty"
- // return
- // }
- // var envVersion string
- // var resourceUrl string
- // if utils.RunMode == "release" {
- // envVersion = "release"
- // } else {
- // envVersion = "trial"
- // }
- // url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
- // method := "POST"
- // payload := strings.NewReader(`{
- // "page":"` + utils.WX_MSG_PATH_ACTIVITY_SIGNIN + `",
- // "scene":"` + strconv.Itoa(activityId) + `",
- // "env_version":"` + envVersion + `",
- // "check_path":false,
- // "auto_color":true
- // }`)
- // client := &http.Client{}
- // req, err := http.NewRequest(method, url, payload)
- // if err != nil {
- // msg = "获取微信二维码失败,Err:" + err.Error()
- // return
- // }
- // req.Header.Add("Content-Type", "application/json")
- // postBody, err := client.Do(req)
- // if err != nil {
- // msg = "获取微信二维码失败,Err:" + err.Error()
- // return
- // }
- // defer postBody.Body.Close()
- // uploadDir := "static/img/share/"
- // uuid := utils.GetRandStringNoSpecialChar(28)
- // if !utils.FileIsExist(uploadDir) {
- // err = os.MkdirAll(uploadDir, 0755)
- // if err != nil {
- // msg = "生成文件夹失败,Err:" + err.Error()
- // return
- // }
- // }
- // imagePath := uploadDir + uuid + ".jpg"
- // switch header := postBody.Header.Get("Content-Type"); {
- // case strings.HasPrefix(header, "application/json"):
- // tokenResp := ReturnBodyRule{}
- // decoder := json.NewDecoder(postBody.Body)
- // if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
- // msg = "获取微信二维码失败,Err:" + decodeErr.Error()
- // return
- // }
- // case strings.HasPrefix(header, "image"):
- // reply, e := ioutil.ReadAll(postBody.Body)
- // if e != nil {
- // err = e
- // msg = "获取微信二维码失败,Err:" + err.Error()
- // return
- // }
- // imageContent, e := os.Create(imagePath)
- // if e != nil {
- // err = e
- // msg = "获取微信二维码失败,Err:" + err.Error()
- // return
- // }
- // writeStringRes, e := io.WriteString(imageContent, string(reply))
- // if e != nil {
- // err = e
- // fmt.Println(writeStringRes)
- // return
- // }
- // closeErr := imageContent.Close()
- // if closeErr != nil {
- // err = closeErr
- // return
- // }
- // randStr := utils.GetRandStringNoSpecialChar(28)
- // fileName := randStr + ".jpg"
- // savePath := uploadDir + time.Now().Format("200601/20060102/")
- // savePath += fileName
- // //上传到阿里云
- // err = services.UploadFileToAliyun(fileName, imagePath, savePath)
- // if err != nil {
- // fmt.Println("文件上传失败,Err:" + err.Error())
- // return
- // }
- // fileHost := "https://hzstatic.hzinsights.com/"
- // resourceUrl = fileHost + savePath
- // defer func() {
- // os.Remove(imagePath)
- // }()
- // default:
- // msg = "生成二维码失败"
- // return
- // }
- //
- // detailConfig, e := cygx.GetCygxConfigDetailByCode(Cygx_activity_sigin_html)
- // if e != nil {
- // err = errors.New("GetCygxConfigDetailByCode 获取配置签到码格式信息失败, Err: " + e.Error())
- // return
- // }
- // configValue := detailConfig.ConfigValue
- // configValue = strings.Replace(configValue, "{{TITLE}}", activityInfo.ActivityName, -1)
- // configValue = strings.Replace(configValue, "{{IMG}}", resourceUrl, -1)
- // configValue = strings.Replace(configValue, "{{PLEASE}}", "请扫码确认签到", -1)
- // configValue = strings.Replace(configValue, "{{SHOWTEXT}}", "将签到成功页面出示给接待人员", -1)
- // htm2ImgReq := make(map[string]interface{})
- // htm2ImgReq["html_content"] = configValue
- // htm2ImgReq["width"] = 1364
- // htm2ImgReq["height"] = 2060
- // res, err := postHtml2Img(htm2ImgReq)
- // if err != nil || res == nil {
- // msg = "html转图片请求失败"
- // return
- // }
- // if res.Code != 200 {
- // msg = "html转图片请求失败"
- // err = errors.New("html转图片失败: " + res.Msg)
- // return
- // }
- // imgUrl = res.Data
- // // 记录海报信息
- //
- // err = cygx.UpdateCygxActivitySigninImg(imgUrl, activityId)
- // if err != nil {
- // return
- // }
- // item := new(cygx.CygxActivityPoster)
- // item.ActivityId = activityId
- // item.ImgXcx = resourceUrl
- // item.ImgPoster = imgUrl
- // item.CreateTime = time.Now()
- // err = cygx.AddCygxActivityPoster(item)
- // return
- //}
|