Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

10
app/interface/main/web/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
.idea/*
.project
.buildpath
.externalToolBuilders
.settings
.DS_Store
.a
*.iml
.vscode/*
cmd/cmd

View File

@@ -0,0 +1,21 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/interface/main/web/cmd:all-srcs",
"//app/interface/main/web/conf:all-srcs",
"//app/interface/main/web/dao:all-srcs",
"//app/interface/main/web/http:all-srcs",
"//app/interface/main/web/model:all-srcs",
"//app/interface/main/web/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,865 @@
### web-interface
#### Version 3.7.0
##### Features
> 1.archive stats3 use grpc
#### Version 3.6.3
##### Features
> 1.timeline add h5 cover.
#### Version 3.6.2
##### Features
> 1.特殊用户组生产环境详情页接口不可见稿件
#### Version 3.6.1
##### Features
> 1.bnj arc is normal.
#### Version 3.6.0
##### Features
> 1.coin add like select.
> 2.add likeTriple api.
> 3.bnj live arc memory cache.
> 4.rm prom error
#### Version 3.5.5
##### Features
> 1.view first cid.
#### Version 3.5.4
##### Features
> 1.conf watch.
#### Version 3.5.3
##### Features
> 1.fix card mid 0.
#### Version 3.5.2
##### Features
> 1.bnj2019 related arcs empty list.
#### Version 3.5.1
##### Features
> 1.addShare only shareClient.
#### Version 3.5.0
##### Features
> 1.bnj2019 接口.
#### Version 3.4.2
##### Features
> 1.addShare 添加ip参数.
#### Version 3.4.1
##### Features
> 1.ugc pay 修改.
#### Version 3.4.0
##### Features
> 1.shop change url.
#### Version 3.3.0
##### Features
> 1.ugc pay.
#### Version 3.2.0
> 1.rm net ip.
> 2.fix newlist panic
#### Version 3.1.4
##### Features
> 1.fix view data.
#### Version 3.1.3
##### Features
> 1.location的Zone方法改为Info
#### Version 3.1.2
##### Features
> 1.fix subtitle nil panic.
#### Version 3.1.1
##### Features
> 1.fix card relation panic.
> 2.fix search relation map nil.
#### Version 3.1.0
##### Features
> 1.综合搜索加明星卡.
#### Version 3.0.3
##### Features
> 1.fix nav default profile panic.
#### Version 3.0.2
##### Features
> 1.article up list panic fix.
#### Version 3.0.1
##### Features
> 1.分享接口双写
#### Version 3.0.0
##### Features
> 1.arc acc rpc依赖切grpc
#### Version 2.33.2
##### Features
> 1.broadcast default
#### Version 2.33.1
##### Features
> 1.bm trance 方法
#### Version 2.32.0
##### Features
> 1.view 接口新增subtitle信息
#### Version 2.31.1
##### Features
> 1.wechat 搜索接口出影视数据
#### Version 2.31.0
##### Features
> 1.提供新的wx搜索接口
> 2.dynamic panic 修改
#### Version 2.30.0
##### Features
> 1.搜索加单双列逻辑
#### Version 2.29.9
##### Features
> 1.去除fmtPic逻辑
#### Version 2.29.8
##### Features
> 1.like接口新增upID参数
#### Version 2.29.7
##### Features
> 1.wx/hot 新增分页逻辑
> 2.去除多余配置
#### Version 2.29.6
> 1.up/rec 接口新增buvid
#### Version 2.29.5
##### Features
> 1.nav add vip购买类型,代金券张数
#### Version 2.29.4
##### Features
> 1.view 接口,站外播放器可以访问
#### Version 2.29.3
##### Features
> 1.arc/related arc 切 grpc
#### Version 2.29.2
##### Features
> 1.新增coin/list接口
#### Version 2.29.1
##### Features
> 1.up/rec 接口新增ps参数
#### Version 2.29.0
##### Features
> 1.新增tag聚合接口
#### Version 2.28.0
##### Features
> 1.coin 相关接口切到 grpc
#### Version 2.27.2
##### Features
> 1.加配置不展示相关视频
#### Version 2.27.1
##### Features
> 1.改用metadata.remoteIP
#### Version 2.27.0
##### Features
> 1.新增web彩蛋接口
#### Version 2.26.7
##### Features
> 1.修改一部分错误日志
#### Version 2.26.6
##### Features
> 1.up/rec 字段err判断fix
#### Version 2.26.5
##### Features
> 1.up/rec 字段新增sign返回
#### Version 2.26.4
##### Features
> 1.fix card接口error返回
#### Version 2.26.3
##### Features
> 1.新增服务节点接口
#### Version 2.26.2
##### Features
> 1.恢复 view/detail 接口related数据
#### Version 2.26.1
##### Features
> 1.移除parse的使用
#### Version 2.26.0
##### Features
> 1.identify使用grpc
#### Version 2.25.0
##### Features
> 1.新增up推荐接口
#### Version 2.24.2
##### Features
> 1.投币接口使用business
#### Version 2.24.1
##### Features
> 1.稿件投诉接口新增限制
#### Version 2.24.0
##### Features
> 1.搜索接口支持highlight参数
#### Version 2.23.0
##### Features
> 1.新增wx/hot接口
#### Version 2.22.0
##### Features
> 1.conf 配置文件新增rule
> 2.search http client 新增ua header
#### Version 2.21.0
##### Features
> 1.archive/stat 新增 like.
#### Version 2.20.4
##### Features
> 1.保留search outer 接口
#### Version 2.20.3
##### Bug Fixes
> 1.恢复search/default router.
#### Version 2.20.2
##### Features
> 1.search 相关接口切到co.
#### Version 2.20.1
##### Features
> 1.newlist 接口针对特殊一级分区补充数据
> 2.精简conf配置文件
#### Version 2.20.0
##### Features
> 1.新增稿件点赞接口
> 2.投币接口接rpc逻辑修改
> 3.view/detail 接口去除related数据
### v2.19.0
##### Features
> 1.update infoc sdk
#### Version 2.18.0
##### Features
> 1.新增默认搜索词接口
#### Version 2.17.0
##### Features
> 1.nav 新增降级逻辑
#### Version 2.16.0
##### Features
> 1.arc,resource 接入 discovery.
#### Version 2.15.1
##### Features
> 1.card 接口Official添加title
#### Version 2.15.0
##### Features
> 1.新增abserver接口
#### Version 2.14.3
##### Features
> 1.一级分区id去除数据库依赖改为配置文件
#### Version 2.14.2
##### Bug Fixes
> 1.修复 index icon bug
#### Version 2.14.1
##### Features
> 1.移除 index icon 日志
#### Version 2.14.0
##### Features
> 1.移除view,view/detail 接口 breadcrumb 字段
##### Bug Fixes
> 1.fix ranking data nil panic
#### Version 2.13.3
##### Features
> 1.排行榜接口note字段透传
> 2.index icon 添加日志
#### Version 2.13.2
##### Features
> 1.添加弹幕盒子接口
#### Version 2.13.1
##### Features
> 1.投币上报,加稿件投币
#### Version 2.13.0
##### Features
> 1.迁移main目录
#### Version 2.12.5
##### Bug Fixes
> 1.fix pay key
#### Version 2.12.4
##### Features
> 1.修改account-service v7
#### Version 2.12.3
##### Bug Fixes
> 1.fix coin 返回参数
#### Version 2.12.2
##### Features
> 1.fix downLimit 参数错误
#### Version 2.12.1
##### Features
> 1.article coin infoc 上报
#### Version 2.12.0
##### Features
> 1.新增搜索相关接口
#### Version 2.11.4
##### Features
> 1.detail接口 fix reply
#### Version 2.11.3
##### Bug Fixes
> 1.view接口视频能否下载 not PGC
#### Version 2.11.2
##### Features
> 1.view接口新增视频能否下载
#### Version 2.11.1
##### Features
> 1.删除 appeal tag model
#### Version 2.11.0
##### Features
> 1.修改 report tag model
#### Version 2.10.2
##### Features
> 1.删除statsd
#### Version 2.10.1
##### Features
> 1.article/list 添加指针nil判断
#### Version 2.10.0
##### Features
> 1.archive/related 接口添加稿件状态过滤
#### Version 2.9.1
##### Features
> 1.view detail 内部接口Guest
#### Version 2.9.0
##### Features
> 1.ranking tag 切换新大数据接口
#### Version 2.8.1
##### Features
> 1.profile to info2
> 2.attentions use relation
#### Version 2.8.0
##### Features
> 1.添加百度kv接口
#### Version 2.7.2
##### Bug Fixes
> 1.rank bug fix
#### Version 2.7.1
##### Features
> 1.rank other limit
#### Version 2.7.0
##### Features
> 1.acc card to acc info
#### Version 2.6.3
##### Features
> 1.use new degrade
#### Version 2.6.2
##### Bug Fixes
> 1.newlist return data
#### Version 2.6.1
##### Bug Fixes
> 1.nav no login
#### Version 2.6.0
##### Features
> 1.http接入bm
#### Version 2.5.1
##### Bug Fixes
> 1.icon copy len
#### Version 2.5.0
##### Features
> 1.修改index icon 随机数据展现方式
> 2.view 接口remote cache 改随机写
> 3.view 接口zlimit返回-404
#### Version 2.4.1
##### Features
> 1.view接口加区域限制属性
#### Version 2.4.0
##### Features
> 1.添加视频详情聚合接口
> 2.view 返回结果加NoCache
#### Version 2.3.0
##### Features
> 1.修改index icon 随机数据展现方式
#### Version 2.2.3
##### Bug Fixes
> 1.online list dm count fix
#### Version 2.2.2
##### Features
> 1.help detail cache update time desc
#### Version 2.2.1
##### Bug Fixes
> 1.archive/stat reply fix
#### Version 2.2.0
##### Features
> 1.index/icon 接口调整
#### Version 2.1.2
##### Bug Fixes
> 1.add archives log
#### Version 2.1.1
##### Bug Fixes
> 1.online list append fix
#### Version 2.1.0
##### Features
> 1.nav 接口新增是否有店铺标识
> 2.online/list 接口数据新增屏蔽规则
> 3.newlist 调整 addCache 位置
#### Version 2.0.0
##### Features
> 1.配制加common-mc
> 2.帮助接口加degrade
> 3.修复帮助列表缓存顺序问题
> 4.帮助详情加缓存第一页
#### Version 1.30.0
##### Features
> 1.新增 related archive 接口
#### Version 1.29.0
##### Features
> 1.add 封装智齿帮助列表、详情、搜索接口
#### Version 1.28.4
##### Bug Fixes
> 1.fix online count error
#### Version 1.28.3
##### Bug Fixes
> 1.online new fix
#### Version 1.28.2
##### Features
> 1.stats2 to stats3
#### Version 1.28.1
##### Features
> 1.online http fix
#### Version 1.28.0
##### Features
> 1.新增online list接口
#### Version 1.27.3
##### Bug Fixes
> 1.view redirecturl bug fix
#### Version 1.27.2
##### Features
> 1.view 加错误判断与加长简介与分P简介
> 2.长简介接口加稿件描述与分P简介
#### Version 1.27.1
##### Features
> 1.统一prom使用方法
#### Version 1.27.0
##### Features
> 1.新增indexicon接口
#### Version 1.26.0
##### Features
> 1.online接口返回web_online和play_online数据
##### Bug Fixes
> 1.up 相关稿件接口数据去除当前稿件
#### Version 1.25.0
##### Features
> 1.ranking接口稿件计数使用大数据的数据
#### Version 1.24.0
##### Features
> 1.新增interface路由
> 2.errgroup 引包修改
#### Version 1.23.1
##### Features
> 1.新增稿件投诉workflow相关接口url修改
#### Version 1.23.0
##### Features
> 1.新增稿件投诉workflow相关接口
#### Version 1.22.2
##### Bug Fixes
> 1.card 获取article count fix
#### Version 1.22.1
##### Bug Fixes
> 1.up主相关稿件接口数量fix
#### Version 1.22.0
##### Features
> 1.新增up主相关稿件接口
#### Version 1.21.0
##### Features
> 1.新增投币经验接口,投币接口支持专栏
> 2.account card3 恢复成 card2 接口
#### Version 1.20.0
##### Features
> 1.新增专栏up相关稿件接口
#### Version 1.19.0
##### Features
> 1.新增稿件投诉接口
#### Version 1.18.5
##### Features
> 1.Archive2 to Archive3
#### Version 1.18.4
##### Bug Fixes
> 1.tag empty list
#### Version 1.18.3
##### Bug Fixes
> 1.排行榜稿件播放数隐藏变--
#### Version 1.18.2
##### Features
> 1.elec/show add ecode 62001
#### Version 1.18.1
##### Bug Fixes
> 1.web端专栏接口article/list follow 修复
#### Version 1.18.0
##### Features
> 1.web端专栏接口
#### Version 1.17.8
##### Features
> 1.依赖rpc方法view2 改成 view3
> 2.http client 修改
#### Version 1.17.7
##### Bug Fixes
> 1.rank tag 稿件计数实时获取fix
#### Version 1.17.6
##### Bug Fixes
> 1.rank tag 稿件计数实时获取
#### Version 1.17.5
##### Features
> 1.rank 数据源接口全量切换新接口
#### Version 1.17.4
##### Features
> 1.elecShow接口加稿件是自制稿件
#### Version 1.17.3
##### Bug Fixes
> 1.rank 接口返回数据null判断
#### Version 1.17.1
##### Bug Fixes
> 1.newlist 二级分区逻辑fix
#### Version 1.17.0
##### Features
> 1.获取稿件充电面板展示接口
> 2.newlist 添加总的最新视频列表
#### Version 1.16.0
##### Features
> 1.添加游戏分区运营数据接口
#### Version 1.15.0
##### Features
> 1.增加稿件长简介接口
#### Version 1.14.0
##### Features
> 1.增加分享数接口
#### Version 1.13.0
##### Features
> 1.合并大仓库
#### Version 1.12.0
##### Features
> 1.添加ip查询接口
> 2.ranking 循环加判断逻辑
#### Version 1.11.4
##### Features
> 1.番剧动态个数加配制项
#### Version 1.11.3
##### Features
> 1.分区推荐音乐分区使用特殊分区名
#### Version 1.11.2
##### Bug Fixes
> 1.稿件计数接口播放数会员可见修正
#### Version 1.11.1
##### Features
> 1.首页,分区推荐数据源换新接口
#### Version 1.11.0
##### Features
> 1.新增稿件计数接口
#### Version 1.10.0
##### Features
> 1.新增投币接口
#### Version 1.9.13
##### Features
> 1.bigData http client 添加 stats
> 2.排行榜接口数据不够添加log
#### Version 1.9.12
##### Features
> 1.排行榜系列接口min count做区分
#### Version 1.9.11
##### Features
> 1.ranking 大数据接口替换新接口
##### Bug Fixes
> 1.bfs client timeout fix
#### Version 1.9.10
##### Features
> 1.ranking/region 大数据接口替换新接口
#### Version 1.9.9
##### Features
> 1.view接口特殊分区权限调整
#### Version 1.9.8
##### Features
> 1.view接口优化未登录不调用Profile2
#### Version 1.9.6
##### Features
> 1.接入最新prom
> 2.dynamic index 添加log统计番剧获取数据
#### Version 1.9.5
##### Features
> 1.修复面包屑一级不显示二级设置显示问题
#### Version 1.9.4
##### Features
> 1.新增view接口
#### Version 1.9.3
##### Bug Fixes
> 1.ranking region bug fix
#### Version 1.9.2
##### Features
> 1.feedback 接口添加参数
#### Version 1.9.1
##### Features
> 1.修改addCache为统一cache方法
#### Version 1.9.0
##### Features
> 1.接入prom监控
#### Version 1.8.5
##### Bug Fixes
> 1.newlist接口zadd bug fix
#### Version 1.8.4
##### Features
> 1.新增用户卡片信息card接口
#### Version 1.8.3
##### Features
> 1.dynamic/total 删除remote cache
#### Version 1.8.2
##### Features
> 1.修改查询分区信息的sql
#### Version 1.8.1
##### Features
> 1.播放器反馈接口添加字段
#### Version 1.8.0
##### Features
> 1.新增播放器反馈接口
#### Version 1.7.0
##### Features
> 1.dynamic/index 每个分区数据添加个数检查
> 2.升级配置中心
#### Version 1.6.9
##### Features
> 1.产品更改tag热门数据方案暂时将固定数量的版本去掉重新改为分页获取数据
#### Version 1.6.8
##### Features
> 1.newlist 一级分区数据修改从rpc接口获取
> 2.online 分区稿件计数从数据库获取数据改成rpc接口获取
> 3.ranking 首页排行榜稿件计数从rpc实时获取
#### Version 1.6.7
##### Features
> 1.添加根据tag id获取热门视频的接口(由分页改为透传固定数量的数据)
#### Version 1.6.6
##### Features
> 1.添加根据tag id获取热门视频的接口(增加tag state过滤)
#### Version 1.6.5
##### Features
> 1.online 接口增加新稿件总数
#### Version 1.6.4
##### Features
> 1.ranking/region archive 字段类型修正
> 2.region/index 返回tid修正
> 3.ranking 返回空slice规范结果
#### Version 1.6.3
##### Features
> 1.添加根据tag id获取热门视频的接口
#### Version 1.6.2
##### Features
> 1.pn ps check
#### Version 1.6.1
##### Features
> 1.rs code empty -404
#### Version 1.6.0
##### Features
> 1.coins 当前用户对该视频的投币数
#### Version 1.5.0
##### Features
> 1.新增monitor ping 方法
#### Version 1.4.0
##### Features
> 1.newlist接口 返回数据添加page字段
#### Version 1.3.2
##### Features
> 1.newlist接口 新增type参数
#### Version 1.3.1
##### Features
> 1.newlist接口 page size修复
> 2.ranking接口字段修复
#### Version 1.3.0
##### Features
> 1.新增首页nav接口
#### Version 1.2.4
##### Features
> 1.排行榜新增recommend接口
#### Version 1.2.3
##### Bug Fixes
> 1.newlist接口 slice越界修复
#### Version 1.2.2
##### Features
> 1.Attention 接口优化
#### Version 1.2.1
##### Features
> 1.新增首页排行榜接口
#### Version 1.2.0
##### Features
> 1.更新go business
#### Version 1.1.0
##### Features
> 1.排行榜页面分区排行榜tag排行榜接口
> 2.分区最新稿件
#### Version 1.0.0
##### Features
> 1.关注列表功能

View File

@@ -0,0 +1,13 @@
# Owner
liweijia
zhapuyu
# Author
wuhao02
guanyanliang
liweijia
# Reviewer
guanyanliang
liweijia
zhapuyu

View File

@@ -0,0 +1,18 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- guanyanliang
- liweijia
- wuhao02
- zhapuyu
labels:
- interface
- interface/main/web
- main
options:
no_parent_owners: true
reviewers:
- guanyanliang
- liweijia
- wuhao02
- zhapuyu

View File

@@ -0,0 +1,18 @@
#### web-interface
##### 项目简介
> 1.提供web端接口
##### 编译环境
> 请使用golang v1.7.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common
##### 编译执行
> 在主目录执行go build。
> 编译后可执行 ./cmd/cmd -conf web-interface-test.toml 使用项目本地配置文件启动服务。
> 也可执行 ./web-interface -conf_appid=web-interface -conf_version=v2.1.0 -conf_host=172.16.33.134:9011 -conf_path=/data/conf/web-interface -conf_env=10 -conf_token=SEHXM8x1vYhIUaZvQUmyWnMYJrF9jHJY 使用配置中心测试环境配置启动服务如无法启动可检查token是否正确。
##### 特别说明
> http接口文档可参考 http://info.bilibili.co/pages/viewpage.action?pageId=2491046

View File

@@ -0,0 +1,52 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = [
"web-interface-example.toml",
"web-interface-test.toml",
],
importpath = "go-common/app/interface/main/web/cmd",
tags = ["automanaged"],
deps = [
"//app/interface/main/web/conf:go_default_library",
"//app/interface/main/web/http:go_default_library",
"//app/interface/main/web/service:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)

View File

@@ -0,0 +1,52 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/interface/main/web/conf"
"go-common/app/interface/main/web/http"
"go-common/app/interface/main/web/service"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() error(%v)", err)
panic(err)
}
log.Init(conf.Conf.Log)
trace.Init(conf.Conf.Tracer)
defer trace.Close()
defer log.Close()
log.Info("web-interface start")
// ecode
ecode.Init(conf.Conf.Ecode)
//server init
svr := service.New(conf.Conf)
http.Init(conf.Conf, svr)
// signal handler
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("web-interface get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("web-interface exit")
svr.Close()
time.Sleep(time.Second)
return
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}

View File

@@ -0,0 +1,104 @@
# This is a TOML document. Boom.
version = "1.0.0"
user = "nobody"
pid = "/tmp/web-interface.pid"
dir = "./"
perf = "127.0.0.1:6260"
checkFile = "/data/www/web-interface.html"
family = "web-interface"
address = "172.16.33.56"
env = "test"
tick = "5m"
accountURI = "http://account.bilibili.com"
[matsuri]
pastID = 5461206
matID = 5461533
matTime = "2016-12-15T16:57:03+08:00"
tick = "10s"
[identify]
whiteAccessKey = ""
whiteMid = 0
[identify.app]
key = "c05dd4e1638a8af0"
secret = "d3c5a85f5b895a03735b5d20a273bc57"
[identify.memcache]
name = "go-business/identify"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 5
idle = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://passport.bilibili.com"
secret = "http://open.bilibili.com"
[identify.authHTTPClient]
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[identify.secretHTTPClient]
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[web-interface]
IPFile = "/data/conf/iprepo/iprepo.txt"
[host]
apiCo = "http://api.bilibili.co"
[log]
dir = "/data/log/web-interface/"
[app]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
[infoc2]
taskID = "000078"
proto = "tcp"
addr = "172.19.100.20:5401"
chanSize = 1024
[httpClient]
[httpClient.read]
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[httpClient.write]
dial = "1s"
timeout = "3s"
keepAlive = "60s"
timer = 1000
[multiHttp]
[multiHttp.inner]
addrs = ["0.0.0.0:6281"]
maxListen = 1000
[multiHttp.local]
addrs = ["0.0.0.0:6282"]
maxListen = 1000
[bm]
[bm.outer]
addr = "0.0.0.0:6351"
timeout = "1s"
[bm.local]
addr = "0.0.0.0:6352"
timeout = "1s"
[web]
pullRegionInterval = "1m"

View File

@@ -0,0 +1,228 @@
[rule]
minRankCount = 30
minRankIndexCount = 7
minRankRegionCount = 9
minRankRecCount = 7
minRankTagCount = 1
minDyCount = 3
minNewListCnt = 10
authorRecCnt = 16
relatedArcCnt = 10
maxHelpPageSize = 15
maxArcsPageSize = 20
maxSecondCacheSize = 200
maxFirstCacheSize = 20
dynamicNumArcs = 5
regionsCount = 10
bangumiCount = 50
maxArtPageSize = 50
artUpListGetCnt = 50
artUpListCnt = 5
elecShowTypeIDs = [20, 154, 156, 31, 30, 59, 29, 28, 26, 22, 126, 127, 24, 25, 47, 27, 17, 18, 16, 65, 136, 19, 121, 171, 172, 173, 37, 124, 122, 39, 96, 95, 98, 71, 137, 131, 157, 158, 159, 164, 82, 128, 138, 21, 75, 76, 161, 162, 163, 174, 153, 168]
rids = [1, 3, 4, 5, 11, 13, 23, 36, 119, 129, 155, 160, 165, 167, 177, 181]
noRelAids = [28335367,28990666]
[identify]
whiteAccessKey = ""
whiteMid = 0
[identify.app]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
[identify.memcache]
name = "go-business/identify"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 10
idle = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://passport.bilibili.com"
secret = "http://open.bilibili.com"
[identify.httpClient]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "30ms"
timeout = "150ms"
keepAlive = "60s"
[identify.httpClient.url]
"http://passport.bilibili.co/intranet/auth/tokenInfo" = {timeout = "100ms"}
"http://passport.bilibili.co/intranet/auth/cookieInfo" = {timeout = "100ms"}
"http://open.bilibili.co/api/getsecret" = {timeout = "500ms"}
[log]
dir = "/data/log/web-interface/"
#[log.syslog]
# proto = "udp"
# addr = "172.18.19.22:9999"
# project = "web-interface"
# chanSize = 10240
[app]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
[infoc2]
taskID = "000078"
proto = "tcp"
addr = "172.19.100.20:5401"
chanSize = 1024
[httpClient]
[httpClient.read]
key = "6aa4286456d16b97"
secret = "351cf022e1ae8296109c3c524faafcc8"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[httpClient.write]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "1s"
timeout = "3s"
keepAlive = "60s"
timer = 1000
[httpClient.bigData]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[httpClient.help]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[httpClient.search]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[httpClient.pay]
key = "6aa4286456d16b97"
secret = "351cf022e1ae8296109c3c524faafcc8"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
timer = 1000
[HTTPServer]
addr = "0.0.0.0:6351"
timeout = "1s"
[redis]
[redis.localRedis]
name = "web-interface/rank"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 10
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
rankingExpire = "10m"
newlistExpire = "20s"
rcExpire = "5m"
indexIconExpire = "5m"
[redis.bakRedis]
name = "web-interface/rank-bak"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 10
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
rankingExpire = "24h"
newlistExpire = "24h"
regionExpire = "24h"
archiveExpire = "24h"
tagExpire = "24h"
cardExpire = "24h"
rcExpire = "24h"
artUpExpire = "24h"
indexIconExpire = "24h"
helpExpire = "24h"
OlListExpire = "24h"
appealLimitExpire = "1h"
[host]
rank = "http://172.18.7.101"
rank2 = "http://data-test.bilibili.co"
api = "http://api.bilibili.co"
data = "http://data.bilibili.co"
space = "http://space.bilibili.com"
elec = "http://elec.bilibili.co"
arcApi = "http://archive.api.bilibili.co"
liveAPI = "http://api.live.bilibili.co"
helpAPI = "http://service-pre.bilibili.com"
show = "http://uat-show.bilibili.co"
mall = "http://fat1-mall.bilibili.co"
search = "http://s.search.bilibili.co"
pay = "http://pay.bilibili.co"
abServer = "http://10.23.58.27:6193"
manager = "http://manager.bilibili.co"
[web]
pullRegionInterval = "1m"
pullOnlineInterval = "15m"
pullIndexIconInterval = "5m"
searchEggInterval = "10m"
onlineCount = 20
specailInterval = "1m"
[tag]
pageSize = 200
maxSize = 100
[defaultTop]
sImg = "http://i0.hdslb.com/bfs/space/768cc4fd97618cf589d23c2711a1d1a729f42235.png"
lImg = "http://i0.hdslb.com/bfs/space/cb1c3ef50e22b6096fde67febe863494caefebad.png"
[bfs]
addr = "http://bfs.bilibili.co"
bucket = "test"
key = "221bce6492eba70f"
secret = "6eb80603e85842542f9736eb13b7e3"
maxFileSize = 1048576
timeout = "400ms"
[degradeConfig]
expire = 3600
[degradeConfig.memcache]
name = "web-interface"
proto = "tcp"
addr = "172.16.33.54:11211"
idle = 10
active = 10
dialTimeout = "2s"
readTimeout = "2s"
writeTimeout = "2s"
idleTimeout = "7h"
[bnj2019]
bnjMainAid = 36324283
bnjAdAv = 0
bnjListAids = [36324368,36324414,36324551,36324580,36324656,36324841,36324894,36324961,36324997,36325803,36325869,36328477,36328523,36328583,36328676,36328706,36328952,36328993]
bnjTick = "10s"
[[bnj2019.timeline]]
name = "1111"
start = "2018-06-04T00:00:00+08:00"
end = "2018-06-05T10:00:00+08:00"
cover = "//activity.hdslb.com/blackboard/static/20180122/3f23658826b7a0a46f812d368533dc9f/images/j60y4n9j83.png"
[[bnj2019.timeline]]
name = "2222"
start = "2018-06-04T00:00:00+08:00"
end = "2018-06-05T10:00:00+08:00"
cover = "//i0.hdslb.com/bfs/activity-plat/cover/20180209/m6pvmmnpxx.jpg"

View File

@@ -0,0 +1,44 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/interface/main/web/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/log/infoc:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/BurntSushi/toml:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,306 @@
package conf
import (
"errors"
"flag"
xtime "time"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/log/infoc"
"go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/verify"
"go-common/library/net/rpc"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"go-common/library/time"
"github.com/BurntSushi/toml"
)
// global var
var (
confPath string
client *conf.Client
// Conf config
Conf = &Config{}
)
// Config config set
type Config struct {
// log
Log *log.Config
// ecode
Ecode *ecode.Config
// http client
HTTPClient *httpClient
// HTTPServer
HTTPServer *blademaster.ServerConfig
// tracer
Tracer *trace.Config
// auth
Auth *auth.Config
// verify
Verify *verify.Config
// CouponRPC
CouponRPC *rpc.ClientConfig
// ArchiveRPC
ArchiveRPC *rpc.ClientConfig
// DynamicRPC
DynamicRPC *rpc.ClientConfig
// LocationRPC
LocationRPC *rpc.ClientConfig
// CoinRPC
CoinRPC *rpc.ClientConfig
// TagRPC
TagRPC *rpc.ClientConfig
// ArticleRPC
ArticleRPC *rpc.ClientConfig
// ResourceRPC
ResourceRPC *rpc.ClientConfig
// RelationRPC
RelationRPC *rpc.ClientConfig
// ThumbupRPC
ThumbupRPC *rpc.ClientConfig
// DM2RPC
Dm2RPC *rpc.ClientConfig
// FavRPC
FavRPC *rpc.ClientConfig
// Host
Host host
// redis
Redis *redisConf
// degrade
DegradeConfig *degradeConfig
// WEB
WEB *web
// Tag
Tag *tag
// DefaultTop
DefaultTop *defaultTop
// Bfs
Bfs *bfs
// Infoc2
Infoc2 *infoc.Config
// Rule
Rule *rule
// Warden Client
BroadcastClient *warden.ClientConfig
CoinClient *warden.ClientConfig
ArcClient *warden.ClientConfig
AccClient *warden.ClientConfig
ShareClient *warden.ClientConfig
UGCClient *warden.ClientConfig
// bnj
Bnj2019 *bnj2019
}
type rule struct {
// min cache rank count
MinRankCount int
// min cache rank index count
MinRankIndexCount int
// min cache rank region count
MinRankRegionCount int
// min cache rank recommend count
MinRankRecCount int
// min cache rank tag count
MinRankTagCount int
// min cache dynamic count
MinDyCount int
// min newlist tid arc count
MinNewListCnt int
// Elec
ElecShowTypeIDs []int32
// AuthorRecCnt author recommend count
AuthorRecCnt int
// RelatedArcCnt related archive limit count
RelatedArcCnt int
// MaxHelpPageSize help detail search max page count
MaxHelpPageSize int
// newlist
MaxArcsPageSize int
// max size of second region newlist.
MaxSecondCacheSize int
// max size of first region newlist.
MaxFirstCacheSize int
// default num of dynamic archives
DynamicNumArcs int
// regions count
RegionsCount int
// bangumi count
BangumiCount int
// MaxArtPageSize max article page size
MaxArtPageSize int
// article up list get count
ArtUpListGetCnt int
// article up list count
ArtUpListCnt int
// min wechat hot count
MinWxHotCount int
// Rids first region ids
Rids []int32
// no related aids
NoRelAids []int64
}
type httpClient struct {
Read *blademaster.ClientConfig
Write *blademaster.ClientConfig
BigData *blademaster.ClientConfig
Help *blademaster.ClientConfig
Search *blademaster.ClientConfig
Pay *blademaster.ClientConfig
}
type host struct {
Rank string
API string
Data string
Space string
Elec string
ArcAPI string
LiveAPI string
HelpAPI string
Mall string
Search string
Manager string
Pay string
AbServer string
}
type tag struct {
PageSize int
MaxSize int
}
type redisConf struct {
LocalRedis *localRedis
BakRedis *bakRedis
}
type localRedis struct {
*redis.Config
RankingExpire time.Duration
NewlistExpire time.Duration
RcExpire time.Duration
IndexIconExpire time.Duration
WxHotExpire time.Duration
}
type bakRedis struct {
*redis.Config
RankingExpire time.Duration
NewlistExpire time.Duration
RegionExpire time.Duration
ArchiveExpire time.Duration
TagExpire time.Duration
CardExpire time.Duration
RcExpire time.Duration
ArtUpExpire time.Duration
IndexIconExpire time.Duration
HelpExpire time.Duration
OlListExpire time.Duration
WxHotExpire time.Duration
AppealLimitExpire time.Duration
}
type web struct {
PullRegionInterval time.Duration
PullOnlineInterval time.Duration
PullIndexIconInterval time.Duration
SearchEggInterval time.Duration
OnlineCount int
SpecailInterval time.Duration
}
type defaultTop struct {
SImg string
LImg string
}
type bfs struct {
Addr string
Bucket string
Key string
Secret string
MaxFileSize int
Timeout time.Duration
}
type degradeConfig struct {
Expire int32
Memcache *memcache.Config
}
type bnj2019 struct {
Open bool
LiveAid int64
BnjMainAid int64
FakeElec int64
BnjListAids []int64
BnjTick time.Duration
Timeline []*struct {
Name string
Start xtime.Time
End xtime.Time
Cover string
H5Cover string
}
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init init conf
func Init() error {
if confPath != "" {
return local()
}
return remote()
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
client.Watch("web-interface.toml")
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}

View File

@@ -0,0 +1,119 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"abserver_test.go",
"account_redis_test.go",
"archive_test.go",
"article_redis_test.go",
"bfs_test.go",
"bigdata_test.go",
"bnj_test.go",
"dao_test.go",
"dynamic_redis_test.go",
"elec_test.go",
"feedback_test.go",
"help_test.go",
"icon_redis_test.go",
"newlist_redis_test.go",
"online_redis_test.go",
"online_test.go",
"pay_test.go",
"ranking_redis_test.go",
"reply_test.go",
"search_test.go",
"shop_test.go",
"space_test.go",
"tag_test.go",
"view_redis_test.go",
"wechat_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/web/conf:go_default_library",
"//app/interface/main/web/model:go_default_library",
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//app/service/main/dynamic/model:go_default_library",
"//app/service/main/resource/model:go_default_library",
"//library/ecode:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"abserver.go",
"account_redis.go",
"archive.go",
"article_redis.go",
"bfs.go",
"bigdata.go",
"bnj.go",
"dao.go",
"dynamic_redis.go",
"elec.go",
"feedback.go",
"help.go",
"icon_redis.go",
"newlist_redis.go",
"online.go",
"online_redis.go",
"pay.go",
"ranking_redis.go",
"reply.go",
"search.go",
"shop.go",
"space.go",
"tag.go",
"view_redis.go",
"wechat.go",
],
importpath = "go-common/app/interface/main/web/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/web/conf:go_default_library",
"//app/interface/main/web/model:go_default_library",
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//app/service/main/dynamic/model:go_default_library",
"//app/service/main/resource/model:go_default_library",
"//library/cache/redis:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/net/trace:go_default_library",
"//library/stat/prom:go_default_library",
"//library/time:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_abServerURI = "/abserver/v1/web/match-exp"
)
// AbServer get ab server info.
func (d *Dao) AbServer(c context.Context, mid int64, platform int, channel, buvid string) (res model.AbServer, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("channel", channel)
params.Set("buvid", buvid)
params.Set("platform", strconv.Itoa(platform))
var data struct {
Code int `json:"errorCode"`
model.AbServer
}
if err = d.httpR.Get(c, d.abServerURL, ip, params, &data); err != nil {
log.Error("AbServer(%s) mid(%d) channel(%s) buvid(%s) error(%v)", d.abServerURL, mid, channel, buvid, err)
return
}
if data.Code != ecode.OK.Code() {
log.Error("AbServer(%s) mid(%d) channel(%s) buvid(%s) code error(%d)", d.abServerURL, mid, channel, buvid, data.Code)
return
}
res = data.AbServer
return
}

View File

@@ -0,0 +1,27 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAbServer(t *testing.T) {
convey.Convey("AbServer", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
platform = int(0)
channel = "test"
buvid = "test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.AbServer(c, mid, platform, channel, buvid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,75 @@
package dao
import (
"context"
"fmt"
"encoding/json"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyCardFmt = "ac_%d"
)
func keyCard(mid int64) string {
return fmt.Sprintf(_keyCardFmt, mid)
}
// SetCardBakCache set card data to cache.
func (d *Dao) SetCardBakCache(c context.Context, mid int64, rs *model.Card) (err error) {
var bs []byte
key := keyCard(mid)
if bs, err = json.Marshal(rs); err != nil {
log.Error("json.Marshal(%v) error(%v)", rs, err)
return
}
err = d.commonSetBakCache(c, key, bs)
return
}
//CardBakCache get card data from cache.
func (d *Dao) CardBakCache(c context.Context, mid int64) (rs *model.Card, err error) {
key := keyCard(mid)
conn := d.redisBak.Get(c)
defer conn.Close()
var values []byte
if values, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
log.Warn("CardBakCache (%s) return nil", key)
} else {
log.Error("conn.Do(GET,%s) error(%v)", key, err)
}
return
}
if err = json.Unmarshal(values, &rs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", values, err)
}
return
}
func (d *Dao) commonSetBakCache(c context.Context, key string, bs []byte) (err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET,%s,%s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisCardBakExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s,%d) error(%v)", key, d.redisCardBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive(%d) error(%v)", i, err)
}
}
return
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyCard(t *testing.T) {
convey.Convey("keyCard", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyCard(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetCardBakCache(t *testing.T) {
convey.Convey("SetCardBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
rs = &model.Card{Card: &model.AccountCard{Mid: "2222"}, Space: &model.Space{}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetCardBakCache(c, mid, rs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCardBakCache(t *testing.T) {
convey.Convey("CardBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.CardBakCache(c, mid)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", rs)
})
})
})
}
func TestDaocommonSetBakCache(t *testing.T) {
convey.Convey("commonSetBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
bs = []byte("")
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.commonSetBakCache(c, key, bs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,200 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"go-common/library/cache/redis"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_keyArcAppeal = "arc_appeal_%d_%d"
_testerGroup = "20"
)
// ArcReport add archive report
func (d *Dao) ArcReport(c context.Context, mid, aid, tp int64, reason, pics string) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("aid", strconv.FormatInt(aid, 10))
params.Set("type", strconv.FormatInt(tp, 10))
params.Set("reason", reason)
params.Set("pics", pics)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.arcReportURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
log.Error("archive report(%s) param(%v) ecode err(%d)", d.arcReportURL, params, res.Code)
err = ecode.Int(res.Code)
}
return
}
// ArcAppeal add archive appeal.
func (d *Dao) ArcAppeal(c context.Context, mid int64, data map[string]string, business int) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
for name, value := range data {
params.Set(name, value)
}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("business", strconv.Itoa(business))
if v, ok := data["attach"]; ok && v != "" {
params.Set("attachments", v)
}
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.arcAppealURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
log.Error("archive report(%s) ecode err(%d)", d.arcAppealURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}
// AppealTags get appeal tags.
func (d *Dao) AppealTags(c context.Context, business int) (rs json.RawMessage, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("business", strconv.Itoa(business))
var res struct {
Code int `json:"code"`
Data json.RawMessage `json:"data"`
}
if err = d.httpR.Get(c, d.appealTagsURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
log.Error("archive report(%s) param(%v) ecode err(%d)", d.arcReportURL, params, res.Code)
err = ecode.Int(res.Code)
}
rs = res.Data
return
}
// RelatedAids get related aids from bigdata
func (d *Dao) RelatedAids(c context.Context, aid int64) (aids []int64, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("key", strconv.FormatInt(aid, 10))
var res struct {
Code int `json:"code"`
Data []*struct {
Value string `json:"value"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.relatedURL, ip, params, &res); err != nil {
log.Error("realte url(%s) error(%v) ", d.relatedURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("url(%s) res code(%d) or res.result(%v)", d.relatedURL+"?"+params.Encode(), res.Code, res.Data)
err = ecode.Int(res.Code)
return
}
if res.Data == nil {
err = nil
return
}
if len(res.Data) > 0 {
if aids, err = xstr.SplitInts(res.Data[0].Value); err != nil {
log.Error("realte aids url(%s) error(%v)", d.relatedURL+"?"+params.Encode(), err)
}
}
return
}
func keyArcAppealLimit(mid, aid int64) string {
return fmt.Sprintf(_keyArcAppeal, mid, aid)
}
// SetArcAppealCache set arc appeal cache.
func (d *Dao) SetArcAppealCache(c context.Context, mid, aid int64) (err error) {
key := keyArcAppealLimit(mid, aid)
conn := d.redisBak.Get(c)
defer conn.Close()
if err = conn.Send("SET", key, "1"); err != nil {
log.Error("SetArcAppealCache conn.Send(SET, %s) error(%v)", key, err)
return
}
if err = conn.Send("EXPIRE", key, d.redisAppealLimitExpire); err != nil {
log.Error("SetArcAppealCache conn.Send(Expire, %s, %d) error(%v)", key, d.redisAppealLimitExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("SetArcAppealCache conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("SetArcAppealCache conn.Receive() error(%v)", err)
return
}
}
return
}
// ArcAppealCache get arc appeal cache.
func (d *Dao) ArcAppealCache(c context.Context, mid, aid int64) (err error) {
key := keyArcAppealLimit(mid, aid)
conn := d.redisBak.Get(c)
defer conn.Close()
if _, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
return
}
log.Error("ArcAppealCache conn.Do(GET, %s) error(%v)", key, err)
}
err = ecode.ArcAppealLimit
return
}
// Special manager special mid.
func (d *Dao) Special(c context.Context) (midsM map[int64]struct{}, err error) {
params := url.Values{}
params.Set("group_id", _testerGroup)
var res struct {
Code int `json:"code"`
Data []struct {
Mid int64 `json:"mid"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.special, "", params, &res); err != nil {
err = errors.Wrap(err, d.special+"?"+params.Encode())
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.special+"?"+params.Encode())
return
}
midsM = make(map[int64]struct{}, len(res.Data))
for _, l := range res.Data {
midsM[l.Mid] = struct{}{}
}
return
}

View File

@@ -0,0 +1,124 @@
package dao
import (
"context"
"go-common/library/ecode"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoArcAppeal(t *testing.T) {
convey.Convey("ArcAppeal", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
business = int(1)
)
data := map[string]string{"tid": "27", "oid": "222", "description": "test111"}
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.ArcAppeal(c, mid, data, business)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAppealTags(t *testing.T) {
convey.Convey("AppealTags", t, func(ctx convey.C) {
var (
c = context.Background()
business = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.AppealTags(c, business)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRelatedAids(t *testing.T) {
convey.Convey("RelatedAids", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(9912124)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.relatedURL).Reply(200).JSON(`{"data":[{"key":"33817773","value":"14536406,25731794"}]}`)
aids, err := d.RelatedAids(c, aid)
ctx.Convey("Then err should be nil.aids should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(aids, convey.ShouldNotBeNil)
ctx.Printf("%+v", aids)
})
})
})
}
func TestDaokeyArcAppealLimit(t *testing.T) {
convey.Convey("keyArcAppealLimit", t, func(ctx convey.C) {
var (
mid = int64(0)
aid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyArcAppealLimit(mid, aid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetArcAppealCache(t *testing.T) {
convey.Convey("SetArcAppealCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
aid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetArcAppealCache(c, mid, aid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoArcAppealCache(t *testing.T) {
convey.Convey("ArcAppealCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
aid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.ArcAppealCache(c, mid, aid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.ArcAppealLimit)
})
})
})
}
func TestDaoSpecial(t *testing.T) {
convey.Convey("Special", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
midsM, err := d.Special(c)
convCtx.Convey("Then err should be nil.midsM should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(midsM, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,132 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/interface/main/web/model"
artmdl "go-common/app/interface/openplatform/article/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyArtList = "art_%d_%d"
_keyArtUp = "art_u"
)
func keyArtList(rid int64, sort int) string {
return fmt.Sprintf(_keyArtList, rid, sort)
}
// ArticleListCache get article list cache
func (d *Dao) ArticleListCache(c context.Context, rid int64, sort int) (res []*artmdl.Meta, err error) {
var (
value []byte
key = keyArtList(rid, sort)
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
res = []*artmdl.Meta{}
if err = json.Unmarshal(value, &res); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetArticleListCache set article list cache
func (d *Dao) SetArticleListCache(c context.Context, rid int64, sort int, list []*artmdl.Meta) (err error) {
var (
bs []byte
key = keyArtList(rid, sort)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(list); err != nil {
log.Error("json.Marshal(%v) error (%v)", list, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisArtBakExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisArtBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// ArticleUpListCache get article up list cache.
func (d *Dao) ArticleUpListCache(c context.Context) (res []*model.Info, err error) {
var (
value []byte
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", _keyArtUp)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", _keyArtUp, err)
}
return
}
res = []*model.Info{}
if err = json.Unmarshal(value, &res); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetArticleUpListCache set article up list cache.
func (d *Dao) SetArticleUpListCache(c context.Context, list []*model.Info) (err error) {
var (
bs []byte
key = _keyArtUp
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(list); err != nil {
log.Error("json.Marshal(%v) error (%v)", list, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisArtBakExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisArtBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,90 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
artmdl "go-common/app/interface/openplatform/article/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyArtList(t *testing.T) {
convey.Convey("keyArtList", t, func(ctx convey.C) {
var (
rid = int64(0)
sort = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyArtList(rid, sort)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoArticleListCache(t *testing.T) {
convey.Convey("ArticleListCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int64(0)
sort = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ArticleListCache(c, rid, sort)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
convey.Printf("%+v", res)
})
})
})
}
func TestDaoSetArticleListCache(t *testing.T) {
convey.Convey("SetArticleListCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int64(0)
sort = int(0)
list = []*artmdl.Meta{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetArticleListCache(c, rid, sort, list)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoArticleUpListCache(t *testing.T) {
convey.Convey("ArticleUpListCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ArticleUpListCache(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", res)
})
})
})
}
func TestDaoSetArticleUpListCache(t *testing.T) {
convey.Convey("SetArticleUpListCache", t, func(ctx convey.C) {
var (
c = context.Background()
list = []*model.Info{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetArticleUpListCache(c, list)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,93 @@
package dao
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"hash"
"net/http"
"strconv"
"strings"
"time"
"go-common/library/log"
"go-common/library/net/trace"
)
const (
_uploadURL = "/%s"
_family = "http_client"
_template = "%s\n%s\n\n%d\n"
_method = "PUT"
_fileType = "txt"
)
var (
errUpload = errors.New("Upload failed")
)
// Upload upload picture or log file to bfs
func (d *Dao) Upload(c context.Context, content string, expire int64) (location string, err error) {
var (
url string
req *http.Request
resp *http.Response
header http.Header
code string
)
bfsConf := d.c.Bfs
url = fmt.Sprintf(bfsConf.Addr+_uploadURL, bfsConf.Bucket)
if req, err = http.NewRequest(_method, url, strings.NewReader(content)); err != nil {
log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
return
}
authorization := authorize(bfsConf.Key, bfsConf.Secret, _method, bfsConf.Bucket, expire)
req.Header.Set("Host", bfsConf.Addr)
req.Header.Add("Date", fmt.Sprint(expire))
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", _fileType)
if t, ok := trace.FromContext(c); ok {
t = t.Fork(_family, req.URL.Path)
defer t.Finish(&err)
}
c, cancel := context.WithTimeout(c, time.Duration(d.c.Bfs.Timeout))
req = req.WithContext(c)
defer cancel()
resp, err = d.bfsClient.Do(req)
if err != nil {
log.Error("bfsClient.Do(%s) error(%v)", url, err)
return
}
if resp.StatusCode != http.StatusOK {
log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
err = errUpload
return
}
header = resp.Header
code = header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
log.Error("Upload url(%s) code:%s", url, code)
err = errUpload
return
}
location = header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}

View File

@@ -0,0 +1,25 @@
package dao
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoauthorize(t *testing.T) {
convey.Convey("authorize", t, func(ctx convey.C) {
var (
key = ""
secret = ""
method = ""
bucket = ""
expire = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
authorization := authorize(key, secret, method, bucket, expire)
ctx.Convey("Then authorization should not be nil.", func(ctx convey.C) {
ctx.So(authorization, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,203 @@
package dao
import (
"context"
"fmt"
"net/url"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_rankURI = "%s.json"
_rankAllURI = "all-%d"
_rankAllRidURI = "all_region-%d-%d"
_rankAllRecURI = "recent_all-%d"
_rankAllRecRidURI = "recent_region-%d-%d"
_rankOriAllURI = "all_origin-%d"
_rankOriAllRidURI = "all_region_origin-%d-%d"
_rankOriRecURI = "recent_origin-%d"
_rankOriRecRidURI = "recent_region_origin-%d-%d"
_rankAllNewURI = "all_rookie-%d"
_rankAllNewRidURI = "all_region_rookie-%d-%d"
_rankRegionURI = "recent_region%s-%d-%d.json"
_rankRecURI = "reco_region-%d.json"
_rankTagURI = "/tag/hot/web/%d/%d.json"
_rankIndexURI = "reco-%d.json"
_customURI = "game_custom_2.json"
)
// Ranking get ranking data from new api
func (d *Dao) Ranking(c context.Context, rid int16, rankType, day, arcType int) (res *model.RankNew, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
suffix := rankURI(rid, model.RankType[rankType], day, arcType)
var rs struct {
Code int `json:"code"`
Note string `json:"note"`
List []*model.RankNewArchive `json:"list"`
}
if err = d.httpBigData.RESTfulGet(c, d.rankURL, ip, params, &rs, suffix); err != nil {
log.Error("d.httpBigData.RESTfulGet(%s) error(%v)", suffix, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpBigData.RESTfulGet(%s) error code(%d)", suffix, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = &model.RankNew{Note: rs.Note, List: rs.List}
return
}
// RankingIndex get rank index data from bigdata
func (d *Dao) RankingIndex(c context.Context, day int) (res []*model.NewArchive, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
var rs struct {
Code int `json:"code"`
Num int `json:"num"`
List []*model.NewArchive `json:"list"`
}
if err = d.httpBigData.RESTfulGet(c, d.rankIndexURL, remoteIP, params, &rs, day); err != nil {
log.Error("d.httpBigData.RESTfulGet(%d) error(%v)", day, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpBigData.RESTfulGet(%d) error(%v)", day, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = rs.List
return
}
// RankingRegion get rank region data from bigdata
func (d *Dao) RankingRegion(c context.Context, rid int16, day, original int) (res []*model.NewArchive, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
var rs struct {
Code int `json:"code"`
List []*model.NewArchive `json:"list"`
}
if err = d.httpBigData.RESTfulGet(c, d.rankRegionURL, remoteIP, params, &rs, model.OriType[original], rid, day); err != nil {
log.Error("d.httpBigData.RESTfulGet(%d,%d,%d) error(%v)", original, rid, day, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpBigData.RESTfulGet(%d,%d,%d) error code(%d)", original, rid, day, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = rs.List
return
}
// RankingRecommend get rank recommend data from bigdata.
func (d *Dao) RankingRecommend(c context.Context, rid int16) (res []*model.NewArchive, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
var rs struct {
Code int `json:"code"`
Num int `json:"num"`
List []*model.NewArchive `json:"list"`
}
if err = d.httpBigData.RESTfulGet(c, d.rankRecURL, remoteIP, params, &rs, rid); err != nil {
log.Error("d.httpBigData.RESTfulGet(%d) error(%v)", rid, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpBigData.RESTfulGet(%d) error(%v)", rid, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = rs.List
return
}
// RankingTag get rank tag data from bigdata
func (d *Dao) RankingTag(c context.Context, rid int16, tagID int64) (rs []*model.NewArchive, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
var res struct {
Code int `json:"code"`
List []*model.NewArchive `json:"list"`
}
if err = d.httpBigData.RESTfulGet(c, d.rankTagURL, remoteIP, params, &res, rid, tagID); err != nil {
log.Error("d.httpBigData.RESTfulGet(%d,%d) error(%v)", rid, tagID, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpBigData.RESTfulGet(%d,%d) code(%d)", rid, tagID, res.Code)
err = ecode.Int(res.Code)
return
}
rs = res.List
return
}
// RegionCustom get region(game) custom data from big data
func (d *Dao) RegionCustom(c context.Context) (rs []*model.Custom, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
var res struct {
Code int
List []*model.Custom
}
if err = d.httpBigData.Get(c, d.customURL, ip, params, &res); err != nil {
log.Error("d.httpBigData.Get(%s) error(%v)", d.customURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpBigData.Get(%s) error(%v)", d.customURL, err)
err = ecode.Int(res.Code)
return
}
rs = res.List
return
}
func rankURI(rid int16, rankType string, day, arcType int) string {
if rankType == model.RankType[1] {
if arcType == 1 {
if rid > 0 {
return fmt.Sprintf(_rankAllRecRidURI, rid, day)
}
return fmt.Sprintf(_rankAllRecURI, day)
}
if rid > 0 {
return fmt.Sprintf(_rankAllRidURI, rid, day)
}
return fmt.Sprintf(_rankAllURI, day)
} else if rankType == model.RankType[2] {
if arcType == 1 {
if rid > 0 {
return fmt.Sprintf(_rankOriRecRidURI, rid, day)
}
return fmt.Sprintf(_rankOriRecURI, day)
}
if rid > 0 {
return fmt.Sprintf(_rankOriAllRidURI, rid, day)
}
return fmt.Sprintf(_rankOriAllURI, day)
}
if rid > 0 {
return fmt.Sprintf(_rankAllNewRidURI, rid, day)
}
return fmt.Sprintf(_rankAllNewURI, day)
}

View File

@@ -0,0 +1,139 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoRanking(t *testing.T) {
convey.Convey("Ranking", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
rankType = int(0)
day = int(0)
arcType = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Rank+_rankURL).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715,"score":704},{"aid":33913315,"score":571}]}`)
res, err := d.Ranking(c, rid, rankType, day, arcType)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRankingIndex(t *testing.T) {
convey.Convey("RankingIndex", t, func(ctx convey.C) {
var (
c = context.Background()
day = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Rank+_rankURL).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715,"score":704},{"aid":33913315,"score":571}]}`)
res, err := d.RankingIndex(c, day)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRankingRegion(t *testing.T) {
convey.Convey("RankingRegion", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
day = int(0)
original = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Rank+_rankURL).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715,"score":704},{"aid":33913315,"score":571}]}`)
res, err := d.RankingRegion(c, rid, day, original)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRankingRecommend(t *testing.T) {
convey.Convey("RankingRecommend", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Rank+_rankURL).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715,"score":704},{"aid":33913315,"score":571}]}`)
res, err := d.RankingRecommend(c, rid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRankingTag(t *testing.T) {
convey.Convey("RankingTag", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
tagID = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Rank).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715,"score":704},{"aid":33913315,"score":571}]}`)
rs, err := d.RankingTag(c, rid, tagID)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRegionCustom(t *testing.T) {
convey.Convey("RegionCustom", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.customURL).Reply(200).JSON(`{"code":0,"num":8,"list":[{"aid":33986715},{"aid":33913315}]}`)
rs, err := d.RegionCustom(c)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaorankURI(t *testing.T) {
convey.Convey("rankURI", t, func(ctx convey.C) {
var (
rid = int16(0)
rankType = ""
day = int(0)
arcType = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := rankURI(rid, rankType, day, arcType)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,44 @@
package dao
import (
"context"
"fmt"
"strconv"
"strings"
"go-common/library/ecode"
"github.com/pkg/errors"
)
const _bnjConfURI = "/activity/v0/bainian/config"
// Bnj2019Conf .
func (d *Dao) Bnj2019Conf(c context.Context) (mids []int64, err error) {
var res struct {
Code int `json:"code"`
Data struct {
GreyStatus int `json:"grey_status"`
GreyUids string `json:"grey_uids"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.bnjConfURL, "", nil, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.bnjConfURL)
return
}
if res.Data.GreyStatus == 1 {
midsStr := strings.Split(res.Data.GreyUids, ",")
for _, midStr := range midsStr {
var mid int64
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {
err = fmt.Errorf("live grey_uids(%s)", res.Data.GreyUids)
return
}
mids = append(mids, mid)
}
}
return
}

View File

@@ -0,0 +1,21 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_Bnj2019Conf(t *testing.T) {
convey.Convey("ElecShow", t, func(ctx convey.C) {
var c = context.Background()
ctx.Convey("When everything gose positive", func(ctx convey.C) {
rs, err := d.Bnj2019Conf(c)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", rs)
})
})
})
}

View File

@@ -0,0 +1,222 @@
package dao
import (
"context"
xhttp "net/http"
"time"
"go-common/app/interface/main/web/conf"
"go-common/library/cache/redis"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
)
const (
_rankURL = "/data/rank/"
_feedbackURL = "/x/internal/feedback/ugc/add"
_spaceTopPhotoURL = "/api/member/getTopPhoto"
_coinAddURL = "/x/coin/add"
_coinExpURL = "/x/coin/today/exp"
_elecShowURL = "/api/v2/rank/query/av"
_arcReportURL = "/videoup/archive/report"
_arcAppealURL = "/x/internal/workflow/appeal/add"
_appealTagsURL = "/x/internal/workflow/tag/list"
_relatedURL = "/recsys/related"
_onlineURL = "/x/internal/chat/server/ol"
_liveOnlineURL = "/room/v1/Online/get_total_online"
_helpListURL = "/kb/getQuestionTypeListByParentIdBilibili/4"
_helpSearchURL = "/kb/searchInerDocListBilibili/4"
_onlineListURL = "/x/internal/chat/num/top/aid"
_searchURL = "/main/search"
_searchRecURL = "/search/recommend"
_searchDefaultURL = "/query/recommend"
_searchUpRecURL = "/main/recommend"
_searchEggURI = "/x/admin/feed/eggSearchWeb"
_payWalletURL = "/wallet-int/wallet/getUserWalletInfo"
_payWalletOldURL = "/wallet/api/v1/info"
_special = "/x/internal/uper/special"
)
// Dao dao
type Dao struct {
// config
c *conf.Config
// http client
httpR *bm.Client
httpW *bm.Client
httpBigData *bm.Client
httpHelp *bm.Client
httpSearch *bm.Client
httpPay *bm.Client
bfsClient *xhttp.Client
// redis
redis *redis.Pool
redisBak *redis.Pool
redisNlExpire int32
redisNlBakExpire int32
redisRkExpire int32
redisRkBakExpire int32
redisDynamicBakExpire int32
redisArchiveBakExpire int32
redisTagBakExpire int32
redisCardBakExpire int32
redisRcExpire int32
redisRcBakExpire int32
redisArtBakExpire int32
redisIxIconExpire int32
redisIxIconBakExpire int32
redisHelpBakExpire int32
redisOlListBakExpire int32
redisWxHotExpire int32
redisWxHotBakExpire int32
redisAppealLimitExpire int32
// bigdata url
rankURL string
rankIndexURL string
rankRegionURL string
rankRecURL string
rankTagURL string
feedbackURL string
spaceTopPhotoURL string
coinAddURL string
coinExpURL string
customURL string
elecShowURL string
arcReportURL string
appealTagsURL string
arcAppealURL string
relatedURL string
onlineURL string
liveOnlineURL string
helpListURL string
helpSearchURL string
onlineListURL string
shopURL string
replyHotURL string
searchURL string
searchRecURL string
searchDefaultURL string
searchUpRecURL string
searchEggURL string
walletURL string
walletOldURL string
abServerURL string
wxHotURL string
bnjConfURL string
special string
// cache Prom
cacheProm *prom.Prom
}
// New dao new
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// config
c: c,
// http read client
httpR: bm.NewClient(c.HTTPClient.Read),
httpW: bm.NewClient(c.HTTPClient.Write),
httpBigData: bm.NewClient(c.HTTPClient.BigData),
httpHelp: bm.NewClient(c.HTTPClient.Help),
httpSearch: bm.NewClient(c.HTTPClient.Search),
httpPay: bm.NewClient(c.HTTPClient.Pay),
// init bfs http client
bfsClient: xhttp.DefaultClient,
// redis
redis: redis.NewPool(c.Redis.LocalRedis.Config),
redisBak: redis.NewPool(c.Redis.BakRedis.Config),
redisNlExpire: int32(time.Duration(c.Redis.LocalRedis.NewlistExpire) / time.Second),
redisNlBakExpire: int32(time.Duration(c.Redis.BakRedis.NewlistExpire) / time.Second),
redisRkExpire: int32(time.Duration(c.Redis.LocalRedis.RankingExpire) / time.Second),
redisRkBakExpire: int32(time.Duration(c.Redis.BakRedis.RankingExpire) / time.Second),
redisDynamicBakExpire: int32(time.Duration(c.Redis.BakRedis.RegionExpire) / time.Second),
redisArchiveBakExpire: int32(time.Duration(c.Redis.BakRedis.ArchiveExpire) / time.Second),
redisTagBakExpire: int32(time.Duration(c.Redis.BakRedis.TagExpire) / time.Second),
redisCardBakExpire: int32(time.Duration(c.Redis.BakRedis.CardExpire) / time.Second),
redisRcExpire: int32(time.Duration(c.Redis.LocalRedis.RcExpire) / time.Second),
redisRcBakExpire: int32(time.Duration(c.Redis.BakRedis.RcExpire) / time.Second),
redisArtBakExpire: int32(time.Duration(c.Redis.BakRedis.ArtUpExpire) / time.Second),
redisIxIconExpire: int32(time.Duration(c.Redis.LocalRedis.IndexIconExpire) / time.Second),
redisIxIconBakExpire: int32(time.Duration(c.Redis.BakRedis.IndexIconExpire) / time.Second),
redisHelpBakExpire: int32(time.Duration(c.Redis.BakRedis.HelpExpire) / time.Second),
redisOlListBakExpire: int32(time.Duration(c.Redis.BakRedis.OlListExpire) / time.Second),
redisWxHotExpire: int32(time.Duration(c.Redis.LocalRedis.WxHotExpire) / time.Second),
redisWxHotBakExpire: int32(time.Duration(c.Redis.BakRedis.WxHotExpire) / time.Second),
redisAppealLimitExpire: int32(time.Duration(c.Redis.BakRedis.AppealLimitExpire) / time.Second),
// remote source urls
rankURL: c.Host.Rank + _rankURL + _rankURI,
rankIndexURL: c.Host.Rank + _rankURL + _rankIndexURI,
rankRegionURL: c.Host.Rank + _rankURL + _rankRegionURI,
rankRecURL: c.Host.Rank + _rankURL + _rankRecURI,
wxHotURL: c.Host.Rank + _rankURL + _wxHotURI,
rankTagURL: c.Host.Rank + _rankTagURI,
feedbackURL: c.Host.API + _feedbackURL,
spaceTopPhotoURL: c.Host.Space + _spaceTopPhotoURL,
coinAddURL: c.Host.API + _coinAddURL,
coinExpURL: c.Host.API + _coinExpURL,
customURL: c.Host.Rank + _rankURL + _customURI,
elecShowURL: c.Host.Elec + _elecShowURL,
arcReportURL: c.Host.ArcAPI + _arcReportURL,
appealTagsURL: c.Host.API + _appealTagsURL,
arcAppealURL: c.Host.API + _arcAppealURL,
relatedURL: c.Host.Data + _relatedURL,
onlineURL: c.Host.API + _onlineURL,
liveOnlineURL: c.Host.LiveAPI + _liveOnlineURL,
helpListURL: c.Host.HelpAPI + _helpListURL,
helpSearchURL: c.Host.HelpAPI + _helpSearchURL,
onlineListURL: c.Host.API + _onlineListURL,
shopURL: c.Host.Mall + _shopURI,
replyHotURL: c.Host.API + _hotURI,
searchURL: c.Host.Search + _searchURL,
searchRecURL: c.Host.Search + _searchRecURL,
searchDefaultURL: c.Host.Search + _searchDefaultURL,
searchUpRecURL: c.Host.Search + _searchUpRecURL,
searchEggURL: c.Host.Manager + _searchEggURI,
walletURL: c.Host.Pay + _payWalletURL,
walletOldURL: c.Host.Pay + _payWalletOldURL,
abServerURL: c.Host.AbServer + _abServerURI,
bnjConfURL: c.Host.LiveAPI + _bnjConfURI,
special: c.Host.API + _special,
// prom
cacheProm: prom.CacheHit,
}
return d
}
// Ping check connection success.
func (dao *Dao) Ping(c context.Context) (err error) {
if err = dao.pingRedis(c); err != nil {
log.Error("dao.pingRedis error(%v)", err)
return
}
if err = dao.pingRedisBak(c); err != nil {
log.Error("dao.pingRedisBak error(%v)", err)
return
}
return
}
// Close close resource.
func (dao *Dao) Close() {
if dao.redis != nil {
dao.redis.Close()
}
if dao.redisBak != nil {
dao.redisBak.Close()
}
}
func (dao *Dao) pingRedis(c context.Context) (err error) {
conn := dao.redis.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}
func (dao *Dao) pingRedisBak(c context.Context) (err error) {
conn := dao.redisBak.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}

View File

@@ -0,0 +1,47 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/interface/main/web/conf"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "local" {
flag.Set("app_id", "main.web-svr.web-interface")
flag.Set("conf_token", "bc99caee81f27661bd5ff50d1c0d58d6")
flag.Set("tree_id", "2685")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/web-interface-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.httpR.SetTransport(gock.DefaultTransport)
d.httpBigData.SetTransport(gock.DefaultTransport)
d.httpHelp.SetTransport(gock.DefaultTransport)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}

View File

@@ -0,0 +1,163 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/service/main/archive/api"
dymdl "go-common/app/service/main/dynamic/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyRegion = "dr_"
_keyRegionTag = "drt_"
_keyRegions = "drs_"
_keyRegionFmt = "%d_%d_%d"
_keyRegionTagFmt = "%d_%d_%d_%d"
)
func keyRegion(rid int32, pn, ps int) string {
return _keyRegion + fmt.Sprintf(_keyRegionFmt, rid, pn, ps)
}
func keyRegionTag(tagID int64, rid int32, pn, ps int) string {
return _keyRegionTag + fmt.Sprintf(_keyRegionTagFmt, tagID, rid, pn, ps)
}
// SetRegionBakCache set dynamic region data to cache.
func (d *Dao) SetRegionBakCache(c context.Context, rid int32, pn, ps int, rs *dymdl.DynamicArcs3) (err error) {
key := keyRegion(rid, pn, ps)
err = d.setBakCache(c, key, rs)
return
}
// RegionBakCache get dynamic region from cache.
func (d *Dao) RegionBakCache(c context.Context, rid int32, pn, ps int) (rs *dymdl.DynamicArcs3, err error) {
d.cacheProm.Incr("dynamic_region_remote_cache")
key := keyRegion(rid, pn, ps)
rs, err = d.bakCache(c, key)
if rs == nil {
log.Error("RegionBakCache d.bakCache(%d,%d,%d,%s) is nill", rid, pn, ps, key)
}
return
}
// SetRegionTagBakCache set dynamic region tag data to cache.
func (d *Dao) SetRegionTagBakCache(c context.Context, tagID int64, rid int32, pn, ps int, rs *dymdl.DynamicArcs3) (err error) {
key := keyRegionTag(tagID, rid, pn, ps)
err = d.setBakCache(c, key, rs)
return
}
// RegionTagBakCache get dynamic region tag from cache.
func (d *Dao) RegionTagBakCache(c context.Context, tagID int64, rid int32, pn, ps int) (rs *dymdl.DynamicArcs3, err error) {
d.cacheProm.Incr("dynamic_tag_remote_cache")
key := keyRegionTag(tagID, rid, pn, ps)
rs, err = d.bakCache(c, key)
if rs == nil {
log.Error("RegionTagBakCache d.bakCache(%d,%d,%d,%s) is nill", rid, pn, ps, key)
}
return
}
// SetRegionsBakCache set regions data to cache.
func (d *Dao) SetRegionsBakCache(c context.Context, rs map[int32][]*api.Arc) (err error) {
key := _keyRegions
conn := d.redisBak.Get(c)
defer conn.Close()
var bs []byte
if bs, err = json.Marshal(rs); err != nil {
log.Error("json.Marshal(%v) error(%v)", rs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET,%s,%s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisDynamicBakExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s,%d) error(%v)", key, d.redisDynamicBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Recevie(%d) error(%v0", i, err)
}
}
return
}
// RegionsBakCache get dynamic region data from cache.
func (d *Dao) RegionsBakCache(c context.Context) (rs map[int32][]*api.Arc, err error) {
d.cacheProm.Incr("dynamic_regions_remote_cache")
conn := d.redisBak.Get(c)
defer conn.Close()
var values []byte
if values, err = redis.Bytes(conn.Do("GET", _keyRegions)); err != nil {
if err == redis.ErrNil {
err = nil
log.Error("RegionsBakCache (%s) return nil ", _keyRegions)
} else {
log.Error("conn.Do(GET,%s) error(%v)", _keyRegions, err)
}
return
}
rs = make(map[int32][]*api.Arc)
if err = json.Unmarshal(values, &rs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", values, err)
}
return
}
func (d *Dao) setBakCache(c context.Context, key string, rs *dymdl.DynamicArcs3) (err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
var bs []byte
if bs, err = json.Marshal(rs); err != nil {
log.Error("json.Marshal(%v) error(%v)", rs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET,%s,%s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisDynamicBakExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s,%d) error(%v)", key, d.redisDynamicBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive(%d) error(%v)", i, err)
}
}
return
}
func (d *Dao) bakCache(c context.Context, key string) (rs *dymdl.DynamicArcs3, err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
var values []byte
if values, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET,%s) error(%v)", key, err)
}
return
}
rs = &dymdl.DynamicArcs3{}
if err = json.Unmarshal(values, rs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", values, err)
}
return
}

View File

@@ -0,0 +1,179 @@
package dao
import (
"context"
"go-common/app/service/main/archive/api"
dymdl "go-common/app/service/main/dynamic/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyRegion(t *testing.T) {
convey.Convey("keyRegion", t, func(ctx convey.C) {
var (
rid = int32(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRegion(rid, pn, ps)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRegionTag(t *testing.T) {
convey.Convey("keyRegionTag", t, func(ctx convey.C) {
var (
tagID = int64(0)
rid = int32(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRegionTag(tagID, rid, pn, ps)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetRegionBakCache(t *testing.T) {
convey.Convey("SetRegionBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int32(0)
pn = int(0)
ps = int(0)
rs = &dymdl.DynamicArcs3{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRegionBakCache(c, rid, pn, ps, rs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoRegionBakCache(t *testing.T) {
convey.Convey("RegionBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int32(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.RegionBakCache(c, rid, pn, ps)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetRegionTagBakCache(t *testing.T) {
convey.Convey("SetRegionTagBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int64(0)
rid = int32(0)
pn = int(0)
ps = int(0)
rs = &dymdl.DynamicArcs3{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRegionTagBakCache(c, tagID, rid, pn, ps, rs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoRegionTagBakCache(t *testing.T) {
convey.Convey("RegionTagBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int64(0)
rid = int32(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.RegionTagBakCache(c, tagID, rid, pn, ps)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetRegionsBakCache(t *testing.T) {
convey.Convey("SetRegionsBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
rs := map[int32][]*api.Arc{1111: {{Aid: 1111}}}
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRegionsBakCache(c, rs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoRegionsBakCache(t *testing.T) {
convey.Convey("RegionsBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.RegionsBakCache(c)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaosetBakCache(t *testing.T) {
convey.Convey("setBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
rs = &dymdl.DynamicArcs3{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.setBakCache(c, key, rs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaobakCache(t *testing.T) {
convey.Convey("bakCache", t, func(ctx convey.C) {
var (
c = context.Background()
key = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.bakCache(c, key)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"net/url"
"strconv"
"time"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
// ElecShow elec show.
func (d *Dao) ElecShow(c context.Context, mid, aid, loginID int64) (rs *model.ElecShow, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("mid", strconv.FormatInt(mid, 10))
if loginID > 0 {
params.Set("login_mid", strconv.FormatInt(loginID, 10))
}
params.Set("aid", strconv.FormatInt(aid, 10))
params.Set("act", "appkey")
var res struct {
Code int `json:"code"`
Data *model.ElecShow `json:"data"`
}
if err = d.httpR.Get(c, d.elecShowURL, remoteIP, params, &res); err != nil {
log.Error("ElecShow url(%s) error(%v)", d.elecShowURL+"?"+params.Encode(), err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
return
}
rs = res.Data
return
}

View File

@@ -0,0 +1,29 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoElecShow(t *testing.T) {
convey.Convey("ElecShow", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
aid = int64(10100652)
loginID = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.elecShowURL).Reply(200).JSON(`{"code":0,"data":{"show":true,"state":1}}`)
rs, err := d.ElecShow(c, mid, aid, loginID)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,56 @@
package dao
import (
"context"
"encoding/json"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const _platform = "web"
// Feedback feedback http request.
func (d *Dao) Feedback(c context.Context, feedParams *model.Feedback) (err error) {
var (
content []byte
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
if feedParams.Aid > 0 {
params.Set("aid", strconv.FormatInt(feedParams.Aid, 10))
}
params.Set("mid", strconv.FormatInt(feedParams.Mid, 10))
params.Set("tag_id", strconv.FormatInt(feedParams.TagID, 10))
if content, err = json.Marshal(feedParams.Content); err != nil {
log.Error("content json.Marshal(%+v) error(%v)", feedParams.Content, err)
} else {
params.Set("content", string(content))
}
params.Set("browser", feedParams.Browser)
params.Set("version", feedParams.Version)
params.Set("buvid", feedParams.Buvid)
params.Set("platform", _platform)
if feedParams.Email != "" {
params.Set("email", feedParams.Email)
}
if feedParams.QQ != "" {
params.Set("qq", feedParams.QQ)
}
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.feedbackURL, ip, params, &res); err != nil {
log.Error("d.client.Post(%s) error(%v)", d.feedbackURL+"?"+params.Encode(), err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.client.Post(%s) code(%d)", d.feedbackURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}

View File

@@ -0,0 +1,25 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoFeedback(t *testing.T) {
convey.Convey("Feedback", t, func(ctx convey.C) {
var (
c = context.Background()
feedParams = &model.Feedback{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.Feedback(c, feedParams)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,294 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/time"
)
const (
_notRobot = -1
_rsOk = "000000"
_hlKey = "hl_%s"
_hdKey = "hd_%s_%d_%d_%d"
)
// HelpList get help list.
func (d *Dao) HelpList(c context.Context, pTypeID string) (data []*model.HelpList, err error) {
var (
req *http.Request
params = url.Values{}
)
params.Set("parentTypeId", pTypeID)
params.Set("robotFlag", strconv.Itoa(_notRobot))
listURL := d.helpListURL + "?" + params.Encode()
if req, err = http.NewRequest("GET", listURL, nil); err != nil {
log.Error("Help http.NewRequest(%s) error(%v)", listURL, err)
return
}
var res struct {
Code string `json:"retCode"`
Data []*model.HelpList `json:"items"`
}
err = d.httpHelp.Do(c, req, &res)
if err != nil {
log.Error("Help d.httpHelp.Do(%s) error(%v)", listURL, err)
return
}
if res.Code != _rsOk {
log.Error("Help dao.httpHelp.Do(%s) error(%v)", listURL, err)
err = ecode.HelpListError
return
}
data = res.Data
return
}
func keyHl(pTypeID string) string {
return fmt.Sprintf(_hlKey, pTypeID)
}
func keyHd(qTypeID string, keyFlag, pn, ps int) string {
return fmt.Sprintf(_hdKey, qTypeID, keyFlag, pn, ps)
}
// SetHlCache set help list to cache.
func (d *Dao) SetHlCache(c context.Context, pTypeID string, Hl []*model.HelpList) (err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
count := 0
key := keyHl(pTypeID)
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
var bs []byte
for _, list := range Hl {
if bs, err = json.Marshal(list); err != nil {
log.Error("json.Marshal(%v) error (%v)", list, err)
return
}
if err = conn.Send("ZADD", key, list.SortNo, bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, d.redisHelpBakExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisHelpBakExpire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// HlCache get help list from cache.
func (d *Dao) HlCache(c context.Context, pTypeID string) (res []*model.HelpList, err error) {
key := keyHl(pTypeID)
conn := d.redisBak.Get(c)
defer conn.Close()
values, err := redis.Values(conn.Do("ZREVRANGE", key, 0, -1))
if err != nil {
log.Error("conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() err(%v)", err)
return
}
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
list := &model.HelpList{}
if err = json.Unmarshal(bs, list); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
res = append(res, list)
}
return
}
// HelpDetail get help detail.
func (d *Dao) HelpDetail(c context.Context, qTypeID string, keyFlag, pn, ps int, ip string) (data []*model.HelpDeatil, total int, err error) {
var (
req *http.Request
params = url.Values{}
)
params.Set("questionTypeId", qTypeID)
params.Set("keyFlag", strconv.Itoa(keyFlag))
params.Set("keyWords", "")
params.Set("pageNo", strconv.Itoa(pn))
params.Set("pageSize", strconv.Itoa(ps))
params.Set("robotFlag", strconv.Itoa(_notRobot))
searchURL := d.helpSearchURL + "?" + params.Encode()
if req, err = http.NewRequest("GET", searchURL, nil); err != nil {
log.Error("Help http.NewRequest(%s) error(%v)", searchURL, err)
return
}
var res struct {
Code string `json:"retCode"`
Data []*model.HelpDeatil `json:"items"`
Total int `json:"totalCount"`
}
err = d.httpHelp.Do(c, req, &res)
if err != nil {
log.Error("Help d.httpHelp.Do(%s) error(%v)", searchURL, err)
return
}
if res.Code != _rsOk {
log.Error("Help dao.httpHelp.Do(%s) error(%v)", searchURL, err)
err = ecode.HelpDetailError
return
}
total = res.Total
data = res.Data
return
}
// HelpSearch get help search.
func (d *Dao) HelpSearch(c context.Context, pTypeID, keyWords string, keyFlag, pn, ps int) (data []*model.HelpDeatil, total int, err error) {
var (
req *http.Request
params = url.Values{}
)
params.Set("questionTypeId", pTypeID)
params.Set("keyWords", keyWords)
params.Set("keyFlag", strconv.Itoa(keyFlag))
params.Set("pageNo", strconv.Itoa(pn))
params.Set("pageSize", strconv.Itoa(ps))
params.Set("robotFlag", strconv.Itoa(_notRobot))
searchURL := d.helpSearchURL + "?" + params.Encode()
if req, err = http.NewRequest("GET", searchURL, nil); err != nil {
log.Error("Help http.NewRequest(%s) error(%v)", searchURL, err)
return
}
var res struct {
Code string `json:"retCode"`
Data []*model.HelpDeatil `json:"items"`
Total int `json:"totalCount"`
}
err = d.httpHelp.Do(c, req, &res)
if err != nil {
log.Error("Help d.httpHelp.Do(%s) error(%v)", searchURL, err)
return
}
if res.Code != _rsOk {
log.Error("Help dao.httpHelp.Do(%s) error(%v)", searchURL, err)
err = ecode.HelpSearchError
return
}
total = res.Total
data = res.Data
return
}
// SetDetailCache set help detail to cache.
func (d *Dao) SetDetailCache(c context.Context, qTypeID string, keyFlag, pn, ps, total int, data []*model.HelpDeatil) (err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
count := 0
key := keyHd(qTypeID, keyFlag, pn, ps)
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
var bs []byte
for _, detail := range data {
if bs, err = json.Marshal(detail); err != nil {
log.Error("json.Marshal(%v) error (%v)", detail, err)
return
}
if err = conn.Send("ZADD", key, combineHd(detail.UpdateTime, total), bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, d.redisHelpBakExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisHelpBakExpire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// DetailCache get help detail to cache.
func (d *Dao) DetailCache(c context.Context, qTypeID string, keyFlag, pn, ps int) (res []*model.HelpDeatil, count int, err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
key := keyHd(qTypeID, keyFlag, pn, ps)
values, err := redis.Values(conn.Do("ZREVRANGE", key, 0, -1, "WITHSCORES"))
if err != nil {
log.Error("conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() err(%v)", err)
return
}
var num int64
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs, &num); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
detail := &model.HelpDeatil{}
if err = json.Unmarshal(bs, detail); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
res = append(res, detail)
}
count = fromHd(num)
return
}
func fromHd(i int64) int {
return int(i & 0xffff)
}
func combineHd(create time.Time, count int) int64 {
return create.Time().Unix()<<16 | int64(count)
}

View File

@@ -0,0 +1,209 @@
package dao
import (
"context"
"testing"
xtime "time"
"go-common/app/interface/main/web/model"
"go-common/library/time"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoHelpList(t *testing.T) {
convey.Convey("HelpList", t, func(ctx convey.C) {
var (
c = context.Background()
pTypeID = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.helpListURL).Reply(200).JSON(`{"retCode":"000000"}`)
data, err := d.HelpList(c, pTypeID)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaokeyHl(t *testing.T) {
convey.Convey("keyHl", t, func(ctx convey.C) {
var (
pTypeID = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyHl(pTypeID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyHd(t *testing.T) {
convey.Convey("keyHd", t, func(ctx convey.C) {
var (
qTypeID = ""
keyFlag = int(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyHd(qTypeID, keyFlag, pn, ps)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetHlCache(t *testing.T) {
convey.Convey("SetHlCache", t, func(ctx convey.C) {
var (
c = context.Background()
pTypeID = ""
Hl = []*model.HelpList{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetHlCache(c, pTypeID, Hl)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoHlCache(t *testing.T) {
convey.Convey("HlCache", t, func(ctx convey.C) {
var (
c = context.Background()
pTypeID = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.HlCache(c, pTypeID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", res)
})
})
})
}
func TestDaoHelpDetail(t *testing.T) {
convey.Convey("HelpDetail", t, func(ctx convey.C) {
var (
c = context.Background()
qTypeID = ""
keyFlag = int(0)
pn = int(0)
ps = int(0)
ip = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.helpSearchURL).Reply(200).JSON(`{"retCode":"000000", "total":1}`)
data, total, err := d.HelpDetail(c, qTypeID, keyFlag, pn, ps, ip)
ctx.Convey("Then err should be nil.data,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaoHelpSearch(t *testing.T) {
convey.Convey("HelpSearch", t, func(ctx convey.C) {
var (
c = context.Background()
pTypeID = ""
keyWords = ""
keyFlag = int(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.helpSearchURL).Reply(200).JSON(`{"retCode":"000000", "total":1}`)
data, total, err := d.HelpSearch(c, pTypeID, keyWords, keyFlag, pn, ps)
ctx.Convey("Then err should be nil.data,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaoSetDetailCache(t *testing.T) {
convey.Convey("SetDetailCache", t, func(ctx convey.C) {
var (
c = context.Background()
qTypeID = ""
keyFlag = int(0)
pn = int(0)
ps = int(0)
total = int(0)
data = []*model.HelpDeatil{{AllTypeName: "1111"}, {AllTypeName: "2222"}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetDetailCache(c, qTypeID, keyFlag, pn, ps, total, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDetailCache(t *testing.T) {
convey.Convey("DetailCache", t, func(ctx convey.C) {
var (
c = context.Background()
qTypeID = ""
keyFlag = int(0)
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, count, err := d.DetailCache(c, qTypeID, keyFlag, pn, ps)
ctx.Convey("Then err should be nil.res,count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
convey.Printf("%+v", res)
})
})
})
}
func TestDaofromHd(t *testing.T) {
convey.Convey("fromHd", t, func(ctx convey.C) {
var (
i = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := fromHd(i)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocombineHd(t *testing.T) {
convey.Convey("combineHd", t, func(ctx convey.C) {
var (
create = time.Time(xtime.Now().Unix())
count = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := combineHd(create, count)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,92 @@
package dao
import (
"context"
"encoding/json"
resmdl "go-common/app/service/main/resource/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_indexIconKey = "iik"
_indexIconBakKey = "b_iik"
)
// SetIndexIconCache set index icon cache and bak cache
func (d *Dao) SetIndexIconCache(c context.Context, data []*resmdl.IndexIcon) (err error) {
key := _indexIconKey
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setIndexIconCache(conn, key, d.redisRcExpire, data); err != nil {
return
}
key = _indexIconBakKey
connBak := d.redisBak.Get(c)
err = d.setIndexIconCache(connBak, key, d.redisRcBakExpire, data)
connBak.Close()
return
}
func (d *Dao) setIndexIconCache(conn redis.Conn, key string, expire int32, data []*resmdl.IndexIcon) (err error) {
var bs []byte
if bs, err = json.Marshal(data); err != nil {
log.Error("json.Marshal(%v) error (%v)", data, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// IndexIconCache get index icon cache
func (d *Dao) IndexIconCache(c context.Context) (res []*resmdl.IndexIcon, err error) {
key := _indexIconKey
conn := d.redis.Get(c)
defer conn.Close()
res, err = d.indexIconCache(conn, key)
return
}
// IndexIconBakCache get index icon bak cache
func (d *Dao) IndexIconBakCache(c context.Context) (res []*resmdl.IndexIcon, err error) {
d.cacheProm.Incr("indexicon_remote_cache")
key := _indexIconBakKey
conn := d.redisBak.Get(c)
defer conn.Close()
res, err = d.indexIconCache(conn, key)
return
}
func (d *Dao) indexIconCache(conn redis.Conn, key string) (res []*resmdl.IndexIcon, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
if err = json.Unmarshal(value, &res); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
resmdl "go-common/app/service/main/resource/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSetIndexIconCache(t *testing.T) {
convey.Convey("SetIndexIconCache", t, func(ctx convey.C) {
var (
c = context.Background()
data = []*resmdl.IndexIcon{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetIndexIconCache(c, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoIndexIconCache(t *testing.T) {
convey.Convey("IndexIconCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.IndexIconCache(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", res)
})
})
})
}
func TestDaoIndexIconBakCache(t *testing.T) {
convey.Convey("IndexIconBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.IndexIconBakCache(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", res)
})
})
})
}

View File

@@ -0,0 +1,130 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/service/main/archive/api"
"go-common/library/cache/redis"
"go-common/library/log"
"go-common/library/time"
)
const (
// new list
_keyNl = "n_%d_%d"
)
func keyNl(rid int32, tp int8) string {
return fmt.Sprintf(_keyNl, rid, tp)
}
func keyNlBak(rid int32, tp int8) string {
return _keyBakPrefix + keyNl(rid, tp)
}
// NewListCache get region rank list from cache.
func (d *Dao) NewListCache(c context.Context, rid int32, tp int8, start, end int) (arcs []*api.Arc, count int, err error) {
key := keyNl(rid, tp)
conn := d.redis.Get(c)
defer conn.Close()
arcs, count, err = d.nlCache(c, conn, key, start, end)
return
}
// NewListBakCache get region rank list from bak cache.
func (d *Dao) NewListBakCache(c context.Context, rid int32, tp int8, start, end int) (arcs []*api.Arc, count int, err error) {
d.cacheProm.Incr("newlist_remote_cache")
key := keyNlBak(rid, tp)
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, count, err = d.nlCache(c, conn, key, start, end)
if len(arcs) == 0 {
log.Error("NewlistBakCache(%s,%d,%d) is nil", key, start, end)
}
return
}
func (d *Dao) nlCache(c context.Context, conn redis.Conn, key string, start, end int) (arcs []*api.Arc, count int, err error) {
values, err := redis.Values(conn.Do("ZREVRANGE", key, start, end, "WITHSCORES"))
if err != nil {
log.Error("conn.Do(ZREVRANGE, %s) error(%v)", key, err)
return
}
if len(values) == 0 {
return
}
var num int64
for len(values) > 0 {
bs := []byte{}
if values, err = redis.Scan(values, &bs, &num); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
arc := &api.Arc{}
if err = json.Unmarshal(bs, arc); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", bs, err)
return
}
arcs = append(arcs, arc)
}
count = from(num)
return
}
// SetNewListCache set region cache.
func (d *Dao) SetNewListCache(c context.Context, rid int32, tp int8, arcs []*api.Arc, count int) (err error) {
key := keyNl(rid, tp)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setNlCache(c, conn, key, d.redisNlExpire, arcs, count); err != nil {
return
}
key = keyNlBak(rid, tp)
connBak := d.redisBak.Get(c)
err = d.setNlCache(c, connBak, key, d.redisNlBakExpire, arcs, count)
connBak.Close()
return
}
func (d *Dao) setNlCache(c context.Context, conn redis.Conn, key string, expire int32, arcs []*api.Arc, num int) (err error) {
count := 0
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
count++
for _, arc := range arcs {
bs, _ := json.Marshal(arc)
if err = conn.Send("ZADD", key, combine(arc.PubDate, num), bs); err != nil {
log.Error("conn.Send(ZADD, %s, %s) error(%v)", key, string(bs), err)
return
}
count++
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
count++
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < count; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
func from(i int64) int {
return int(i & 0xffffff)
}
func combine(pubdate time.Time, count int) int64 {
return pubdate.Time().Unix()<<24 | int64(count)
}

View File

@@ -0,0 +1,129 @@
package dao
import (
"context"
"testing"
xtime "time"
"go-common/app/service/main/archive/api"
"go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyNl(t *testing.T) {
convey.Convey("keyNl", t, func(ctx convey.C) {
var (
rid = int32(0)
tp = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyNl(rid, tp)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyNlBak(t *testing.T) {
convey.Convey("keyNlBak", t, func(ctx convey.C) {
var (
rid = int32(0)
tp = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyNlBak(rid, tp)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoNewListCache(t *testing.T) {
convey.Convey("NewListCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int32(0)
tp = int8(0)
start = int(0)
end = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, count, err := d.NewListCache(c, rid, tp, start, end)
ctx.Convey("Then err should be nil.arcs,count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoNewListBakCache(t *testing.T) {
convey.Convey("NewListBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int32(0)
tp = int8(0)
start = int(0)
end = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, count, err := d.NewListBakCache(c, rid, tp, start, end)
ctx.Convey("Then err should be nil.arcs,count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoSetNewListCache(t *testing.T) {
convey.Convey("SetNewListCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int32(0)
tp = int8(0)
arcs = []*api.Arc{}
count = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetNewListCache(c, rid, tp, arcs, count)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaofrom(t *testing.T) {
convey.Convey("from", t, func(ctx convey.C) {
var (
i = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := from(i)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocombine(t *testing.T) {
convey.Convey("combine", t, func(ctx convey.C) {
var (
pubdate = time.Time(xtime.Now().Unix())
count = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := combine(pubdate, count)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,81 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
// OnlineCount get online count
func (d *Dao) OnlineCount(c context.Context) (data *model.OnlineCount, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
var res struct {
Code int `json:"code"`
Data *model.OnlineCount `json:"data"`
}
if err = d.httpR.Get(c, d.onlineURL, ip, params, &res); err != nil {
log.Error(" d.httpW.Get.Get(%s) error(%v)", d.onlineURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpW.Get(%s) code error(%d)", d.onlineURL, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Data
return
}
// LiveOnlineCount get live online count
func (d *Dao) LiveOnlineCount(c context.Context) (data *model.LiveOnlineCount, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
var res struct {
Code int `json:"code"`
Data *model.LiveOnlineCount `json:"data"`
}
if err = d.httpR.Get(c, d.liveOnlineURL, ip, params, &res); err != nil {
log.Error(" d.httpW.Get.Get(%s) error(%v)", d.liveOnlineURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpW.Get(%s) code error(%d)", d.liveOnlineURL, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Data
return
}
// OnlineList get online list
func (d *Dao) OnlineList(c context.Context, num int64) (data []*model.OnlineAid, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("num", strconv.FormatInt(num, 10))
var res struct {
Code int `json:"code"`
Data []*model.OnlineAid `json:"data"`
}
if err = d.httpR.Get(c, d.onlineListURL, ip, params, &res); err != nil {
log.Error(" d.httpR.Get.Get(%s) error(%v)", d.onlineListURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s) code error(%d)", d.onlineListURL, res.Code)
return
}
data = res.Data
return
}

View File

@@ -0,0 +1,61 @@
package dao
import (
"context"
"encoding/json"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const _onlineListKey = "olk"
// OnlineListBakCache get online list bak cache.
func (d *Dao) OnlineListBakCache(c context.Context) (rs []*model.OnlineArc, err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
var values []byte
if values, err = redis.Bytes(conn.Do("GET", _onlineListKey)); err != nil {
if err == redis.ErrNil {
err = nil
log.Warn("OnlineListBakCache redis (%s) return nil ", _onlineListKey)
} else {
log.Error("OnlineListBakCache conn.Do(GET,%s) error(%v)", _onlineListKey, err)
}
return
}
if err = json.Unmarshal(values, &rs); err != nil {
log.Error("OnlineListBakCache json.Unmarshal(%v) error(%v)", values, err)
}
return
}
// SetOnlineListBakCache set online list bak cache.
func (d *Dao) SetOnlineListBakCache(c context.Context, data []*model.OnlineArc) (err error) {
conn := d.redisBak.Get(c)
defer conn.Close()
var bs []byte
if bs, err = json.Marshal(data); err != nil {
log.Error("SetOnlineListBakCache json.Marshal(%v) error(%v)", data, err)
return
}
if err = conn.Send("SET", _onlineListKey, bs); err != nil {
log.Error("SetOnlineListBakCache conn.Send(SET,%s,%s) error(%v)", _onlineListKey, string(bs), err)
return
}
if err = conn.Send("EXPIRE", _onlineListKey, d.redisOlListBakExpire); err != nil {
log.Error("SetOnlineListBakCache conn.Send(EXPIRE,%s,%d) error(%v)", _onlineListKey, d.redisOlListBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("SetOnlineListBakCache conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("SetOnlineListBakCache conn.Recevie(%d) error(%v0", i, err)
}
}
return
}

View File

@@ -0,0 +1,40 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSetOnlineListBakCache(t *testing.T) {
convey.Convey("SetOnlineListBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
data = []*model.OnlineArc{{OnlineCount: 111}, {OnlineCount: 222}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetOnlineListBakCache(c, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoOnlineListBakCache(t *testing.T) {
convey.Convey("OnlineListBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.OnlineListBakCache(c)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoOnlineCount(t *testing.T) {
convey.Convey("OnlineCount", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.OnlineCount(c)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLiveOnlineCount(t *testing.T) {
convey.Convey("LiveOnlineCount", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.LiveOnlineCount(c)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOnlineList(t *testing.T) {
convey.Convey("OnlineList", t, func(ctx convey.C) {
var (
c = context.Background()
num = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.OnlineList(c, num)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,113 @@
package dao
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// Wallet get user bcoin doc:http://info.bilibili.co/pages/viewpage.action?pageId=7559096
func (d *Dao) Wallet(c context.Context, mid int64) (wallet *model.Wallet, err error) {
const (
plat = 3
platStr = "3"
customID = "10008"
)
params := url.Values{}
params.Set("customerId", customID)
params.Set("platformType", platStr)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("traceId", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("timestamp", strconv.FormatInt(time.Now().UnixNano()/1000, 10))
params.Set("signType", "MD5")
params.Set("appkey", d.c.HTTPClient.Pay.Key)
type pJSON struct {
CustomerID string `json:"customerId"`
PlatformType int `json:"platformType"`
Mid int64 `json:"mid"`
TraceID string `json:"traceId"`
Timestamp string `json:"timestamp"`
SignType string `json:"signType"`
Appkey string `json:"appkey"`
Sign string `json:"sign"`
}
tmp := params.Encode() + d.c.HTTPClient.Pay.Secret
if strings.IndexByte(tmp, '+') > -1 {
tmp = strings.Replace(tmp, "+", "%20", -1)
}
mh := md5.Sum([]byte(tmp))
sign := hex.EncodeToString(mh[:])
p := &pJSON{
CustomerID: customID,
PlatformType: plat,
Mid: mid,
TraceID: params.Get("traceId"),
Timestamp: params.Get("timestamp"),
SignType: params.Get("signType"),
Appkey: params.Get("appkey"),
Sign: sign,
}
bs, _ := json.Marshal(p)
req, _ := http.NewRequest("POST", d.walletURL, strings.NewReader(string(bs)))
req.Header.Set("Content-Type", "application/json")
var res struct {
Code int `json:"code"`
Data struct {
// DefaultBp float32 `json:"defaultBp"`
CouponBalance float32 `json:"couponBalance"`
AvailableBp float32 `json:"availableBp"`
} `json:"data"`
}
if err = d.httpPay.Do(c, req, &res); err != nil {
return
}
if res.Code != 0 {
err = errors.Wrap(ecode.Int(res.Code), d.walletURL+"?"+params.Encode())
log.Error("account pay url(%s) error(%v)", d.walletURL+"?"+params.Encode(), res.Code)
return
}
wallet = &model.Wallet{
Mid: mid,
BcoinBalance: res.Data.AvailableBp,
CouponBalance: res.Data.CouponBalance,
}
return
}
// OldWallet get wallet info
func (d *Dao) OldWallet(c context.Context, mid int64) (w *model.Wallet, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data *model.Wallet `json:"data"`
}
err = d.httpR.Get(c, d.walletOldURL, remoteIP, params, &res)
if err != nil {
log.Error("account pay url(%s) error(%v)", d.walletOldURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("account pay url(%s) error(%v)", d.walletOldURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
w = res.Data
return
}

View File

@@ -0,0 +1,40 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoWallet(t *testing.T) {
convey.Convey("Wallet", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
wallet, err := d.Wallet(c, mid)
ctx.Convey("Then err should be nil.wallet should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(wallet, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOldWallet(t *testing.T) {
convey.Convey("OldWallet", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
w, err := d.OldWallet(c, mid)
ctx.Convey("Then err should be nil.w should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(w, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,500 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyRkFmt = "r_v2_%d_%d_%d_%d"
_keyRkIndexFmt = "ri_%d"
_keyRkRegionFmt = "rc_%d_%d_%d"
_keyRkRecommendFmt = "rr_%d"
_keyRkTagFmt = "rt_%d_%d"
_keyRegionCustom = "krc"
_keyRegionCustomBak = _keyBakPrefix + _keyRegionCustom
_keyBakPrefix = "b_"
)
func keyRkList(rid int16, rankType, day, arcType int) string {
return fmt.Sprintf(_keyRkFmt, rid, rankType, day, arcType)
}
func keyRkListBak(rid int16, rankType, day, arcType int) string {
return _keyBakPrefix + keyRkList(rid, rankType, day, arcType)
}
func keyRkIndex(day int) string {
return fmt.Sprintf(_keyRkIndexFmt, day)
}
func keyRkIndexBak(day int) string {
return _keyBakPrefix + keyRkIndex(day)
}
func keyRkRegionList(rid int16, day, original int) string {
return fmt.Sprintf(_keyRkRegionFmt, rid, day, original)
}
func keyRkRegionListBak(rid int16, day, original int) string {
return _keyBakPrefix + keyRkRegionList(rid, day, original)
}
func keyRkRecommendList(rid int16) string {
return fmt.Sprintf(_keyRkRecommendFmt, rid)
}
func keyRkRecommendListBak(rid int16) string {
return _keyBakPrefix + fmt.Sprintf(_keyRkRecommendFmt, rid)
}
func keyRkTagList(rid int16, tagID int64) string {
return fmt.Sprintf(_keyRkTagFmt, rid, tagID)
}
func keyRkTagListBak(rid int16, tagID int64) string {
return _keyBakPrefix + keyRkTagList(rid, tagID)
}
// RankingCache get rank list from cache.
func (d *Dao) RankingCache(c context.Context, rid int16, rankType, day, arcType int) (data *model.RankData, err error) {
key := keyRkList(rid, rankType, day, arcType)
conn := d.redis.Get(c)
defer conn.Close()
data, err = d.rankingCache(conn, key)
return
}
// RankingBakCache get rank list from bak cache.
func (d *Dao) RankingBakCache(c context.Context, rid int16, rankType, day, arcType int) (data *model.RankData, err error) {
d.cacheProm.Incr("ranking_remote_cache")
key := keyRkListBak(rid, rankType, day, arcType)
conn := d.redisBak.Get(c)
defer conn.Close()
data, err = d.rankingCache(conn, key)
if data == nil || len(data.List) == 0 {
log.Error("RankingBakCache(%s) is nil", key)
}
return
}
// RankingIndexCache get rank index from cache.
func (d *Dao) RankingIndexCache(c context.Context, day int) (arcs []*model.IndexArchive, err error) {
key := keyRkIndex(day)
conn := d.redis.Get(c)
defer conn.Close()
arcs, err = d.rankingIndexCache(conn, key)
return
}
// RankingIndexBakCache get rank index from bak cache.
func (d *Dao) RankingIndexBakCache(c context.Context, day int) (arcs []*model.IndexArchive, err error) {
d.cacheProm.Incr("ranking_index_remote_cache")
key := keyRkIndexBak(day)
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, err = d.rankingIndexCache(conn, key)
if len(arcs) == 0 {
log.Error("RankingIndexBakCache(%s) is nil", key)
}
return
}
// RankingRegionCache get rank cate list from cache.
func (d *Dao) RankingRegionCache(c context.Context, rid int16, day, original int) (arcs []*model.RegionArchive, err error) {
key := keyRkRegionList(rid, day, original)
conn := d.redis.Get(c)
defer conn.Close()
arcs, err = d.rankingRegionCache(conn, key)
return
}
// RankingRegionBakCache get rank cate list from bak cache.
func (d *Dao) RankingRegionBakCache(c context.Context, rid int16, day, original int) (arcs []*model.RegionArchive, err error) {
d.cacheProm.Incr("ranking_region_remote_cache")
key := keyRkRegionListBak(rid, day, original)
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, err = d.rankingRegionCache(conn, key)
if len(arcs) == 0 {
log.Error("RankingRegionBakCache(%s) is nil", key)
}
return
}
// RankingRecommendCache get rank recommend list from cache.
func (d *Dao) RankingRecommendCache(c context.Context, rid int16) (arcs []*model.IndexArchive, err error) {
key := keyRkRecommendList(rid)
conn := d.redis.Get(c)
defer conn.Close()
arcs, err = d.rankingIndexCache(conn, key)
return
}
// RankingRecommendBakCache get rank recommend list from bak cache.
func (d *Dao) RankingRecommendBakCache(c context.Context, rid int16) (arcs []*model.IndexArchive, err error) {
d.cacheProm.Incr("ranking_rec_remote_cache")
key := keyRkRecommendListBak(rid)
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, err = d.rankingIndexCache(conn, key)
if len(arcs) == 0 {
log.Error("RankingRecommendBakCache(%s) is nil", key)
}
return
}
// RankingTagCache get ranking tag from cache.
func (d *Dao) RankingTagCache(c context.Context, rid int16, tagID int64) (arcs []*model.TagArchive, err error) {
key := keyRkTagList(rid, tagID)
conn := d.redis.Get(c)
defer conn.Close()
arcs, err = d.rankingTagCache(conn, key)
return
}
// RankingTagBakCache get ranking tag from bak cache.
func (d *Dao) RankingTagBakCache(c context.Context, rid int16, tagID int64) (arcs []*model.TagArchive, err error) {
d.cacheProm.Incr("ranking_tag_remote_cache")
key := keyRkTagListBak(rid, tagID)
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, err = d.rankingTagCache(conn, key)
if len(arcs) == 0 {
log.Error("RankingTagBakCache(%s) is nil", key)
}
return
}
// RegionCustomCache get region custom data from cache
func (d *Dao) RegionCustomCache(c context.Context) (res []*model.Custom, err error) {
key := _keyRegionCustom
conn := d.redis.Get(c)
defer conn.Close()
res, err = regionCustomCache(conn, key)
return
}
// RegionCustomBakCache get region custom data from cache
func (d *Dao) RegionCustomBakCache(c context.Context) (res []*model.Custom, err error) {
key := _keyRegionCustomBak
conn := d.redis.Get(c)
defer conn.Close()
res, err = regionCustomCache(conn, key)
return
}
func regionCustomCache(conn redis.Conn, key string) (res []*model.Custom, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
res = []*model.Custom{}
if err = json.Unmarshal(value, &res); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetRegionCustomCache set region custom data cache
func (d *Dao) SetRegionCustomCache(c context.Context, data []*model.Custom) (err error) {
key := _keyRegionCustom
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRegionCustomCache(conn, key, d.redisRcExpire, data); err != nil {
return
}
key = _keyRegionCustomBak
connBak := d.redisBak.Get(c)
err = d.setRegionCustomCache(connBak, key, d.redisRcBakExpire, data)
connBak.Close()
return
}
func (d *Dao) setRegionCustomCache(conn redis.Conn, key string, expire int32, data []*model.Custom) (err error) {
var bs []byte
if bs, err = json.Marshal(data); err != nil {
log.Error("json.Marshal(%v) error (%v)", data, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisRkExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisRkExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
func (d *Dao) rankingCache(conn redis.Conn, key string) (arcs *model.RankData, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
arcs = new(model.RankData)
if err = json.Unmarshal(value, &arcs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
func (d *Dao) rankingIndexCache(conn redis.Conn, key string) (arcs []*model.IndexArchive, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
arcs = []*model.IndexArchive{}
if err = json.Unmarshal(value, &arcs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
func (d *Dao) rankingRegionCache(conn redis.Conn, key string) (arcs []*model.RegionArchive, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
arcs = []*model.RegionArchive{}
if err = json.Unmarshal(value, &arcs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
func (d *Dao) rankingTagCache(conn redis.Conn, key string) (arcs []*model.TagArchive, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
arcs = []*model.TagArchive{}
if err = json.Unmarshal(value, &arcs); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetRankingCache set ranking data to cache
func (d *Dao) SetRankingCache(c context.Context, rid int16, rankType, day, arcType int, data *model.RankData) (err error) {
key := keyRkList(rid, rankType, day, arcType)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRkCache(c, conn, key, d.redisRkExpire, data); err != nil {
return
}
key = keyRkListBak(rid, rankType, day, arcType)
connBak := d.redisBak.Get(c)
err = d.setRkCache(c, connBak, key, d.redisRkBakExpire, data)
connBak.Close()
return
}
// SetRankingIndexCache set ranking index data to cache
func (d *Dao) SetRankingIndexCache(c context.Context, day int, arcs []*model.IndexArchive) (err error) {
key := keyRkIndex(day)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRkIndexCache(c, conn, key, d.redisRkExpire, arcs); err != nil {
return
}
key = keyRkIndexBak(day)
connBak := d.redisBak.Get(c)
err = d.setRkIndexCache(c, connBak, key, d.redisRkBakExpire, arcs)
connBak.Close()
return
}
// SetRankingRegionCache set ranking data to cache
func (d *Dao) SetRankingRegionCache(c context.Context, rid int16, day, original int, arcs []*model.RegionArchive) (err error) {
key := keyRkRegionList(rid, day, original)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRkRegionCache(c, conn, key, d.redisRkExpire, arcs); err != nil {
return
}
key = keyRkRegionListBak(rid, day, original)
connBak := d.redisBak.Get(c)
err = d.setRkRegionCache(c, connBak, key, d.redisRkBakExpire, arcs)
connBak.Close()
return
}
// SetRankingRecommendCache set ranking data to bak cache
func (d *Dao) SetRankingRecommendCache(c context.Context, rid int16, arcs []*model.IndexArchive) (err error) {
key := keyRkRecommendList(rid)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRkIndexCache(c, conn, key, d.redisRkExpire, arcs); err != nil {
return
}
key = keyRkRecommendListBak(rid)
connBak := d.redisBak.Get(c)
err = d.setRkIndexCache(c, connBak, key, d.redisRkBakExpire, arcs)
connBak.Close()
return
}
// SetRankingTagCache set ranking tag data to cache
func (d *Dao) SetRankingTagCache(c context.Context, rid int16, tagID int64, arcs []*model.TagArchive) (err error) {
key := keyRkTagList(rid, tagID)
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setRkTagCache(c, conn, key, d.redisRkExpire, arcs); err != nil {
return
}
key = keyRkTagListBak(rid, tagID)
connBak := d.redisBak.Get(c)
err = d.setRkTagCache(c, connBak, key, d.redisRkBakExpire, arcs)
connBak.Close()
return
}
func (d *Dao) setRkCache(c context.Context, conn redis.Conn, key string, expire int32, arcs *model.RankData) (err error) {
var bs []byte
if bs, err = json.Marshal(arcs); err != nil {
log.Error("json.Marshal(%v) error (%v)", arcs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
func (d *Dao) setRkIndexCache(c context.Context, conn redis.Conn, key string, expire int32, arcs []*model.IndexArchive) (err error) {
var bs []byte
if bs, err = json.Marshal(arcs); err != nil {
log.Error("json.Marshal(%v) error (%v)", arcs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
func (d *Dao) setRkRegionCache(c context.Context, conn redis.Conn, key string, expire int32, arcs []*model.RegionArchive) (err error) {
var bs []byte
if bs, err = json.Marshal(arcs); err != nil {
log.Error("json.Marshal(%v) error (%v)", arcs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
func (d *Dao) setRkTagCache(c context.Context, conn redis.Conn, key string, expire int32, arcs []*model.TagArchive) (err error) {
var bs []byte
if bs, err = json.Marshal(arcs); err != nil {
log.Error("json.Marshal(%v) error (%v)", arcs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,465 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyRkList(t *testing.T) {
convey.Convey("keyRkList", t, func(ctx convey.C) {
var (
rid = int16(1)
rankType = int(0)
day = int(1)
arcType = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkList(rid, rankType, day, arcType)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkListBak(t *testing.T) {
convey.Convey("keyRkListBak", t, func(ctx convey.C) {
var (
rid = int16(0)
rankType = int(0)
day = int(0)
arcType = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkListBak(rid, rankType, day, arcType)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkIndex(t *testing.T) {
convey.Convey("keyRkIndex", t, func(ctx convey.C) {
var (
day = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkIndex(day)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkIndexBak(t *testing.T) {
convey.Convey("keyRkIndexBak", t, func(ctx convey.C) {
var (
day = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkIndexBak(day)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkRegionList(t *testing.T) {
convey.Convey("keyRkRegionList", t, func(ctx convey.C) {
var (
rid = int16(1)
day = int(3)
original = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkRegionList(rid, day, original)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkRegionListBak(t *testing.T) {
convey.Convey("keyRkRegionListBak", t, func(ctx convey.C) {
var (
rid = int16(1)
day = int(3)
original = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkRegionListBak(rid, day, original)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkRecommendList(t *testing.T) {
convey.Convey("keyRkRecommendList", t, func(ctx convey.C) {
var (
rid = int16(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkRecommendList(rid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkRecommendListBak(t *testing.T) {
convey.Convey("keyRkRecommendListBak", t, func(ctx convey.C) {
var (
rid = int16(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkRecommendListBak(rid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkTagList(t *testing.T) {
convey.Convey("keyRkTagList", t, func(ctx convey.C) {
var (
rid = int16(1)
tagID = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkTagList(rid, tagID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyRkTagListBak(t *testing.T) {
convey.Convey("keyRkTagListBak", t, func(ctx convey.C) {
var (
rid = int16(1)
tagID = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyRkTagListBak(rid, tagID)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRankingCache(t *testing.T) {
convey.Convey("RankingCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(1)
rankType = int(1)
day = int(3)
arcType = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.RankingCache(c, rid, rankType, day, arcType)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaoRankingBakCache(t *testing.T) {
convey.Convey("RankingBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(1)
rankType = int(1)
day = int(3)
arcType = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.RankingBakCache(c, rid, rankType, day, arcType)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaoRankingIndexCache(t *testing.T) {
convey.Convey("RankingIndexCache", t, func(ctx convey.C) {
var (
c = context.Background()
day = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingIndexCache(c, day)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingIndexBakCache(t *testing.T) {
convey.Convey("RankingIndexBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
day = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingIndexBakCache(c, day)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingRegionCache(t *testing.T) {
convey.Convey("RankingRegionCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(1)
day = int(3)
original = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingRegionCache(c, rid, day, original)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingRegionBakCache(t *testing.T) {
convey.Convey("RankingRegionBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(1)
day = int(3)
original = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingRegionBakCache(c, rid, day, original)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingRecommendCache(t *testing.T) {
convey.Convey("RankingRecommendCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingRecommendCache(c, rid)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingRecommendBakCache(t *testing.T) {
convey.Convey("RankingRecommendBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingRecommendBakCache(c, rid)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingTagCache(t *testing.T) {
convey.Convey("RankingTagCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
tagID = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingTagCache(c, rid, tagID)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoRankingTagBakCache(t *testing.T) {
convey.Convey("RankingTagBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
tagID = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.RankingTagBakCache(c, rid, tagID)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoSetRegionCustomCache(t *testing.T) {
convey.Convey("SetRegionCustomCache", t, func(ctx convey.C) {
var (
c = context.Background()
data = []*model.Custom{{Aid: 1111}, {Aid: 2222}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRegionCustomCache(c, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoRegionCustomCache(t *testing.T) {
convey.Convey("RegionCustomCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RegionCustomCache(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRegionCustomBakCache(t *testing.T) {
convey.Convey("RegionCustomBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RegionCustomBakCache(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetRankingCache(t *testing.T) {
convey.Convey("SetRankingCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
rankType = int(0)
day = int(0)
arcType = int(0)
data = &model.RankData{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRankingCache(c, rid, rankType, day, arcType, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetRankingIndexCache(t *testing.T) {
convey.Convey("SetRankingIndexCache", t, func(ctx convey.C) {
var (
c = context.Background()
day = int(0)
arcs = []*model.IndexArchive{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRankingIndexCache(c, day, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetRankingRegionCache(t *testing.T) {
convey.Convey("SetRankingRegionCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
day = int(0)
original = int(0)
arcs = []*model.RegionArchive{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRankingRegionCache(c, rid, day, original, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetRankingRecommendCache(t *testing.T) {
convey.Convey("SetRankingRecommendCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
arcs = []*model.IndexArchive{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRankingRecommendCache(c, rid, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetRankingTagCache(t *testing.T) {
convey.Convey("SetRankingTagCache", t, func(ctx convey.C) {
var (
c = context.Background()
rid = int16(0)
tagID = int64(0)
arcs = []*model.TagArchive{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetRankingTagCache(c, rid, tagID, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_hotURI = "/x/internal/v2/reply/hot"
_archiveType = 1
)
// Hot reply hot.
func (d *Dao) Hot(c context.Context, aid int64) (rs *model.ReplyHot, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
params.Set("oid", strconv.FormatInt(aid, 10))
params.Set("type", strconv.FormatInt(_archiveType, 10))
var res struct {
Code int `json:"code"`
Data *model.ReplyHot `json:"data"`
}
if err = d.httpR.Get(c, d.replyHotURL, remoteIP, params, &res); err != nil {
err = errors.Wrapf(err, "replyHot url(%s)", d.replyHotURL+"?"+params.Encode())
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
return
}
rs = &model.ReplyHot{Replies: res.Data.Replies, Page: res.Data.Page}
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoHot(t *testing.T) {
convey.Convey("Hot", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(10100652)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.Hot(c, aid)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,568 @@
package dao
import (
"context"
"net/http"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/xstr"
)
const (
_searchVer = "v3"
_searchPlatform = "web"
_searchUpRecType = "up_rec"
)
// SearchAll search all data.
func (d *Dao) SearchAll(c context.Context, mid int64, arg *model.SearchAllArg, buvid, ua, typ string) (res *model.Search, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchParam(params, mid, model.SearchTypeAll, arg.Keyword, _searchPlatform, arg.FromSource, buvid, ip)
params.Set("duration", strconv.Itoa(arg.Duration))
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("tids", strconv.Itoa(arg.Rid))
if typ == model.WxSearchType {
params.Set("highlight", strconv.Itoa(arg.Highlight))
for k, v := range model.SearchDefaultArg[model.WxSearchTypeAll] {
params.Set(k, strconv.Itoa(v))
}
} else {
for k, v := range model.SearchDefaultArg[model.SearchTypeAll] {
params.Set(k, strconv.Itoa(v))
}
params.Set("single_column", strconv.Itoa(arg.SingleColumn))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.Search)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("Search d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("Search d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchVideo search season data.
func (d *Dao) SearchVideo(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeVideo, buvid, ip, arg)
params.Set("duration", strconv.Itoa(arg.Duration))
params.Set("order", arg.Order)
params.Set("from_source", arg.FromSource)
params.Set("tids", strconv.FormatInt(arg.Rid, 10))
params.Set("page", strconv.Itoa(arg.Pn))
for k, v := range model.SearchDefaultArg[model.SearchTypeVideo] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchVideo d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchVideo d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchBangumi search bangumi data.
func (d *Dao) SearchBangumi(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeBangumi, buvid, ip, arg)
params.Set("duration", strconv.Itoa(arg.Duration))
params.Set("order", arg.Order)
params.Set("page", strconv.Itoa(arg.Pn))
for k, v := range model.SearchDefaultArg[model.SearchTypeBangumi] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchBangumi d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchBangumi d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchPGC search pgc(movie) data.
func (d *Dao) SearchPGC(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypePGC, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
for k, v := range model.SearchDefaultArg[model.SearchTypePGC] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchPGC d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchPGC d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchLive search live data.
func (d *Dao) SearchLive(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeLive, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypeLive] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchVideo d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchVideo d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchLiveRoom search live data.
func (d *Dao) SearchLiveRoom(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeLiveRoom, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypeLiveRoom] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchLiveRoom d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchLiveRoom d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchLiveUser search live user data.
func (d *Dao) SearchLiveUser(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeLiveUser, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypeLiveUser] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchVideo d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchVideo d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchArticle search article.
func (d *Dao) SearchArticle(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeArticle, buvid, ip, arg)
params.Set("category_id", strconv.FormatInt(arg.CategoryID, 10))
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypeArticle] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchArticle d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchArticle d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchSpecial search special data.
func (d *Dao) SearchSpecial(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeSpecial, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("vp_num", strconv.Itoa(arg.VpNum))
for k, v := range model.SearchDefaultArg[model.SearchTypeSpecial] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchSpecial d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchSpecial d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchTopic search topic data.
func (d *Dao) SearchTopic(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeTopic, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
for k, v := range model.SearchDefaultArg[model.SearchTypeTopic] {
params.Set(k, strconv.Itoa(v))
}
if arg.Highlight > 0 {
params.Set("highlight", strconv.Itoa(arg.Highlight))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchVideo d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchVideo d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchUser search user data.
func (d *Dao) SearchUser(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypeUser, buvid, ip, arg)
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("user_type", strconv.Itoa(arg.UserType))
params.Set("bili_user_vl", strconv.Itoa(arg.BiliUserVl))
params.Set("order_sort", strconv.Itoa(arg.OrderSort))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypeUser] {
params.Set(k, strconv.Itoa(v))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchUser d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchUser d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchPhoto search photo data.
func (d *Dao) SearchPhoto(c context.Context, mid int64, arg *model.SearchTypeArg, buvid, ua string) (res *model.SearchTypeRes, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchTypeParam(params, mid, model.SearchTypePhoto, buvid, ip, arg)
params.Set("category_id", strconv.FormatInt(arg.CategoryID, 10))
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("order", arg.Order)
for k, v := range model.SearchDefaultArg[model.SearchTypePhoto] {
params.Set(k, strconv.Itoa(v))
}
if arg.Highlight > 0 {
params.Set("highlight", strconv.Itoa(arg.Highlight))
}
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchTypeRes)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("SearchPhoto d.httpSearch.Get(%s) error(%v)", d.searchURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchPhoto d.httpSearch.Get(%s) code(%d) error", d.searchURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchRec search recommend data.
func (d *Dao) SearchRec(c context.Context, mid int64, pn, ps int, keyword, fromSource, buvid, ua string) (res *model.SearchRec, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params = setSearchParam(params, mid, "", keyword, _searchPlatform, fromSource, buvid, ip)
params.Set("page", strconv.Itoa(pn))
params.Set("pagesize", strconv.Itoa(ps))
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchRecURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
res = new(model.SearchRec)
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("Search d.httpSearch.Get(%s) error(%v)", d.searchRecURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("Search d.httpSearch.Do(%s) code error(%d)", d.searchRecURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// SearchDefault get search default word.
func (d *Dao) SearchDefault(c context.Context, mid int64, fromSource, buvid, ua string) (data *model.SearchDefault, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("main_ver", _searchVer)
params.Set("platform", _searchPlatform)
params.Set("clientip", ip)
params.Set("userid", strconv.FormatInt(mid, 10))
params.Set("search_type", "default")
params.Set("from_source", fromSource)
params.Set("buvid", buvid)
var req *http.Request
if req, err = d.httpSearch.NewRequest(http.MethodGet, d.searchDefaultURL, ip, params); err != nil {
return
}
req.Header.Set("browser-info", ua)
var res struct {
Code int `json:"code"`
SeID string `json:"seid"`
Tips string `json:"recommend_tips"`
Result []struct {
ID int64 `json:"id"`
Name string `json:"name"`
ShowName string `json:"show_name"`
Type string `json:"type"`
} `json:"result"`
}
if err = d.httpSearch.Do(c, req, &res); err != nil {
log.Error("Search d.httpSearch.Get(%s) error(%v)", d.searchDefaultURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("Search d.httpSearch.Do(%s) code error(%d)", d.searchDefaultURL, res.Code)
err = ecode.Int(res.Code)
}
if len(res.Result) == 0 {
err = ecode.NothingFound
return
}
data = &model.SearchDefault{}
for _, v := range res.Result {
data.Trackid = res.SeID
data.ID = v.ID
data.ShowName = v.ShowName
data.Name = v.Name
}
return
}
// UpRecommend .
func (d *Dao) UpRecommend(c context.Context, mid int64, arg *model.SearchUpRecArg, buvid string) (rs []*model.SearchUpRecRes, trackID string, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("userid", strconv.FormatInt(mid, 10))
params.Set("service_area", arg.ServiceArea)
params.Set("rec_type", _searchUpRecType)
params.Set("platform", arg.Platform)
params.Set("clientip", ip)
params.Set("pagesize", strconv.Itoa(arg.Ps))
params.Set("buvid", buvid)
if arg.MobiApp != "" {
params.Set("mobi_app", arg.MobiApp)
}
if arg.Device != "" {
params.Set("device", arg.Device)
}
if arg.Build != 0 {
params.Set("build", strconv.FormatInt(arg.Build, 10))
}
if arg.ContextID != 0 {
params.Set("context_id", strconv.FormatInt(arg.ContextID, 10))
}
if len(arg.MainTids) > 0 {
params.Set("main_tids", xstr.JoinInts(arg.MainTids))
}
if len(arg.SubTids) > 0 {
params.Set("sub_tids", xstr.JoinInts(arg.SubTids))
}
var res struct {
Code int `json:"code"`
Trackid string `json:"trackid"`
Data []*model.SearchUpRecRes `json:"data"`
}
if err = d.httpSearch.Get(c, d.searchUpRecURL, ip, params, &res); err != nil {
log.Error("UpRecommend d.httpSearch.Get(%s) error(%v)", d.searchUpRecURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("UpRecommend d.httpSearch.Do(%s) code error(%d)", d.searchUpRecURL, res.Code)
err = ecode.Int(res.Code)
return
}
rs = res.Data
trackID = res.Trackid
return
}
// SearchEgg search egg.
func (d *Dao) SearchEgg(c context.Context) (data []*model.SearchEgg, err error) {
var (
ip = metadata.String(c, metadata.RemoteIP)
res struct {
Code int `json:"code"`
Data []*model.SearchEgg `json:"data"`
}
)
if err = d.httpSearch.Get(c, d.searchEggURL, ip, url.Values{}, &res); err != nil {
log.Error("SearchEgg d.httpSearch.Get(%s) error(%v)", d.searchEggURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("SearchEgg d.httpSearch.Do(%s) code error(%d)", d.searchEggURL, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Data
return
}
func setSearchParam(param url.Values, mid int64, searchType, keyword, platform, fromSource, buvid, ip string) url.Values {
param.Set("main_ver", _searchVer)
if searchType != "" {
param.Set("search_type", searchType)
}
param.Set("platform", platform)
param.Set("keyword", keyword)
param.Set("from_source", fromSource)
param.Set("userid", strconv.FormatInt(mid, 10))
param.Set("buvid", buvid)
param.Set("clientip", ip)
return param
}
func setSearchTypeParam(param url.Values, mid int64, searchType, buvid, ip string, arg *model.SearchTypeArg) url.Values {
param.Set("main_ver", _searchVer)
if searchType != "" {
param.Set("search_type", searchType)
}
param.Set("platform", arg.Platform)
param.Set("keyword", arg.Keyword)
param.Set("from_source", arg.FromSource)
param.Set("userid", strconv.FormatInt(mid, 10))
param.Set("single_column", strconv.Itoa(arg.SingleColumn))
param.Set("buvid", buvid)
param.Set("clientip", ip)
return param
}

View File

@@ -0,0 +1,314 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSearchAll(t *testing.T) {
convey.Convey("SearchAll", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchAllArg{Pn: 1, Keyword: "test", Rid: 1}
buvid = ""
ua = ""
)
typ := model.WxSearchType
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchAll(c, mid, arg, buvid, ua, typ)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchVideo(t *testing.T) {
convey.Convey("SearchVideo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeVideo, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchVideo(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchBangumi(t *testing.T) {
convey.Convey("SearchBangumi", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeBangumi, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchBangumi(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchPGC(t *testing.T) {
convey.Convey("SearchPGC", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypePGC, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchPGC(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchLive(t *testing.T) {
convey.Convey("SearchLive", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeLive, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchLive(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchLiveRoom(t *testing.T) {
convey.Convey("SearchLiveRoom", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeLiveRoom, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchLiveRoom(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchLiveUser(t *testing.T) {
convey.Convey("SearchLiveUser", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeLiveUser, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchLiveUser(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchArticle(t *testing.T) {
convey.Convey("SearchArticle", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeArticle, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchArticle(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchSpecial(t *testing.T) {
convey.Convey("SearchSpecial", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeSpecial, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchSpecial(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchTopic(t *testing.T) {
convey.Convey("SearchTopic", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeTopic, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchTopic(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchUser(t *testing.T) {
convey.Convey("SearchUser", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypeUser, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchUser(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchPhoto(t *testing.T) {
convey.Convey("SearchPhoto", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
arg = &model.SearchTypeArg{Pn: 1, SearchType: model.SearchTypePhoto, Keyword: "test"}
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchPhoto(c, mid, arg, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchRec(t *testing.T) {
convey.Convey("SearchRec", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
pn = int(1)
ps = int(10)
keyword = "test"
fromSource = ""
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SearchRec(c, mid, pn, ps, keyword, fromSource, buvid, ua)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSearchDefault(t *testing.T) {
convey.Convey("SearchDefault", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
fromSource = ""
buvid = ""
ua = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.SearchDefault(c, mid, fromSource, buvid, ua)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpRecommend(t *testing.T) {
convey.Convey("UpRecommend", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
arg = &model.SearchUpRecArg{ServiceArea: "reg_ok", Platform: "web"}
buvid = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, trackID, err := d.UpRecommend(c, mid, arg, buvid)
ctx.Convey("Then err should be nil.rs,trackID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(trackID, convey.ShouldNotBeNil)
ctx.Printf("%+v", rs)
})
})
})
}
func TestDaoSearchEgg(t *testing.T) {
convey.Convey("SearchEgg", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.SearchEgg(c)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_shopURI = "/mall-shop/merchant/enter/service/shop/get"
_shopTypePc = "2"
)
// ShopInfo get shop info data.
func (d *Dao) ShopInfo(c context.Context, mid int64) (data *model.ShopInfo, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("type", _shopTypePc)
var res struct {
Code int `json:"code"`
Data *model.ShopInfo `json:"data"`
}
if err = d.httpR.Get(c, d.shopURL, ip, params, &res); err != nil {
err = errors.Wrapf(err, "ShopInfo(%s) mid(%d)", d.shopURL+params.Encode(), mid)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
return
}
data = res.Data
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoShopInfo(t *testing.T) {
convey.Convey("ShopInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515399)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.ShopInfo(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", data)
})
})
})
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
// TopPhoto getTopPhoto from space
func (d *Dao) TopPhoto(c context.Context, mid int64) (space *model.Space, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
model.Space
}
if err = d.httpR.Get(c, d.spaceTopPhotoURL, remoteIP, params, &res); err != nil {
log.Error("TopPhoto space url(%s) error(%v)", d.spaceTopPhotoURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("TopPhoto space url(%s) error(%v)", d.spaceTopPhotoURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
space = &res.Space
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTopPhoto(t *testing.T) {
convey.Convey("TopPhoto", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
space, err := d.TopPhoto(c, mid)
ctx.Convey("Then err should be nil.space should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(space, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,97 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/xstr"
)
const (
_redisTagAv = "t_a_"
_tagFeedURL = "/feed/tag/top"
)
func tagAidKey(tid int64) string {
return _redisTagAv + strconv.FormatInt(tid, 10)
}
// TagAids provides aids via tag
func (d *Dao) TagAids(c context.Context, tid int64) (res []int64, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("tag", strconv.FormatInt(tid, 10))
params.Set("pn", "1")
params.Set("rn", strconv.Itoa(d.c.Tag.PageSize))
params.Set("src", "1") // plat. PC:1, APP:2
rs := &model.TagAids{}
if err = d.httpR.Get(c, d.c.Host.Data+_tagFeedURL, ip, params, rs); err != nil {
log.Error("tag d.httpR.Get(%s, %s, %v) error(%v)", d.c.Host.Data+_tagFeedURL, ip, params, err)
return
}
if rs.Code != ecode.OK.Code() {
err = ecode.Int(rs.Code)
return
}
res = rs.Data
return
}
// TagAidsBakCache gets avids cache
func (d *Dao) TagAidsBakCache(c context.Context, tid int64) (res []int64, err error) {
var (
conn = d.redisBak.Get(c)
key = tagAidKey(tid)
s string
)
defer conn.Close()
if s, err = redis.String(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
if res, err = xstr.SplitInts(s); err != nil {
log.Error("xstr.SplitInts(%s) error(%v)", s, err)
}
return
}
// SetTagAidsBakCache set the avids cache
func (d *Dao) SetTagAidsBakCache(c context.Context, tid int64, aids []int64) (err error) {
var (
conn = d.redisBak.Get(c)
key = tagAidKey(tid)
)
defer conn.Close()
s := xstr.JoinInts(aids)
if err = conn.Send("SET", key, s); err != nil {
log.Error("conn.Do(SET, %s, %s) error(%v)", key, s, err)
return
}
if err = conn.Send("EXPIRE", key, d.redisTagBakExpire); err != nil {
log.Error("conn.Send(EXPIRE, %s, %d) error(%v)", key, d.redisTagBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,73 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestDaotagAidKey(t *testing.T) {
convey.Convey("tagAidKey", t, func(ctx convey.C) {
var (
tid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := tagAidKey(tid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTagAids(t *testing.T) {
convey.Convey("TagAids", t, func(ctx convey.C) {
var (
c = context.Background()
tid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Host.Data+_tagFeedURL).Reply(200).JSON(`{"code":0,"data":[1111,2222],"total":2}`)
res, err := d.TagAids(c, tid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetTagAidsBakCache(t *testing.T) {
convey.Convey("SetTagAidsBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
tid = int64(2222)
aids = []int64{111, 222}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetTagAidsBakCache(c, tid, aids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTagAidsBakCache(t *testing.T) {
convey.Convey("TagAidsBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
tid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.TagAidsBakCache(c, tid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,70 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyArchiveFmt = "va_%d"
)
func keyArchive(aid int64) string {
return fmt.Sprintf(_keyArchiveFmt, aid)
}
// SetViewBakCache set view archive page data to cache.
func (d *Dao) SetViewBakCache(c context.Context, aid int64, a *model.View) (err error) {
key := keyArchive(aid)
conn := d.redisBak.Get(c)
defer conn.Close()
var bs []byte
if bs, err = json.Marshal(a); err != nil {
log.Error("SetViewBakCache json.Marshal(%v) error(%v)", a, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("SetViewBakCache conn.Send(SET,%s,%s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, d.redisArchiveBakExpire); err != nil {
log.Error("SetViewBakCache conn.Send(EXPIRE,%s,%d) error(%v)", key, d.redisArchiveBakExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("SetViewBakCache conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("SetViewBakCache conn.Recevie(%d) error(%v0", i, err)
}
}
return
}
// ViewBakCache get view archive page data from cache.
func (d *Dao) ViewBakCache(c context.Context, aid int64) (rs *model.View, err error) {
key := keyArchive(aid)
conn := d.redisBak.Get(c)
defer conn.Close()
var values []byte
if values, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
log.Warn("ViewBakCache redis (%s) return nil ", key)
} else {
log.Error("ViewBakCache conn.Do(GET,%s) error(%v)", key, err)
}
return
}
if err = json.Unmarshal(values, &rs); err != nil {
log.Error("ViewBakCache json.Unmarshal(%v) error(%v)", values, err)
}
return
}

View File

@@ -0,0 +1,56 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyArchive(t *testing.T) {
convey.Convey("keyArchive", t, func(ctx convey.C) {
var (
aid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyArchive(aid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetViewBakCache(t *testing.T) {
convey.Convey("SetViewBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(0)
a = &model.View{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetViewBakCache(c, aid, a)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoViewBakCache(t *testing.T) {
convey.Convey("ViewBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rs, err := d.ViewBakCache(c, aid)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,120 @@
package dao
import (
"context"
"encoding/json"
"net/url"
"go-common/app/interface/main/web/model"
"go-common/library/cache/redis"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_wxHotURI = "hot-weixin.json"
_wxCacheKey = "wx_hot"
_wxBkCacheKey = _keyBakPrefix + _wxCacheKey
)
// WxHot get wx hot aids.
func (d *Dao) WxHot(c context.Context) (aids []int64, err error) {
ip := metadata.String(c, metadata.RemoteIP)
var res struct {
Code int `json:"code"`
List []*model.NewArchive `json:"list"`
}
if err = d.httpBigData.Get(c, d.wxHotURL, ip, url.Values{}, &res); err != nil {
log.Error("d.httpBigData.Get(%s) error(%v)", d.wxHotURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpBigData.Get(%s) error(%v)", d.wxHotURL, err)
err = ecode.Int(res.Code)
return
}
for _, v := range res.List {
if v.Aid > 0 {
aids = append(aids, v.Aid)
}
}
return
}
// WxHotCache get wx hot cache.
func (d *Dao) WxHotCache(c context.Context) (arcs []*model.WxArchive, err error) {
key := _wxCacheKey
conn := d.redis.Get(c)
defer conn.Close()
arcs, err = wxHotCache(conn, key)
return
}
// WxHotBakCache get wx hot bak cache.
func (d *Dao) WxHotBakCache(c context.Context) (arcs []*model.WxArchive, err error) {
key := _wxBkCacheKey
conn := d.redisBak.Get(c)
defer conn.Close()
arcs, err = wxHotCache(conn, key)
return
}
func wxHotCache(conn redis.Conn, key string) (res []*model.WxArchive, err error) {
var value []byte
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
res = []*model.WxArchive{}
if err = json.Unmarshal(value, &res); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetWxHotCache set wx hot to cache.
func (d *Dao) SetWxHotCache(c context.Context, arcs []*model.WxArchive) (err error) {
key := _wxCacheKey
conn := d.redis.Get(c)
defer conn.Close()
if err = d.setWxHotCache(c, conn, key, d.redisWxHotExpire, arcs); err != nil {
return
}
key = _wxBkCacheKey
connBak := d.redisBak.Get(c)
err = d.setWxHotCache(c, connBak, key, d.redisWxHotBakExpire, arcs)
connBak.Close()
return
}
func (d *Dao) setWxHotCache(c context.Context, conn redis.Conn, key string, expire int32, arcs []*model.WxArchive) (err error) {
var bs []byte
if bs, err = json.Marshal(arcs); err != nil {
log.Error("json.Marshal(%v) error (%v)", arcs, err)
return
}
if err = conn.Send("SET", key, bs); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,73 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/web/model"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoWxHot(t *testing.T) {
convey.Convey("WxHot", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.wxHotURL).Reply(200).JSON(`{"code":0,"list":[{"aid":111,"score":10},{"aid":2222,"score":20}]}`)
aids, err := d.WxHot(c)
ctx.Convey("Then err should be nil.aids should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(aids, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetWxHotCache(t *testing.T) {
convey.Convey("SetWxHotCache", t, func(ctx convey.C) {
var (
c = context.Background()
arcs = []*model.WxArchive{{Aid: 1111}, {Aid: 2222}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetWxHotCache(c, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWxHotCache(t *testing.T) {
convey.Convey("WxHotCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.WxHotCache(c)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoWxHotBakCache(t *testing.T) {
convey.Convey("WxHotBakCache", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.WxHotBakCache(c)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}

View File

@@ -0,0 +1,71 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"archive.go",
"article.go",
"bnj.go",
"broadcast.go",
"coin.go",
"dynamic.go",
"elec.go",
"feedback.go",
"help.go",
"http.go",
"icon.go",
"ip.go",
"like.go",
"nav.go",
"newlist.go",
"online.go",
"ranking.go",
"resource.go",
"search.go",
"tag.go",
"wechat.go",
],
importpath = "go-common/app/interface/main/web/http",
tags = ["automanaged"],
deps = [
"//app/interface/main/web/conf:go_default_library",
"//app/interface/main/web/model:go_default_library",
"//app/interface/main/web/service:go_default_library",
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/log/infoc:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/cache:go_default_library",
"//library/net/http/blademaster/middleware/cache/store:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/xstr:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)

View File

@@ -0,0 +1,29 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func attentions(c *bm.Context) {
var mid int64
midStr, _ := c.Get("mid")
mid = midStr.(int64)
c.JSON(webSvc.Attentions(c, mid))
}
func card(c *bm.Context) {
var loginID int64
v := new(struct {
Mid int64 `form:"mid" validate:"min=1"`
TopPhoto bool `form:"photo"`
Article bool `form:"article"`
})
if err := c.Bind(v); err != nil {
return
}
// login mid
if loginIDStr, ok := c.Get("mid"); ok {
loginID = loginIDStr.(int64)
}
c.JSON(webSvc.Card(c, v.Mid, loginID, v.TopPhoto, v.Article))
}

View File

@@ -0,0 +1,240 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
const (
_buvid = "buvid3"
)
func view(c *bm.Context) {
var (
aid, mid, cid int64
cookieStr string
err error
rs *model.View
)
cookieStr = c.Request.Header.Get("Cookie")
aidStr := c.Request.Form.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
// get mid
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
cidStr := c.Request.Form.Get("cid")
if cidStr != "" {
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
cdnIP := c.Request.Header.Get("X-Cache-Server-Addr")
if rs, err = webSvc.View(c, aid, cid, mid, cdnIP, cookieStr); err != nil {
c.JSON(nil, err)
return
}
c.JSON(rs, nil)
}
func archiveStat(c *bm.Context) {
var (
aid int64
err error
)
aidStr := c.Request.Form.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.ArchiveStat(c, aid))
}
func addShare(c *bm.Context) {
var (
aid, mid int64
err error
buvid, sid string
)
aidStr := c.Request.Form.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
// get mid
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if bdCookie, _ := c.Request.Cookie(_buvid); bdCookie != nil {
buvid = bdCookie.Value
}
if sidCookie, _ := c.Request.Cookie("sid"); sidCookie != nil {
sid = sidCookie.Value
}
c.JSON(webSvc.AddShare(c, aid, mid, c.Request.UserAgent(), c.Request.Referer(), c.Request.URL.Path, buvid, sid))
}
func description(c *bm.Context) {
var (
aid, page int64
err error
)
params := c.Request.Form
aidStr := params.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
pstr := params.Get("page")
if pstr != "" {
if page, err = strconv.ParseInt(pstr, 10, 64); err != nil || page < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
c.JSON(webSvc.Description(c, aid, page))
}
func arcReport(c *bm.Context) {
var (
aid, mid, tp int64
err error
params = c.Request.Form
)
midStr, _ := c.Get("mid")
mid = midStr.(int64)
aidStr := params.Get("aid")
tpStr := params.Get("type")
reason := params.Get("reason")
pics := params.Get("pics")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if tp, err = strconv.ParseInt(tpStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, webSvc.ArcReport(c, mid, aid, tp, reason, pics))
}
func appealTags(c *bm.Context) {
c.JSON(webSvc.AppealTags(c))
}
func arcAppeal(c *bm.Context) {
var (
mid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
data := make(map[string]string)
for name := range params {
switch name {
case "tid":
tidStr := params.Get("tid")
if _, err = strconv.ParseInt(tidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
data["tid"] = tidStr
case "aid":
aidStr := params.Get("aid")
if _, err = strconv.ParseInt(aidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
data["oid"] = aidStr
case "desc":
desc := params.Get("desc")
if desc == "" {
c.JSON(nil, ecode.RequestErr)
return
}
data["description"] = desc
default:
data[name] = params.Get(name)
}
}
c.JSON(nil, webSvc.ArcAppeal(c, mid, data))
}
func authorRecommend(c *bm.Context) {
var (
aid int64
err error
)
params := c.Request.Form
aidStr := params.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.AuthorRecommend(c, aid))
}
func relatedArcs(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(webSvc.RelatedArcs(c, v.Aid))
}
func detail(c *bm.Context) {
var (
mid int64
err error
rs *model.Detail
)
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if midStr, ok := c.Get("mid"); ok {
mid = midStr.(int64)
}
cdnIP := c.Request.Header.Get("X-Cache-Server-Addr")
if rs, err = webSvc.Detail(c, v.Aid, mid, cdnIP, c.Request.Header.Get("Cookie")); err != nil {
c.JSON(nil, err)
return
}
c.JSON(rs, nil)
}
func arcUGCPay(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(webSvc.ArcUGCPay(c, mid, v.Aid))
}
func arcRelation(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(webSvc.ArcRelation(c, mid, v.Aid))
}

View File

@@ -0,0 +1,109 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/conf"
artmdl "go-common/app/interface/openplatform/article/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func articleList(c *bm.Context) {
var (
rid, mid int64
pn, ps, sort int
aids []int64
err error
)
param := c.Request.Form
pnStr := param.Get("pn")
psStr := param.Get("ps")
ridStr := param.Get("rid")
aidsStr := param.Get("aids")
sortStr := param.Get("sort")
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Rule.MaxArtPageSize {
ps = conf.Conf.Rule.MaxArtPageSize
}
if ridStr != "" {
if rid, err = strconv.ParseInt(ridStr, 10, 64); err != nil || rid < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
if aidsStr != "" {
if aids, err = xstr.SplitInts(aidsStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if sortStr != "" {
if sort, err = strconv.Atoi(sortStr); err != nil || sort < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
sortCheck := false
for _, v := range artmdl.SortFields {
if sort == v {
sortCheck = true
break
}
}
if !sortCheck && sort != 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
c.JSON(webSvc.ArticleList(c, rid, mid, sort, pn, ps, aids))
}
func articleUpList(c *bm.Context) {
var mid int64
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.ArticleUpList(c, mid))
}
func categories(c *bm.Context) {
c.JSON(webSvc.Categories(c))
}
func newCount(c *bm.Context) {
var (
count, pubTime int64
err error
)
pubTimeStr := c.Request.Form.Get("pubtime")
if pubTime, err = strconv.ParseInt(pubTimeStr, 10, 64); err != nil || pubTime < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if count, err = webSvc.NewCount(c, pubTime); err != nil {
c.JSON(nil, err)
return
}
c.JSON(struct {
NewCount int64 `json:"new_count"`
}{NewCount: count}, nil)
}
func upMoreArts(c *bm.Context) {
var (
aid int64
err error
)
aidStr := c.Request.Form.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.UpMoreArts(c, aid))
}

View File

@@ -0,0 +1,32 @@
package http
import bm "go-common/library/net/http/blademaster"
func bnj2019(c *bm.Context) {
var mid int64
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.Bnj2019(c, mid))
}
func bnj2019Aids(c *bm.Context) {
data := make(map[string]interface{}, 1)
data["list"] = webSvc.Bnj2019Aids(c)
c.JSON(data, nil)
}
func timeline(c *bm.Context) {
var mid int64
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
list, err := webSvc.Timeline(c, mid)
if err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 1)
data["list"] = list
c.JSON(data, nil)
}

View File

@@ -0,0 +1,15 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func broadServer(c *bm.Context) {
v := new(struct {
Platform string `form:"platform" validate:"required"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(webSvc.BroadServers(c, v.Platform))
}

View File

@@ -0,0 +1,135 @@
package http
import (
"strconv"
"time"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log/infoc"
bm "go-common/library/net/http/blademaster"
)
func coins(c *bm.Context) {
var (
mid, aid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
aidStr := params.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.Coins(c, mid, aid))
}
func addCoin(c *bm.Context) {
var (
mid, aid, multiply int64
err error
like bool
actLike = "cointolike"
)
params := c.Request.Form
aidStr := params.Get("aid")
multiStr := params.Get("multiply")
avTypeStr := params.Get("avtype")
business := params.Get("business")
upIDStr := params.Get("upid")
selectLikeStr := params.Get("select_like")
selectLike, _ := strconv.Atoi(selectLikeStr)
midStr, _ := c.Get("mid")
mid = midStr.(int64)
ck := c.Request.Header.Get("Cookie")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if multiply, err = strconv.ParseInt(multiStr, 10, 64); err != nil || multiply <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
upID, _ := strconv.ParseInt(upIDStr, 10, 64)
avtype, _ := strconv.ParseInt(avTypeStr, 10, 64)
if avtype == 0 {
avtype = model.CoinAddArcType
}
if avtype != model.CoinAddArcType && avtype != model.CoinAddArtType {
c.JSON(nil, ecode.RequestErr)
return
}
if avtype == model.CoinAddArtType && upID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if business != "" {
if business == model.CoinArcBusiness {
avtype = model.CoinAddArcType
} else if business == model.CoinArtBusiness {
avtype = model.CoinAddArtType
} else {
c.JSON(nil, ecode.RequestErr)
return
}
} else {
switch avtype {
case model.CoinAddArcType:
business = model.CoinArcBusiness
case model.CoinAddArtType:
business = model.CoinArtBusiness
default:
c.JSON(nil, ecode.RequestErr)
return
}
}
ua := c.Request.UserAgent()
refer := c.Request.Referer()
if like, err = webSvc.AddCoin(c, aid, mid, upID, multiply, avtype, business, ck, ua, refer, time.Now(), selectLike); err == nil {
if webSvc.CheatInfoc != nil {
itemType := infoc.ItemTypeAv
if avtype == model.CoinAddArtType {
itemType = "article"
}
webSvc.CheatInfoc.InfoAntiCheat2(c, strconv.FormatInt(upID, 10), strconv.FormatInt(aid, 10), strconv.FormatInt(mid, 10), strconv.FormatInt(aid, 10), itemType, "coin", "")
if like {
webSvc.CheatInfoc.InfoAntiCheat2(c, strconv.FormatInt(upID, 10), strconv.FormatInt(aid, 10), strconv.FormatInt(mid, 10), strconv.FormatInt(aid, 10), "av", actLike, "")
}
}
}
c.JSON(struct {
Like bool `json:"like"`
}{Like: like}, err)
}
func coinExp(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(webSvc.CoinExp(c, mid))
}
func coinList(c *bm.Context) {
var (
ls []*model.CoinArc
count int
err error
)
v := new(struct {
Mid int64 `form:"mid" validate:"min=1"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"20" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if ls, count, err = webSvc.CoinList(c, v.Mid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
c.JSONMap(map[string]interface{}{
"count": count,
"data": ls,
}, err)
}

View File

@@ -0,0 +1,71 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/conf"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func dynamicRegion(c *bm.Context) {
var (
rid, pn, ps int
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
pnStr := params.Get("pn")
psStr := params.Get("ps")
if rid, err = strconv.Atoi(ridStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 {
ps = conf.Conf.Rule.DynamicNumArcs
} else if ps > conf.Conf.Rule.MaxArcsPageSize {
ps = conf.Conf.Rule.MaxArcsPageSize
}
c.JSON(webSvc.DynamicRegion(c, int32(rid), pn, ps))
}
func dynamicRegionTag(c *bm.Context) {
var (
tagID int64
rid, pn, ps int
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
tagIDStr := params.Get("tag_id")
pnStr := params.Get("pn")
psStr := params.Get("ps")
if rid, err = strconv.Atoi(ridStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if tagID, err = strconv.ParseInt(tagIDStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 {
ps = conf.Conf.Rule.DynamicNumArcs
} else if ps > conf.Conf.Rule.MaxArcsPageSize {
ps = conf.Conf.Rule.MaxArcsPageSize
}
c.JSON(webSvc.DynamicRegionTag(c, tagID, int32(rid), pn, ps))
}
func dynamicRegionTotal(c *bm.Context) {
c.JSON(webSvc.DynamicRegionTotal(c))
}
func dynamicRegions(c *bm.Context) {
c.JSON(webSvc.DynamicRegions(c))
}

View File

@@ -0,0 +1,32 @@
package http
import (
"strconv"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func elecShow(c *bm.Context) {
var (
mid, loginID, aid int64
err error
)
params := c.Request.Form
midStr := params.Get("mid")
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil || mid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
aidStr := params.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
// login mid
if loginIDStr, ok := c.Get("mid"); ok {
loginID = loginIDStr.(int64)
}
c.JSON(webSvc.ElecShow(c, mid, aid, loginID))
}

View File

@@ -0,0 +1,64 @@
package http
import (
"net/http"
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func feedback(c *bm.Context) {
var (
mid, aid, tagID int64
content, buvid string
buvidCk *http.Cookie
midStr interface{}
ok bool
err error
)
params := c.Request.Form
content = params.Get("content")
aidStr := params.Get("aid")
if aidStr != "" {
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil {
log.Warn("strconv.ParseInt(%s) err(%d)", aidStr, err)
c.JSON(nil, ecode.RequestErr)
return
}
}
tagIDStr := params.Get("tag_id")
if tagID, err = strconv.ParseInt(tagIDStr, 10, 64); err != nil || tagID < 1 {
log.Warn("strconv.ParseInt(%s) error(%v)", tagIDStr, err)
c.JSON(nil, ecode.RequestErr)
return
}
if !model.CheckFeedTag(tagID) {
log.Warn("tag_id(%d) check fail", tagID)
c.JSON(nil, ecode.RequestErr)
return
}
if buvidCk, err = c.Request.Cookie("buvid3"); err != nil {
log.Warn("buvid3 is nil")
c.JSON(nil, ecode.RequestErr)
return
}
if buvid = buvidCk.Value; buvid == "" {
log.Warn("buvid == nil")
c.JSON(nil, ecode.RequestErr)
return
}
if midStr, ok = c.Get("mid"); ok {
mid = midStr.(int64)
}
browser := params.Get("browser")
version := params.Get("version")
email := params.Get("email")
qq := params.Get("qq")
other := params.Get("other")
feedParams := &model.Feedback{Aid: aid, Mid: mid, TagID: tagID, Buvid: buvid, Browser: browser,
Version: version, Content: &model.Content{Reason: content}, Email: email, QQ: qq, Other: other}
c.JSON(nil, webSvc.Feedback(c, feedParams))
}

View File

@@ -0,0 +1,101 @@
package http
import (
"go-common/app/interface/main/web/conf"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func helpList(c *bm.Context) {
var (
rs []*model.HelpList
err error
)
v := new(struct {
PTypeID string `form:"parentTypeId" validate:"required"`
})
if err = c.Bind(v); err != nil {
return
}
if rs, err = webSvc.HelpList(c, v.PTypeID); err != nil {
c.JSON(nil, ecode.Degrade)
return
}
c.JSON(rs, nil)
}
func helpDetail(c *bm.Context) {
var (
total int
detail []*model.HelpDeatil
list []*model.HelpList
err error
)
v := new(struct {
PTypeID string `form:"questionTypeId" validate:"required"`
KeyFlag int `form:"keyFlag" default:"1" validate:"min=1"`
FID string `form:"fId"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"15" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Ps > conf.Conf.Rule.MaxHelpPageSize {
v.Ps = conf.Conf.Rule.MaxHelpPageSize
}
if detail, list, total, err = webSvc.HelpDetail(c, v.FID, v.PTypeID, v.KeyFlag, v.Pn, v.Ps); err != nil {
c.JSON(nil, ecode.Degrade)
log.Error("webSvc.HelpDetail(%s,%d,%d,%d) error(%v)", v.PTypeID, v.KeyFlag, v.Pn, v.Ps, err)
return
}
data := make(map[string]interface{}, 2)
rsDetail := make(map[string]interface{}, 2)
page := map[string]int{
"num": v.Pn,
"size": v.Ps,
"total": total,
}
rsDetail["items"] = detail
rsDetail["page"] = page
data["detail"] = rsDetail
data["list"] = list
c.JSON(data, nil)
}
func helpSearch(c *bm.Context) {
var (
total int
list []*model.HelpDeatil
err error
)
v := new(struct {
PTypeID string `form:"questionTypeId" default:"-1"`
KeyWords string `form:"keyWords" validate:"required"`
KeyFlag int `form:"keyFlag" default:"1" validate:"min=1"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"15" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Ps > conf.Conf.Rule.MaxHelpPageSize {
v.Ps = conf.Conf.Rule.MaxHelpPageSize
}
if list, total, err = webSvc.HelpSearch(c, v.PTypeID, v.KeyWords, v.KeyFlag, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
log.Error("webSvc.HelpDetail(%s,%d,%d,%d) error(%v)", v.KeyWords, v.KeyFlag, v.Pn, v.Ps, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"num": v.Pn,
"size": v.Ps,
"total": total,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}

View File

@@ -0,0 +1,210 @@
package http
import (
"net/http"
"go-common/app/interface/main/web/conf"
"go-common/app/interface/main/web/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/cache"
"go-common/library/net/http/blademaster/middleware/cache/store"
"go-common/library/net/http/blademaster/middleware/verify"
)
var (
webSvc *service.Service
authSvr *auth.Auth
vfySvr *verify.Verify
// cache components
cacheSvr *cache.Cache
deg *cache.Degrader
)
// Init init
func Init(c *conf.Config, s *service.Service) {
authSvr = auth.New(c.Auth)
vfySvr = verify.New(c.Verify)
webSvc = s
cacheSvr = cache.New(store.NewMemcache(c.DegradeConfig.Memcache))
deg = cache.NewDegrader(c.DegradeConfig.Expire)
// init outer router
engine := bm.NewServer(c.HTTPServer)
engine.Use(bm.Recovery(), bm.Logger(), bm.Trace(), bm.Mobile())
outerRouter(engine)
internalRouter(engine)
if err := engine.Start(); err != nil {
log.Error("engine.Start error(%v)", err)
panic(err)
}
}
func outerRouter(e *bm.Engine) {
e.Ping(ping)
e.GET("/x/web-interface/view", authSvr.Guest, view)
group := e.Group("/x/web-interface", bm.CSRF(), bm.CORS())
{
arcGroup := group.Group("/archive")
{
arcGroup.GET("/coins", authSvr.User, coins)
arcGroup.GET("/stat", archiveStat)
arcGroup.GET("/desc", description)
arcGroup.POST("/report", authSvr.User, arcReport)
arcGroup.POST("/appeal", authSvr.User, arcAppeal)
arcGroup.GET("/appeal/tags", appealTags)
arcGroup.GET("/author/recommend", authorRecommend)
arcGroup.GET("/related", relatedArcs)
arcGroup.POST("/like", authSvr.User, like)
arcGroup.POST("/like/triple", authSvr.User, likeTriple)
arcGroup.GET("/has/like", authSvr.User, hasLike)
arcGroup.GET("/ugc/pay", authSvr.User, arcUGCPay)
arcGroup.GET("/relation", authSvr.User, arcRelation)
}
dyGroup := group.Group("/dynamic")
{
dyGroup.GET("/region", dynamicRegion)
dyGroup.GET("/index", dynamicRegions)
dyGroup.GET("/tag", dynamicRegionTag)
dyGroup.GET("/total", dynamicRegionTotal)
}
rankGroup := group.Group("/ranking")
{
rankGroup.GET("", ranking)
rankGroup.GET("/index", rankingIndex)
rankGroup.GET("/region", rankingRegion)
rankGroup.GET("/recommend", rankingRecommend)
rankGroup.GET("/tag", rankingTag)
}
tagGroup := group.Group("/tag")
{
tagGroup.GET("/top", tagAids)
}
artGroup := group.Group("/article")
{
artGroup.GET("/list", authSvr.Guest, articleList)
artGroup.GET("/up/list", authSvr.Guest, articleUpList)
artGroup.GET("/categories", categories)
artGroup.GET("/newcount", newCount)
artGroup.GET("/early", upMoreArts)
}
coinGroup := group.Group("/coin")
{
coinGroup.POST("/add", authSvr.User, addCoin)
coinGroup.GET("/today/exp", authSvr.User, coinExp)
}
onlineGroup := group.Group("/online")
{
onlineGroup.GET("", onlineInfo)
onlineGroup.GET("/list", onlineList)
}
helpGroup := group.Group("/help")
{
helpGroup.GET("/list", cacheSvr.Cache(deg.Args("parentTypeId"), nil), helpList)
helpGroup.GET("/detail", cacheSvr.Cache(deg.Args("pn", "ps", "fId", "questionTypeId"), nil), helpDetail)
helpGroup.GET("/search", helpSearch)
}
viewGroup := group.Group("/view")
{
viewGroup.GET("/detail", authSvr.Guest, detail)
}
searchGroup := group.Group("/search")
{
searchGroup.GET("/all", authSvr.Guest, searchAll)
searchGroup.GET("/type", authSvr.Guest, searchByType)
searchGroup.GET("/recommend", authSvr.Guest, searchRec)
searchGroup.GET("/default", authSvr.Guest, searchDefault)
searchGroup.GET("/egg", searchEgg)
}
wxGroup := group.Group("/wx")
{
wxGroup.GET("/hot", wxHot)
wxGroup.GET("/search/all", authSvr.Guest, wxSearchAll)
}
bnjGroup := group.Group("/bnj2019")
{
bnjGroup.GET("", authSvr.Guest, bnj2019)
bnjGroup.GET("/timeline", authSvr.Guest, timeline)
}
group.GET("/region/custom", regionCustom)
group.GET("/attentions", authSvr.User, attentions)
group.GET("/card", authSvr.Guest, card)
group.GET("/nav", authSvr.Guest, nav)
group.GET("/newlist", newList)
group.POST("/feedback", authSvr.Guest, feedback)
group.GET("/zone", ipZone)
group.POST("/share/add", authSvr.Guest, addShare)
group.GET("/elec/show", authSvr.Guest, elecShow)
group.GET("/index/icon", indexIcon)
group.GET("/baidu/kv", kv)
group.GET("/cmtbox", cmtbox)
group.GET("/abserver", authSvr.Guest, abServer)
group.GET("/up/rec", authSvr.User, upRec)
group.GET("/broadcast/servers", broadServer)
}
e.GET("/x/coin/list", coinList)
}
func internalRouter(e *bm.Engine) {
group := e.Group("/x/internal/web-interface")
{
dyGroup := group.Group("/dynamic")
{
dyGroup.GET("/region", vfySvr.Verify, dynamicRegion)
dyGroup.GET("/index", vfySvr.Verify, dynamicRegions)
dyGroup.GET("/tag", vfySvr.Verify, dynamicRegionTag)
dyGroup.GET("/total", vfySvr.Verify, dynamicRegionTotal)
}
rankGroup := group.Group("/ranking")
{
rankGroup.GET("", vfySvr.Verify, ranking)
rankGroup.GET("/index", vfySvr.Verify, rankingIndex)
rankGroup.GET("/region", vfySvr.Verify, rankingRegion)
rankGroup.GET("/recommend", vfySvr.Verify, rankingRecommend)
rankGroup.GET("/tag", vfySvr.Verify, rankingTag)
}
tagGroup := group.Group("/tag")
{
tagGroup.GET("/top", vfySvr.Verify, tagAids)
tagGroup.GET("/detail", vfySvr.Verify, tagDetail)
}
helpGroup := group.Group("/help")
{
helpGroup.GET("/list", vfySvr.Verify, helpList)
helpGroup.GET("/detail", vfySvr.Verify, helpDetail)
helpGroup.GET("/search", vfySvr.Verify, helpSearch)
}
onlineGroup := group.Group("/online")
{
onlineGroup.GET("", vfySvr.Verify, onlineInfo)
onlineGroup.GET("/list", vfySvr.Verify, onlineList)
}
viewGroup := group.Group("/view")
{
viewGroup.GET("", vfySvr.Verify, authSvr.Guest, view)
viewGroup.GET("/detail", vfySvr.Verify, authSvr.Guest, detail)
}
searchGroup := group.Group("/search")
{
searchGroup.GET("/all", vfySvr.Verify, authSvr.Guest, searchAll)
searchGroup.GET("/type", vfySvr.Verify, authSvr.Guest, searchByType)
searchGroup.GET("/recommend", vfySvr.Verify, authSvr.Guest, searchRec)
}
group.GET("/newlist", vfySvr.Verify, newList)
group.GET("/zone", vfySvr.Verify, ipZone)
group.GET("/region/custom", vfySvr.Verify, regionCustom)
group.GET("/baidu/kv", vfySvr.Verify, kv)
group.GET("/cmtbox", vfySvr.Verify, cmtbox)
group.GET("/broadcast/servers", vfySvr.Verify, broadServer)
group.GET("/bnj2019", vfySvr.Verify, authSvr.Guest, bnj2019)
group.GET("/bnj2019/aids", vfySvr.Verify, bnj2019Aids)
}
}
func ping(c *bm.Context) {
if err := webSvc.Ping(c); err != nil {
log.Error("web-interface ping error")
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,9 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func indexIcon(c *bm.Context) {
c.JSON(webSvc.IndexIcon(), nil)
}

View File

@@ -0,0 +1,9 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func ipZone(c *bm.Context) {
c.JSON(webSvc.IPZone(c))
}

View File

@@ -0,0 +1,68 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/model"
bm "go-common/library/net/http/blademaster"
)
func like(c *bm.Context) {
var (
mid int64
err error
)
v := new(struct {
Aid int64 `form:"aid" validate:"min=1,required"`
Like int8 `form:"like" validate:"min=1,max=4,required"`
})
if err = c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid = midStr.(int64)
upperID, err := webSvc.Like(c, v.Aid, mid, v.Like)
c.JSON(nil, err)
if err == nil && webSvc.CheatInfoc != nil {
webSvc.CheatInfoc.InfoAntiCheat2(c, strconv.FormatInt(upperID, 10), strconv.FormatInt(v.Aid, 10), strconv.FormatInt(mid, 10), strconv.FormatInt(v.Aid, 10), "av", model.LikeType[v.Like], "")
}
}
func likeTriple(c *bm.Context) {
var (
mid int64
actTriple = "triplelike"
err error
)
v := new(struct {
Aid int64 `form:"aid" validate:"min=1,required"`
})
if err = c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid = midStr.(int64)
triple, err := webSvc.LikeTriple(c, v.Aid, mid)
c.JSON(triple, err)
if err != nil {
return
}
if err == nil && webSvc.CheatInfoc != nil && triple.Anticheat {
webSvc.CheatInfoc.InfoAntiCheat2(c, strconv.FormatInt(triple.UpID, 10), strconv.FormatInt(v.Aid, 10), strconv.FormatInt(mid, 10), strconv.FormatInt(v.Aid, 10), "av", actTriple, "")
}
}
func hasLike(c *bm.Context) {
var (
mid int64
)
v := new(struct {
Aid int64 `form:"aid" validate:"min=1,required"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid = midStr.(int64)
c.JSON(webSvc.HasLike(c, v.Aid, mid))
}

View File

@@ -0,0 +1,22 @@
package http
import (
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func nav(c *bm.Context) {
var (
rawMid interface{}
ok bool
)
if rawMid, ok = c.Get("mid"); !ok {
// NOTE NoLogin here only for web
c.JSON(model.FailedNavResp{}, ecode.NoLogin)
return
}
mid := rawMid.(int64)
c.JSON(webSvc.Nav(c, mid, c.Request.Header.Get("Cookie")))
}

View File

@@ -0,0 +1,56 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/conf"
"go-common/app/service/main/archive/api"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func newList(c *bm.Context) {
var (
rid, pn, ps, tp, count int
rs []*api.Arc
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
pnStr := params.Get("pn")
psStr := params.Get("ps")
tpStr := params.Get("type")
if ridStr != "" {
if rid, err = strconv.Atoi(ridStr); err != nil || rid < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Rule.MaxArcsPageSize {
ps = conf.Conf.Rule.MaxArcsPageSize
}
if tpStr != "" {
if tp, err = strconv.Atoi(tpStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if rs, count, err = webSvc.NewList(c, int32(rid), int8(tp), pn, ps); err != nil {
c.JSON(nil, err)
log.Error("webSvc.Newlist(%d,%d,%d) error(%v)", rid, pn, ps, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"num": pn,
"size": ps,
"count": count,
}
data["page"] = page
data["archives"] = rs
c.JSON(data, nil)
}

View File

@@ -0,0 +1,13 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func onlineInfo(c *bm.Context) {
c.JSON(webSvc.OnlineArchiveCount(c), nil)
}
func onlineList(c *bm.Context) {
c.JSON(webSvc.OnlineList(c))
}

View File

@@ -0,0 +1,152 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func ranking(c *bm.Context) {
var (
rid int64
rankType, day, arcType int
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
rankTypeStr := params.Get("type")
dayStr := params.Get("day")
arcTypeStr := params.Get("arc_type")
if rid, err = strconv.ParseInt(ridStr, 10, 64); err != nil || rid < 0 {
rid = 0
}
if rankType, err = strconv.Atoi(rankTypeStr); err != nil {
rankType = 1
}
if day, err = strconv.Atoi(dayStr); err != nil {
day = 3
}
if arcType, err = strconv.Atoi(arcTypeStr); err != nil {
arcType = 0
}
if err = checkType(rid, rankType, day, arcType); err != nil {
c.JSON(nil, err)
return
}
c.JSON(webSvc.Ranking(c, int16(rid), rankType, model.DayType[day], model.ArcType[arcType]))
}
func checkType(rid int64, rankType, day, arcType int) (err error) {
if _, ok := model.RankType[rankType]; !ok {
err = ecode.RequestErr
return
}
if _, ok := model.DayType[day]; !ok {
err = ecode.RequestErr
return
}
if _, ok := model.ArcType[arcType]; !ok {
err = ecode.RequestErr
}
// bangumi and rookie not have recent contribution
if (rid == 33 || rankType == 3) && arcType == 1 {
err = ecode.RequestErr
}
return
}
func rankingIndex(c *bm.Context) {
var (
day int
err error
)
params := c.Request.Form
dayStr := params.Get("day")
if day, err = strconv.Atoi(dayStr); err != nil {
day = 3
}
if err = checkIndexDay(day); err != nil {
c.JSON(nil, err)
return
}
c.JSON(webSvc.RankingIndex(c, day))
}
func rankingRegion(c *bm.Context) {
var (
day, original int
rid int64
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
dayStr := params.Get("day")
originalStr := params.Get("original")
if rid, err = strconv.ParseInt(ridStr, 10, 64); err != nil || rid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if day, err = strconv.Atoi(dayStr); err != nil {
day = 3
}
if _, ok := model.DayType[day]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
if original, err = strconv.Atoi(originalStr); err != nil {
original = 0
} else if original != 1 && original != 0 {
original = 0
}
c.JSON(webSvc.RankingRegion(c, int16(rid), day, original))
}
func rankingRecommend(c *bm.Context) {
var (
rid int64
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
if rid, err = strconv.ParseInt(ridStr, 10, 64); err != nil || rid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.RankingRecommend(c, int16(rid)))
}
func rankingTag(c *bm.Context) {
var (
rid, tagID int64
err error
)
params := c.Request.Form
ridStr := params.Get("rid")
tagIDStr := params.Get("tag_id")
if rid, err = strconv.ParseInt(ridStr, 10, 64); err != nil || rid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if tagID, err = strconv.ParseInt(tagIDStr, 10, 64); err != nil || tagID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.RankingTag(c, int16(rid), tagID))
}
func regionCustom(c *bm.Context) {
c.JSON(webSvc.RegionCustom(c))
}
func checkIndexDay(day int) (err error) {
err = ecode.RequestErr
for _, dayItem := range model.IndexDayType {
if day == dayItem {
err = nil
return
}
}
return
}

View File

@@ -0,0 +1,51 @@
package http
import (
"strconv"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func kv(c *bm.Context) {
c.JSON(webSvc.Kv(c))
}
func cmtbox(c *bm.Context) {
var (
id int64
err error
)
params := c.Request.Form
idStr := params.Get("id")
if id, err = strconv.ParseInt(idStr, 10, 64); err != nil || id <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(webSvc.CmtBox(c, id))
}
func abServer(c *bm.Context) {
var (
mid int64
buvid string
)
v := new(struct {
Channel string `form:"channel"`
Platform int `form:"platform"`
})
if err := c.Bind(v); err != nil {
return
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if buvid == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.AbServer(c, mid, v.Platform, v.Channel, buvid))
}

View File

@@ -0,0 +1,126 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/model"
bm "go-common/library/net/http/blademaster"
)
func searchAll(c *bm.Context) {
var (
mid int64
buvid string
err error
)
v := new(model.SearchAllArg)
if err = c.Bind(v); err != nil {
return
}
if v.Pn <= 0 {
v.Pn = 1
}
singleColumnStr := c.Request.Form.Get("single_column")
if v.SingleColumn, err = strconv.Atoi(singleColumnStr); err != nil {
v.SingleColumn = -1
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.SearchAll(c, mid, v, buvid, c.Request.Header.Get("User-Agent"), ""))
}
func searchByType(c *bm.Context) {
var (
mid int64
buvid string
err error
)
v := new(model.SearchTypeArg)
if err = c.Bind(v); err != nil {
return
}
singleColumnStr := c.Request.Form.Get("single_column")
if v.SingleColumn, err = strconv.Atoi(singleColumnStr); err != nil {
v.SingleColumn = -1
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.SearchByType(c, mid, v, buvid, c.Request.Header.Get("User-Agent")))
}
func searchRec(c *bm.Context) {
var (
mid int64
buvid string
err error
)
v := new(struct {
Pn int `form:"page" default:"1" validate:"min=1"`
Ps int `form:"pagesize" default:"5" validate:"min=1"`
Keyword string `form:"keyword"`
FromSource string `form:"from_source"`
})
if err = c.Bind(v); err != nil {
return
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.SearchRec(c, mid, v.Pn, v.Ps, v.Keyword, v.FromSource, buvid, c.Request.Header.Get("User-Agent")))
}
func searchDefault(c *bm.Context) {
var (
mid int64
buvid string
err error
)
v := new(struct {
FromSource string `form:"from_source"`
})
if err = c.Bind(v); err != nil {
return
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.SearchDefault(c, mid, v.FromSource, buvid, c.Request.Header.Get("User-Agent")))
}
func upRec(c *bm.Context) {
var buvid string
v := new(model.SearchUpRecArg)
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
c.JSON(webSvc.UpRec(c, mid, v, buvid))
}
func searchEgg(c *bm.Context) {
v := new(struct {
EggID int64 `form:"egg_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(webSvc.SearchEgg(c, v.EggID))
}

View File

@@ -0,0 +1,54 @@
package http
import (
"strconv"
"go-common/app/interface/main/web/conf"
v1 "go-common/app/service/main/archive/api"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// tagAids gets aids via tag
func tagAids(c *bm.Context) {
var (
err error
tid int64
pn, ps, total int
arcs []*v1.Arc
params = c.Request.Form
tidStr = params.Get("tid") // tag id
pnStr = params.Get("pn")
psStr = params.Get("ps")
)
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Tag.MaxSize {
ps = conf.Conf.Tag.MaxSize
}
if tid, err = strconv.ParseInt(tidStr, 10, 64); err != nil || tid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if total, arcs, err = webSvc.TagAids(c, tid, pn, ps); err != nil {
log.Error("webSvc.TagAids(%d, %d, %d) error(%v)", tid, pn, ps, err)
return
}
c.JSONMap(map[string]interface{}{
"data": arcs,
"total": total,
}, nil)
}
func tagDetail(c *bm.Context) {
v := new(struct {
TagID int64 `form:"tag_id" validate:"min=1"`
Ps int `form:"ps" default:"20" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(webSvc.TagDetail(c, v.TagID, v.Ps))
}

View File

@@ -0,0 +1,52 @@
package http
import (
"go-common/app/interface/main/web/model"
bm "go-common/library/net/http/blademaster"
)
func wxHot(c *bm.Context) {
v := new(struct {
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"100" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
list, count, err := webSvc.WxHot(c, v.Pn, v.Ps)
if err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"pn": v.Pn,
"ps": v.Ps,
"count": count,
}
data["data"] = list
data["page"] = page
c.JSONMap(data, nil)
}
func wxSearchAll(c *bm.Context) {
var (
mid int64
buvid string
err error
)
v := new(model.SearchAllArg)
if err = c.Bind(v); err != nil {
return
}
if v.Pn <= 0 {
v.Pn = 1
}
if ck, err := c.Request.Cookie("buvid3"); err == nil {
buvid = ck.Value
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(webSvc.SearchAll(c, mid, v, buvid, c.Request.Header.Get("User-Agent"), model.WxSearchType))
}

View File

@@ -0,0 +1,60 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"abserver.go",
"account.go",
"archive.go",
"article.go",
"baidu.go",
"bigdata.go",
"bnj.go",
"coin.go",
"elec.go",
"feedback.go",
"help.go",
"icon.go",
"nav.go",
"online.go",
"reply.go",
"search.go",
"shop.go",
"tag.go",
"web.go",
"wechat.go",
],
importpath = "go-common/app/interface/main/web/model",
tags = ["automanaged"],
deps = [
"//app/interface/main/dm2/model:go_default_library",
"//app/interface/main/reply/model/reply:go_default_library",
"//app/interface/main/tag/model:go_default_library",
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/account/model:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//app/service/main/broadcast/api/grpc/v1:go_default_library",
"//app/service/main/ugcpay/api/grpc/v1:go_default_library",
"//library/time:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,10 @@
package model
import "encoding/json"
// AbServer .
type AbServer struct {
Hit json.RawMessage `json:"hit"`
Expire int `json:"expire"`
Vars json.RawMessage `json:"vars"`
}

View File

@@ -0,0 +1,120 @@
package model
import (
"strconv"
accmdl "go-common/app/service/main/account/api"
account "go-common/app/service/main/account/model"
)
// Space space top photo
type Space struct {
SImg string `json:"s_img"`
LImg string `json:"l_img"`
}
// Card Card and Space and Relation and Archive Count.
type Card struct {
Card *AccountCard `json:"card"`
Space *Space `json:"space,omitempty"`
Following bool `json:"following"`
ArchiveCount int `json:"archive_count"`
ArticleCount int `json:"article_count"`
Follower int64 `json:"follower"`
}
// AccountCard struct.
type AccountCard struct {
Mid string `json:"mid"`
Name string `json:"name"`
Approve bool `json:"approve"`
Sex string `json:"sex"`
Rank string `json:"rank"`
Face string `json:"face"`
DisplayRank string `json:"DisplayRank"`
Regtime int64 `json:"regtime"`
Spacesta int `json:"spacesta"`
Birthday string `json:"birthday"`
Place string `json:"place"`
Description string `json:"description"`
Article int `json:"article"`
Attentions []int64 `json:"attentions"`
Fans int `json:"fans"`
Friend int `json:"friend"`
Attention int `json:"attention"`
Sign string `json:"sign"`
LevelInfo struct {
Cur int `json:"current_level"`
Min int `json:"current_min"`
NowExp int `json:"current_exp"`
NextExp interface{} `json:"next_exp"`
} `json:"level_info"`
Pendant account.PendantInfo `json:"pendant"`
Nameplate account.NameplateInfo `json:"nameplate"`
Official accmdl.OfficialInfo
OfficialVerify struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"official_verify"`
Vip struct {
Type int `json:"vipType"`
DueRemark string `json:"dueRemark"`
AccessStatus int `json:"accessStatus"`
VipStatus int `json:"vipStatus"`
VipStatusWarn string `json:"vipStatusWarn"`
} `json:"vip"`
}
// FromCard from account catd.
func (ac *AccountCard) FromCard(c *account.Card) {
ac.Mid = strconv.FormatInt(c.Mid, 10)
ac.Name = c.Name
// ac.Approve =
ac.Sex = c.Sex
ac.Rank = strconv.FormatInt(int64(c.Rank), 10)
ac.DisplayRank = "0"
ac.Face = c.Face
// ac.Regtime =
if c.Silence == 1 {
ac.Spacesta = -2
}
// ac.Birthday =
// ac.Place =
// ac.Description =
// ac.Article =
// ac.Attentions = []int64{}
// ac.Fans =
// ac.Friend
// ac.Attention =
ac.Sign = c.Sign
ac.LevelInfo.Cur = int(c.Level)
ac.LevelInfo.NextExp = 0
// ac.LevelInfo.Min =
ac.Pendant = c.Pendant
ac.Nameplate = c.Nameplate
if c.Official.Role == 0 {
ac.OfficialVerify.Type = -1
} else {
if c.Official.Role <= 2 {
ac.OfficialVerify.Type = 0
ac.OfficialVerify.Desc = c.Official.Title
} else {
ac.OfficialVerify.Type = 1
ac.OfficialVerify.Desc = c.Official.Title
}
}
ac.Official = c.Official
ac.Vip.Type = int(c.Vip.Type)
ac.Vip.VipStatus = int(c.Vip.Status)
}
// DefaultProfile .
var DefaultProfile = &accmdl.ProfileStatReply{
Profile: &account.Profile{
Sex: "保密",
Rank: 10000,
Face: "https://static.hdslb.com/images/member/noface.gif",
Sign: "没签名",
},
LevelInfo: accmdl.LevelInfo{},
}

View File

@@ -0,0 +1,159 @@
package model
import (
"go-common/app/interface/main/dm2/model"
tagmdl "go-common/app/interface/main/tag/model"
accmdl "go-common/app/service/main/account/model"
arcmdl "go-common/app/service/main/archive/api"
ugcmdl "go-common/app/service/main/ugcpay/api/grpc/v1"
)
// View view data
type View struct {
// archive data
*arcmdl.Arc
NoCache bool `json:"no_cache"`
// video data pages
Pages []*arcmdl.Page `json:"pages,omitempty"`
Subtitle *Subtitle `json:"subtitle"`
Asset *ugcmdl.AssetQueryResp `json:"asset,omitempty"`
}
// AssetRelation .
type AssetRelation struct {
State int `json:"state"`
}
// Stat archive stat web struct
type Stat struct {
Aid int64 `json:"aid"`
View interface{} `json:"view"`
Danmaku int32 `json:"danmaku"`
Reply int32 `json:"reply"`
Fav int32 `json:"favorite"`
Coin int32 `json:"coin"`
Share int32 `json:"share"`
Like int32 `json:"like"`
NowRank int32 `json:"now_rank"`
HisRank int32 `json:"his_rank"`
NoReprint int32 `json:"no_reprint"`
Copyright int32 `json:"copyright"`
}
// Detail detail data
type Detail struct {
View *View
Card *Card
Tags []*tagmdl.Tag
Reply *ReplyHot
Related []*arcmdl.Arc
}
// ArchiveUserCoins .
type ArchiveUserCoins struct {
Multiply int64 `json:"multiply"`
}
// Subtitle dm subTitle.
type Subtitle struct {
AllowSubmit bool `json:"allow_submit"`
List []*SubtitleItem `json:"list"`
}
// SubtitleItem dm subTitle.
type SubtitleItem struct {
*model.VideoSubtitle
Author *accmdl.Info `json:"author"`
}
// TripleRes struct
type TripleRes struct {
Like bool `json:"like"`
Coin bool `json:"coin"`
Fav bool `json:"fav"`
Multiply int64 `json:"multiply"`
UpID int64 `json:"-"`
Anticheat bool `json:"-"`
}
var (
// StatAllowStates archive stat allow states
statAllowStates = []int32{-9, -15, -30}
)
// CheckAllowState check archive stat allow state
func CheckAllowState(arc *arcmdl.Arc) bool {
if arc.IsNormal() {
return true
}
for _, allow := range statAllowStates {
if arc.State == allow {
return true
}
}
return false
}
// FmtArc fmt grpc arc to archive3
func FmtArc(arc *arcmdl.Arc) (data *arcmdl.Arc) {
data = &arcmdl.Arc{
Aid: arc.Aid,
Videos: arc.Videos,
TypeID: arc.TypeID,
TypeName: arc.TypeName,
Copyright: arc.Copyright,
Pic: arc.Pic,
Title: arc.Title,
PubDate: arc.PubDate,
Ctime: arc.Ctime,
Desc: arc.Desc,
State: arc.State,
Access: arc.Access,
Attribute: arc.Attribute,
Tag: arc.Tag,
Tags: arc.Tags,
Duration: arc.Duration,
MissionID: arc.MissionID,
OrderID: arc.OrderID,
RedirectURL: arc.RedirectURL,
Forward: arc.Forward,
Rights: arcmdl.Rights{
Bp: arc.Rights.Bp,
Elec: arc.Rights.Elec,
Download: arc.Rights.Download,
Movie: arc.Rights.Movie,
Pay: arc.Rights.Pay,
HD5: arc.Rights.HD5,
NoReprint: arc.Rights.NoReprint,
Autoplay: arc.Rights.Autoplay,
UGCPay: arc.Rights.UGCPay,
},
Author: arcmdl.Author{
Mid: arc.Author.Mid,
Name: arc.Author.Name,
Face: arc.Author.Face,
},
Stat: arcmdl.Stat{
Aid: arc.Stat.Aid,
View: arc.Stat.View,
Danmaku: arc.Stat.Danmaku,
Reply: arc.Stat.Reply,
Fav: arc.Stat.Fav,
Coin: arc.Stat.Coin,
Share: arc.Stat.Share,
NowRank: arc.Stat.NowRank,
HisRank: arc.Stat.HisRank,
Like: arc.Stat.Like,
DisLike: arc.Stat.DisLike,
},
ReportResult: arc.ReportResult,
Dynamic: arc.Dynamic,
FirstCid: arc.FirstCid,
Dimension: arcmdl.Dimension{
Width: arc.Dimension.Width,
Height: arc.Dimension.Height,
Rotate: arc.Dimension.Rotate,
},
}
return
}

View File

@@ -0,0 +1,87 @@
package model
import (
artmdl "go-common/app/interface/openplatform/article/model"
accmdl "go-common/app/service/main/account/model"
"go-common/library/time"
"strconv"
)
// Info struct.
type Info struct {
Mid string `json:"mid"`
Name string `json:"uname"`
Sex string `json:"sex"`
Sign string `json:"sign"`
Avatar string `json:"avatar"`
Rank string `json:"rank"`
DisplayRank string `json:"DisplayRank"`
LevelInfo struct {
Cur int `json:"current_level"`
Min int `json:"current_min"`
NowExp int `json:"current_exp"`
NextExp interface{} `json:"next_exp"`
} `json:"level_info"`
Pendant accmdl.PendantInfo `json:"pendant"`
Nameplate accmdl.NameplateInfo `json:"nameplate"`
OfficialVerify struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"official_verify"`
Vip struct {
Type int `json:"vipType"`
DueDate int64 `json:"vipDueDate"`
DueRemark string `json:"dueRemark"`
AccessStatus int `json:"accessStatus"`
VipStatus int `json:"vipStatus"`
VipStatusWarn string `json:"vipStatusWarn"`
} `json:"vip"`
// article
ID int64 `json:"id"`
Title string `json:"title"`
PublishTime time.Time `json:"publish_time"`
Following bool `json:"following"`
}
// FromCard from card.
func (i *Info) FromCard(c *accmdl.Card) {
i.Mid = strconv.FormatInt(c.Mid, 10)
i.Name = c.Name
i.Sex = c.Sex
i.Sign = c.Sign
i.Avatar = c.Face
i.Rank = strconv.FormatInt(int64(c.Rank), 10)
i.DisplayRank = "0"
i.LevelInfo.Cur = int(c.Level)
i.LevelInfo.NextExp = 0
// i.LevelInfo.Min =
i.Pendant = c.Pendant
i.Nameplate = c.Nameplate
if c.Official.Role == 0 {
i.OfficialVerify.Type = -1
} else {
if c.Official.Role <= 2 {
i.OfficialVerify.Type = 0
i.OfficialVerify.Desc = c.Official.Title
} else {
i.OfficialVerify.Type = 1
i.OfficialVerify.Desc = c.Official.Title
}
}
i.Vip.Type = int(c.Vip.Type)
i.Vip.VipStatus = int(c.Vip.Status)
i.Vip.DueDate = c.Vip.DueDate
}
// Meta struct.
type Meta struct {
*artmdl.Meta
Like int `json:"like"`
}
// ArticleUpInfo struct.
type ArticleUpInfo struct {
ArtCount int `json:"art_count"`
Follower int64 `json:"follower"`
IsFollowing bool `json:"is_following"`
}

View File

@@ -0,0 +1,14 @@
package model
import xtime "go-common/library/time"
// Kv baidu kv struct.
type Kv struct {
ID int `json:"id"`
Name string `json:"name"`
Pic string `json:"pic"`
URL string `json:"url"`
ResID int `json:"resource_id"`
STime xtime.Time `json:"stime"`
ETime xtime.Time `json:"etime"`
}

View File

@@ -0,0 +1,179 @@
package model
import arcmdl "go-common/app/service/main/archive/api"
// Rank bigdata rank struct
type Rank struct {
Note string `json:"note"`
Code int `json:"code"`
Page int `json:"page"`
Num int `json:"num"`
List []*RankArchive `json:"list"`
}
// RankArchive bigdata rank archive struct
type RankArchive struct {
Aid interface{} `json:"aid"`
Author string `json:"author"`
Coins int32 `json:"coins"`
Duration string `json:"duration"`
Mid int64 `json:"mid"`
Pic string `json:"pic"`
Play interface{} `json:"play"`
Pts int `json:"pts"`
Title string `json:"title"`
Trend *int `json:"trend"`
VideoReview int32 `json:"video_review"`
Rights arcmdl.Rights `json:"rights"`
Others []*Other `json:"others,omitempty"`
}
// Other bigdata other rank struct
type Other struct {
Aid interface{} `json:"aid"`
Play interface{} `json:"play"`
VideoReview int32 `json:"video_review"`
Coins int32 `json:"coins"`
Pts int `json:"pts"`
Title string `json:"title"`
Pic string `json:"pic"`
Duration string `json:"duration"`
Rights arcmdl.Rights `json:"rights"`
}
// RankIndex rank index struct.
type RankIndex struct {
Code int `json:"code"`
Pages int `json:"pages"`
Num int `json:"num"`
List map[string]*IndexArchive `json:"list"`
}
// IndexArchive rank index archive struct.
type IndexArchive struct {
Aid string `json:"aid"`
Typename string `json:"typename"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Play interface{} `json:"play"`
Review int32 `json:"review"`
VideoReview int32 `json:"video_review"`
Favorites int32 `json:"favorites"`
Mid int64 `json:"mid"`
Author string `json:"author"`
Description string `json:"description"`
Create string `json:"create"`
Pic string `json:"pic"`
Coins int32 `json:"coins"`
Duration string `json:"duration"`
Badgepay bool `json:"badgepay"`
Rights arcmdl.Rights `json:"rights"`
}
// RankRecommend rank recommend data struct
type RankRecommend struct {
Code int `json:"code"`
Pages int `json:"pages"`
Num int `json:"num"`
List []*IndexArchive `json:"list"`
}
// RankRegion rank region data struct
type RankRegion struct {
Hot *RankDetail `json:"hot"`
HotOriginal *RankDetail `json:"hot_original"`
}
// RankDetail rank region detail struct
type RankDetail struct {
Note string `json:"note"`
Code int `json:"code"`
Page int `json:"page"`
Num int `json:"num"`
List []*RegionArchive `json:"list"`
}
// RegionArchive bigdata region rank archive struct
type RegionArchive struct {
Aid string `json:"aid"`
Typename string `json:"typename"`
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Play interface{} `json:"play"`
Review int32 `json:"review"`
VideoReview int32 `json:"video_review"`
Favorites int32 `json:"favorites"`
Mid int64 `json:"mid"`
Author string `json:"author"`
Description string `json:"description"`
Create string `json:"create"`
Pic string `json:"pic"`
Coins int32 `json:"coins"`
Duration string `json:"duration"`
Badgepay bool `json:"badgepay"`
Pts int `json:"pts"`
Rights arcmdl.Rights `json:"rights"`
}
// TagArchive bigdata region rank archive struct
type TagArchive struct {
Title string `json:"title"`
Author string `json:"author"`
Description string `json:"description"`
Pic string `json:"pic"`
Play string `json:"play"`
Favorites string `json:"favorites"`
Mid string `json:"mid"`
Review string `json:"review"`
CreatedAt string `json:"created_at"`
VideoReview string `json:"video_review"`
Coins string `json:"coins"`
Duration string `json:"duration"`
Aid int64 `json:"aid"`
Pts int `json:"pts"`
Trend int `json:"trend"`
Rights arcmdl.Rights `json:"rights"`
}
// RankData rank service return data
type RankData struct {
Note string `json:"note"`
List []*RankArchive `json:"list"`
}
// RankNewArchive rank archive new struct
type RankNewArchive struct {
*NewArchive
*RankStat
Others []*NewArchive `json:"others,omitempty"`
}
// RankNew rank new struct.
type RankNew struct {
Note string `json:"note"`
List []*RankNewArchive `json:"list"`
}
// NewArchive new rank archive struct
type NewArchive struct {
Aid int64 `json:"aid"`
Score int `json:"score"`
}
// RankStat rank archive stat.
type RankStat struct {
Play int32 `json:"play"`
Coin int32 `json:"coin"`
Danmu int32 `json:"danmu"`
}
// Custom game custom struct
type Custom struct {
Aid int64 `json:"aid"`
Title string `json:"title"`
Pic string `json:"pic"`
Note string `json:"note"`
Pos int `json:"-"`
URL string `json:"url"`
Type string `json:"type"`
}

View File

@@ -0,0 +1,43 @@
package model
import (
arcmdl "go-common/app/service/main/archive/api"
)
// Bnj2019 .
type Bnj2019 struct {
*Bnj2019View
Elec *ElecShow `json:"elec"`
Related []*Bnj2019Related `json:"related"`
ReqUser *ReqUser `json:"req_user"`
}
// Bnj2019View .
type Bnj2019View struct {
*arcmdl.Arc
Pages []*arcmdl.Page `json:"pages"`
}
// Bnj2019Related .
type Bnj2019Related struct {
*arcmdl.Arc
Pages []*arcmdl.Page `json:"pages"`
}
// ReqUser req user.
type ReqUser struct {
Attention bool `json:"attention"`
Favorite bool `json:"favorite"`
Like bool `json:"like"`
Dislike bool `json:"dislike"`
Coin int64 `json:"coin"`
}
// Timeline bnj timeline.
type Timeline struct {
Name string `json:"name"`
Start int64 `json:"start"`
End int64 `json:"end"`
Cover string `json:"cover"`
H5Cover string `json:"h5_cover"`
}

View File

@@ -0,0 +1,13 @@
package model
import (
v1 "go-common/app/service/main/archive/api"
)
// CoinArc coin archive.
type CoinArc struct {
*v1.Arc
Coins int64 `json:"coins"`
Time int64 `json:"time"`
IP string `json:"ip"`
}

View File

@@ -0,0 +1,24 @@
package model
import "encoding/json"
// ElecShow elec show
type ElecShow struct {
ShowInfo *ShowInfo `json:"show_info"`
AvCount int `json:"av_count"`
Count int `json:"count"`
TotalCount int64 `json:"total_count"`
SpecialDay int `json:"special_day"`
DisplayNum int `json:"display_num"`
AvList json.RawMessage `json:"av_list,omitempty"`
AvUser json.RawMessage `json:"av_user,omitempty"`
List json.RawMessage `json:"list,omitempty"`
User json.RawMessage `json:"user,omitempty"`
}
// ShowInfo show info
type ShowInfo struct {
Show bool `json:"show"`
State int8 `json:"state"`
Reason string `json:"reason,omitempty"`
}

View File

@@ -0,0 +1,21 @@
package model
// Feedback feedback param struct.
type Feedback struct {
Aid int64
Mid int64
TagID int64
Buvid string
Content *Content
Browser string
Version string
Email string
QQ string
Other string
}
// Content Content struct.
type Content struct {
Reason string `json:"reason"`
URL string `json:"url"`
}

View File

@@ -0,0 +1,39 @@
package model
import "go-common/library/time"
// HelpList help list
type HelpList struct {
Last bool `json:"last"`
ParentTypeID string `json:"parentTypeId"`
QuestionTypeDesc string `json:"questionTypeDesc"`
QuestionTypeID string `json:"questionTypeId"`
QuestionTypeName string `json:"questionTypeName"`
QuestionTypeStatus int `json:"questionTypeStatus"`
SortNo int `json:"sortNo"`
TypeLevel int `json:"typeLevel"`
}
// HelpDeatil help deatil and search
type HelpDeatil struct {
AllTypeName string `json:"allTypeName"`
AnswerDesc string `json:"answerDesc"`
AnswerFlag int `json:"answerFlag"`
AnswerID string `json:"answerId"`
AnswerImg string `json:"answerImg"`
AnswerTxt string `json:"answerTxt"`
AuditStatus int `json:"auditStatus"`
CompanyID string `json:"companyId"`
CreateID string `json:"createId"`
CreateTime time.Time `json:"createTime"`
DocID string `json:"docId"`
LinkFlag int `json:"linkFlag"`
MatchFlag int `json:"matchFlag"`
QuestionID string `json:"questionId"`
QuestionTitle string `json:"questionTitle"`
QuestionTypeID string `json:"questionTypeId"`
QuestionTypeName string `json:"questionTypeName"`
UpdateID string `json:"updateId"`
UpdateTime time.Time `json:"updateTime"`
UsedFlag int `json:"usedFlag"`
}

View File

@@ -0,0 +1,10 @@
package model
// IndexIcon index icon struct.
type IndexIcon struct {
ID int64 `json:"id"`
Title string `json:"title"`
Links []string `json:"links"`
Icon string `json:"icon"`
Weight int `json:"weight"`
}

View File

@@ -0,0 +1,52 @@
package model
import (
account "go-common/app/service/main/account/model"
)
// NavResp struct of nav api response
type NavResp struct {
IsLogin bool `json:"isLogin"`
//AccessStatus int `json:"accessStatus"`
//DueRemark string `json:"dueRemark"`
EmailVerified int `json:"email_verified"`
Face string `json:"face"`
LevelInfo struct {
Cur int `json:"current_level"`
Min int `json:"current_min"`
NowExp int `json:"current_exp"`
NextExp interface{} `json:"next_exp"`
} `json:"level_info"`
Mid int64 `json:"mid"`
MobileVerified int `json:"mobile_verified"`
Coins float64 `json:"money"`
Moral float32 `json:"moral"`
OfficialVerify struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"officialVerify"`
Pendant account.PendantInfo `json:"pendant"`
Scores int `json:"scores"`
Uname string `json:"uname"`
VipDueDate int64 `json:"vipDueDate"`
VipStatus int `json:"vipStatus"`
VipType int `json:"vipType"`
VipPayType int32 `json:"vip_pay_type"`
Wallet *Wallet `json:"wallet"`
HasShop bool `json:"has_shop"`
ShopURL string `json:"shop_url"`
AllowanceCount int `json:"allowance_count"`
}
// FailedNavResp struct of failed nav response
type FailedNavResp struct {
IsLogin bool `json:"isLogin"`
}
// Wallet struct.
type Wallet struct {
Mid int64 `json:"mid"`
BcoinBalance float32 `json:"bcoin_balance"`
CouponBalance float32 `json:"coupon_balance"`
CouponDueTime int64 `json:"coupon_due_time"`
}

Some files were not shown because too many files have changed in this diff Show More