Initial commit: web_hghl_server

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 16:28:14 +08:00
co-authored by Claude Opus 4.7
commit 65fca60622
653 changed files with 135901 additions and 0 deletions
+235
View File
@@ -0,0 +1,235 @@
package dataReport
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"videoweb/pub/common/godef"
"videoweb/pub/common/log"
"videoweb/pub/common/useragent"
"videoweb/pub/pubdef"
"github.com/google/uuid"
"github.com/moul/http2curl"
)
var config = Config{}
func Init(c Config) {
config = c
// 根据运行模式设置SDK配置API地址
switch c.RunMod {
case "prod", "release":
sdkConfigAPIURL = sdkConfigAPIProd
default:
sdkConfigAPIURL = sdkConfigAPIDev
}
}
// GenerateGlobalEventID 生成全局唯一的 event_id
func GenerateGlobalEventID() string {
// 生成一个新的 UUID
return strings.ReplaceAll(uuid.New().String(), "-", "")
}
func AsyncReport(eventData interface{}, retryCount int) {
// TODO 后续可改成kafka异步处理
godef.Go(func() {
// 自动重试
baseDelay := 1 * time.Second
for i := 0; i < retryCount; i++ {
err := report(eventData)
if err != nil {
log.Error("Event.report failed", log.Any("retryCount", retryCount), log.Any("eventData", eventData), log.E(err))
// 指数退避 + 随机抖动
sleepTime := time.Duration(math.Pow(2, float64(i)))*baseDelay + time.Duration(rand.Intn(1000))*time.Millisecond
time.Sleep(sleepTime)
continue
}
break
}
})
}
// 上报事件
func report(eventData interface{}) error {
// 将结构体转换为表单数据
formData, err := structToFormData(eventData)
if err != nil {
return err
}
apiUrl := config.ApiUrl + "/api/eventTracking/report.json"
req, err := http.NewRequest("POST", apiUrl, bytes.NewBufferString(formData))
if err != nil {
log.Error("Event report NewRequest fail", log.E(err))
return fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{
Timeout: 5 * time.Second, // 设置超时时间为 5 秒
}
command, _ := http2curl.GetCurlCommand(req)
fmt.Println(command)
resp, err := client.Do(req)
if err != nil {
log.Error("Event report fail", log.E(err))
return fmt.Errorf("failed to send request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Error("Event report fail", log.Any("http.code", resp.StatusCode))
return fmt.Errorf("failed to report event, http.code: %d", resp.StatusCode)
}
// 读取返回的 body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("Event report fail", log.E(err))
return fmt.Errorf("failed to read response body: %v", err)
}
res := &Response{}
err = json.Unmarshal(body, res)
if err != nil {
log.Error("Event report json.Unmarshal(body, res) fail", log.Any("body", string(body)), log.E(err))
return err
}
if res.Code != 0 {
log.Error("Event report fail", log.Any("code", res.Code), log.Any("msg", res.Msg), log.Any("data", res.Data))
return fmt.Errorf("failed to report event, res.code: %d", res.Code)
}
// 输出响应状态和返回的 body
log.Info("Event report Response", log.Any("eventData", eventData), log.Any("body", string(body)))
return nil
}
func structToFormData(data interface{}) (string, error) {
// 序列化结构体为 JSON 字符串
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
// 反序列化为 map
var dataMap map[string]interface{}
err = json.Unmarshal(jsonData, &dataMap)
if err != nil {
return "", err
}
var formData []string
// 遍历 map,将其转换为 form 数据
for key, value := range dataMap {
if value == nil {
continue // 如果值为 nil,跳过
}
// 将值转换为字符串
valueStr := fmt.Sprintf("%v", value)
// 使用 URL 编码
formData = append(formData, fmt.Sprintf(
"%s=%s",
url.QueryEscape(key),
url.QueryEscape(valueStr),
))
}
return strings.Join(formData, "&"), nil
}
func NewCommonField(event string, districtCode string, ua useragent.UA, ip string, uid int64) CommonField {
return NewCommonFieldAt(event, districtCode, ua, ip, uid, time.Now().Unix())
}
func NewCommonFieldAt(event string, districtCode string, ua useragent.UA, ip string, uid int64, clientTS int64) CommonField {
eventId := GenerateGlobalEventID()
// 五项公共字段和 app_version 使用当前请求中的 SDK 原值,旧客户端缺失时留空。
// 不能用业务 DevID、用户表会话或推算的平台补齐,否则仍会与客户端埋点不一致。
sdk := ua.SDKCommon
if missing := sdk.MissingFields(); len(missing) > 0 {
log.Warn("【SDK公共参数缺失】NewCommonFieldAt",
log.Any("接口", ua.RequestPath), log.Any("事件", event),
log.Any("eventId", eventId), log.Any("userId", uid), log.Any("客户端版本", ua.Ver),
log.Any("已获取SDK参数", sdk != nil), log.Any("缺失字段", missing))
}
if sdk == nil {
sdk = &useragent.SDKCommonFields{}
}
return CommonField{
UID: fmt.Sprintf("%v", uid),
EventID: eventId,
Event: event,
Channel: districtCode,
AppID: pubdef.ReportAppId(),
AppVersion: sdk.AppVersion,
ClientTS: fmt.Sprintf("%v", clientTS),
Device: sdk.Device,
DeviceID: sdk.DeviceID,
DeviceFingerprint: sdk.DeviceFingerprint,
FPVersion: sdk.FPVersion,
UserAgent: strings.TrimSpace(ua.UserAgent),
DeviceModel: strings.TrimSpace(ua.DevType),
SID: sdk.SID,
IP: ip,
}
}
func JsonNumber(v int64) json.Number {
return json.Number(strconv.FormatInt(v, 10))
}
func JsonRawMessage(v interface{}) json.RawMessage {
b, _ := json.Marshal(v)
return b
}
// 批量上报事件
func BatchReport(ctx context.Context, data interface{}) error {
apiUrl := config.ApiUrl + "/api/eventTracking/batchReport.json"
reqBody, err := json.Marshal(data)
if err != nil {
log.Error("Event report json.Marshal fail", log.E(err))
return err
}
req, err := http.NewRequest("POST", apiUrl, bytes.NewReader(reqBody))
if err != nil {
log.Error("Event report NewRequest fail", log.E(err))
return fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
curl, _ := http2curl.GetCurlCommand(req)
client := &http.Client{
Timeout: 5 * time.Second, // 设置超时时间为 5 秒
}
resp, err := client.Do(req)
if err != nil {
log.Error("Event report fail", log.Any("curl", curl), log.E(err))
return fmt.Errorf("failed to send request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Error("Event report fail", log.Any("curl", curl), log.Any("http.code", resp.StatusCode))
return fmt.Errorf("failed to report event, status code: %d", resp.StatusCode)
}
// 读取返回的 body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("Event report fail", log.Any("curl", curl), log.E(err))
return fmt.Errorf("failed to read response body: %v", err)
}
// 输出响应状态和返回的 body
log.Info("Event report Response", log.Any("body", string(body)))
return nil
}
+131
View File
@@ -0,0 +1,131 @@
package dataReport
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"videoweb/pub/common/log"
"videoweb/pub/redis"
"github.com/robfig/cron/v3"
)
const (
sdkConfigAPIProd = "https://api.dc-server.cc/sdk/getAvailableDomainList"
sdkConfigAPIDev = "https://dcapi.dc-dev.cc/sdk/getAvailableDomainList"
sdkConfigCacheKey = "report:sdk:domain_config"
sdkConfigCacheTTL = 30 * time.Minute
sdkConfigFetchInterval = "0 */10 * * * *"
)
var (
sdkConfigAPIURL = sdkConfigAPIProd // 默认正式环境,Init时会根据RunMod覆盖
sdkConfigCron *cron.Cron
sdkConfigOnce sync.Once
sdkConfigMu sync.RWMutex
sdkDomainConfig string
sdkConfigUpdatedAt time.Time
)
type sdkConfigResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data string `json:"data"`
}
// StartSDKConfigCron 定时拉取 SDK 域名配置串,服务端只缓存并原样透传。
func StartSDKConfigCron() {
sdkConfigOnce.Do(func() {
if err := RefreshSDKDomainConfig(); err != nil {
log.Error("RefreshSDKDomainConfig first run fail", log.E(err))
}
sdkConfigCron = cron.New(cron.WithSeconds())
if _, err := sdkConfigCron.AddFunc(sdkConfigFetchInterval, func() {
if err := RefreshSDKDomainConfig(); err != nil {
log.Error("RefreshSDKDomainConfig cron fail", log.E(err))
}
}); err != nil {
log.Error("StartSDKConfigCron AddFunc fail", log.E(err))
return
}
sdkConfigCron.Start()
})
}
func StopSDKConfigCron() {
if sdkConfigCron == nil {
return
}
ctx := sdkConfigCron.Stop()
<-ctx.Done()
}
func RefreshSDKDomainConfig() error {
data, err := fetchSDKDomainConfig(sdkConfigAPIURL, &http.Client{Timeout: 5 * time.Second})
if err != nil {
return err
}
setSDKDomainConfig(data)
if redis.Client() == nil {
return nil
}
return redis.Set(sdkConfigCacheKey, data, sdkConfigCacheTTL)
}
func GetSDKDomainConfig() string {
if redis.Client() != nil {
data, err := redis.Get(sdkConfigCacheKey)
if err != nil {
log.Error("GetSDKDomainConfig redis get fail", log.E(err))
} else if data != nil && *data != "" {
setSDKDomainConfig(*data)
return *data
}
}
sdkConfigMu.RLock()
defer sdkConfigMu.RUnlock()
return sdkDomainConfig
}
func setSDKDomainConfig(data string) {
sdkConfigMu.Lock()
defer sdkConfigMu.Unlock()
sdkDomainConfig = data
sdkConfigUpdatedAt = time.Now()
}
func fetchSDKDomainConfig(apiURL string, client *http.Client) (string, error) {
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("sdk config http status: %d", resp.StatusCode)
}
var result sdkConfigResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
if result.Code != 0 {
return "", fmt.Errorf("sdk config code: %d, msg: %s", result.Code, result.Msg)
}
if strings.TrimSpace(result.Data) == "" {
return "", fmt.Errorf("sdk config data is empty")
}
return result.Data, nil
}
+224
View File
@@ -0,0 +1,224 @@
package dataReport
import (
"context"
"encoding/json"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type Config struct {
ApiUrl string `json:"apiUrl"`
RunMod string `json:"runMod"` // 运行模式: dev/test/prod/release
}
const (
EventTypeAdClick = "ad_click"
EventTypeUserLogin = "user_login"
EventTypeUserRegister = "user_register"
EventTypeOrderCreated = "order_created"
EventTypeOrderPaid = "order_paid"
EventTypeCoinConsume = "coin_consume"
EventTypeVideoPurchase = "video_purchase"
EventTypeVideoLike = "video_like"
EventTypeVideoCollect = "video_collect"
EventTypePlayletLike = "playlet_like"
EventTypeVideoComment = "video_comment"
EventTypeVideoStatusChange = "video_status_change" // 视频状态变更
EventTypeDramaLike = "drama_like"
EventTypeDramaCollect = "drama_collect"
EventTypeDramaComment = "drama_comment"
EventTypeDramaPurchase = "drama_purchase"
DramaContentTypeShortDrama = "short_drama"
DramaUnlockTypeCoin = "coin"
DramaUnlockTypeVIP = "vip_subscription"
DramaUnlockTypeAd = "ad"
DramaUnlockTypeOther = "other"
)
// Event 定义事件的接口
type Event interface {
Generate(ctx context.Context, retryCount int)
AsyncReport(ctx context.Context, retryCount int) error // 执行事件上报
}
// 定义公共字段和事件数据结构
type CommonField struct {
Event string `json:"event"` // 事件类型
Channel string `json:"channel"` // 渠道码
EventID string `json:"event_id"` // 事件唯一标识符
AppID string `json:"app_id"` // 应用ID
AppVersion string `json:"app_version"` // 客户端通过 X-SDK-Common 传入的版本,缺失时留空
UID string `json:"uid"` // 用户ID
SID string `json:"sid"` // 会话ID
ClientTS string `json:"client_ts"` // 客户端时间戳
Device string `json:"device"` // 设备类型(如:Android, iOS, PC)
DeviceID string `json:"device_id"` // 设备ID
DeviceFingerprint string `json:"device_fingerprint"` // SDK 设备指纹,SDK 原值为空时也保留字段。
FPVersion string `json:"fp_version"` // SDK 指纹算法版本
UserAgent string `json:"user_agent"` // 用户代理信息
DeviceBrand string `json:"device_brand"` // 设备品牌(如:HUAWEI)
DeviceModel string `json:"device_model"` // 设备型号
SystemName string `json:"system_name"` // 系统名称
SystemVersion string `json:"system_version"` // 系统版本
IP string `json:"ip"` // 用户IP地址
Payload json.RawMessage `json:"payload"` // 事件数据
}
// UserRegisterEvent 注册事件
type UserRegisterEvent struct {
Type string `json:"type"` // 注册方式:phone, deviceid, email, username
TraceID string `json:"trace_id"` // 唯一标识,落地页点击生成
CreateTime json.Number `json:"create_time"` // 注册时间,10位时间戳
}
type UserLoginEvent struct {
Type string `json:"type"` // 登录方式
}
// OrderCreatedEvent 订单创建
type OrderCreatedEvent struct {
OrderID string `json:"order_id"` // 订单号(唯一标识)
OrderType string `json:"order_type"` // 订单类型
ProductID string `json:"product_id"` // 商品ID
ProductName string `json:"product_name"` // 商品名称
VIPDurationID string `json:"vip_duration_type"`
VIPDurationName string `json:"vip_duration_name"`
Amount json.Number `json:"amount"` // 订单金额(分)
Currency string `json:"currency"` // 货币类型
CoinQuantity json.Number `json:"coin_quantity"` // 金币数量
SourcePageKey string `json:"source_page_key"` // 来源页面标识
SourcePageName string `json:"source_page_name"` // 来源页面名称
CreateTime json.Number `json:"create_time"` // 订单创建时间
}
// OrderPaidEvent 订单支付成功
type OrderPaidEvent struct {
OrderID string `json:"order_id"` // 订单号(关联创建事件)
OrderType string `json:"order_type"` // 订单类型:coin_purchase, vip_subscription
ProductID string `json:"product_id"` // 商品ID
Amount json.Number `json:"amount"` // 实际支付金额(分)
Currency string `json:"currency"` // 货币类型:CNY, USD
CoinQuantity json.Number `json:"coin_quantity"` // 金币数量(仅金币订单)
VIPExpirationTime json.Number `json:"vip_expiration_time"` // VIP过期时间(10位时间戳)
PayType string `json:"pay_type"` // 支付方式:wechat, alipay, bank_card
PayChannel string `json:"pay_channel"` // 支付渠道:银行名称
TransactionID string `json:"transaction_id"` // 第三方支付交易号
CreateTime json.Number `json:"create_time"`
}
// CoinConsumeEvent 金币消耗
type CoinConsumeEvent struct {
ProductID string `json:"product_id"` // 商品ID
ProductName string `json:"product_name"` // 商品名称
CoinConsumeAmount json.Number `json:"coin_consume_amount"` // 金币消耗数量
CoinBalanceBefore json.Number `json:"coin_balance_before"` // 消耗前金币余额
CoinBalanceAfter json.Number `json:"coin_balance_after"` // 消耗后金币余额
ConsumeReasonKey string `json:"consume_reason_key"` // 消耗原因
ConsumeReasonName string `json:"consume_reason_name"` // 消耗原因名称
CreateTime json.Number `json:"create_time"` // 订单创建时间
OrderId string `json:"order_id"` // 订单id
}
// VideoPurchaseEvent 视频购买事件
type VideoPurchaseEvent struct {
MediaId string `json:"media_id"` // 老司机媒体资源ID(老司机接口返回的id字段)
VideoID string `json:"video_id"` // 视频ID
VideoTitle string `json:"video_title"` // 视频标题
VideoTypeID string `json:"video_type_id"` // 视频分类ID
VideoTypeName string `json:"video_type_name"` // 视频分类名称
VideoContentType string `json:"video_content_type"` // 视频类型: video(长视频)、short_video(短视频)
RecommendTraceId string `json:"recommend_trace_id"` // 推荐引擎的trace_id。没有对接搜索推荐引擎的上报空字符串。
CoinQuantity json.Number `json:"coin_quantity"` // 金币数量
OrderID string `json:"order_id"` // 订单号
}
type (
VideoEventPub struct {
MediaId string `json:"media_id"` // 老司机媒体资源ID(老司机接口返回的id字段)
VideoID string `json:"video_id"` // 视频ID
VideoTitle string `json:"video_title"` // 视频标题
VideoTypeID string `json:"video_type_id"` // 视频分类ID
VideoTypeName string `json:"video_type_name"` // 视频分类名称
VideoContentType string `json:"video_content_type"` // 视频类型: video(长视频)、short_video(短视频)
RecommendTraceId string `json:"recommend_trace_id"` // 推荐引擎的trace_id。没有对接搜索推荐引擎的上报空字符串。
}
VideoLikeEvent struct {
VideoEventPub
Flag json.Number `json:"flag"` // 点赞状态:1(点赞), 2(取消点赞)
}
VideoCollectEvent struct {
VideoEventPub
Flag json.Number `json:"flag"` // 收藏状态:1(收藏), 2(取消收藏)
}
VideoCommentEvent struct {
VideoEventPub
CommentContent string `json:"comment_content"` // 评论内容
}
// VideoStatusChangeEvent 视频状态变更事件
VideoStatusChangeEvent struct {
MediaId string `json:"media_id"` // 老司机媒体资源ID
VideoID string `json:"video_id"` // 视频ID
VideoTitle string `json:"video_title"` // 视频标题
VideoTypeID string `json:"video_type_id"` // 视频分类ID
VideoTypeName string `json:"video_type_name"` // 视频分类名称
Flag json.Number `json:"flag"` // 状态标识
}
DramaEventPub struct {
DramaID string `json:"drama_id"` // 剧集章节ID(PlayletChapter.Id)
DramaTitle string `json:"drama_title"` // 剧集名称
Episode json.Number `json:"episode"` // 第几集,默认1
VideoID string `json:"video_id"` // 媒资中心章节ID(PlayletChapter.MediaContentId)
TotalEpisode json.Number `json:"total_episode"` // 已上线总集数
DramaTypeID string `json:"drama_type_id"` // 剧集分类ID
DramaTypeName string `json:"drama_type_name"` // 剧集分类名称
DramaContentType string `json:"drama_content_type"` // short_drama
DramaTagKey string `json:"drama_tag_key"` // 标签KEY,逗号分隔
DramaTagName string `json:"drama_tag_name"` // 标签名称,逗号分隔
DramaDuration json.Number `json:"drama_duration"` // 剧集时长(秒)
}
DramaLikeEvent struct {
DramaEventPub
Flag json.Number `json:"flag"` // 点赞状态:1(点赞), 2(取消点赞)
}
DramaCollectEvent struct {
DramaEventPub
Flag json.Number `json:"flag"` // 收藏状态:1(收藏), 2(取消收藏)
}
DramaCommentEvent struct {
DramaEventPub
CommentContent string `json:"comment_content"` // 评论内容
}
DramaPurchaseEvent struct {
DramaEventPub
CoinQuantity json.Number `json:"coin_quantity"` // 金币数量
OrderID string `json:"order_id"` // 订单号,与 coin_consume 保持一致
UnlockType string `json:"unlock_type"` // coin / vip_subscription / ad / other
AdID string `json:"ad_id"` // 广告解锁时的广告ID
}
)
type AdClickEvent struct {
CommonField
PageKey string `json:"page_key"` // 页面标识
PageName string `json:"page_name"` // 页面名称
AdSlotKey string `json:"ad_slot_key"` // 广告位标识
AdSlotName string `json:"ad_slot_name"` // 广告位名称
AdID string `json:"ad_id"` // 广告ID
CreativeID string `json:"creative_id"` // 素材ID(可选)
AdType string `json:"ad_type"` // 广告类型
}