Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/interface/main/account/cmd:all-srcs",
"//app/interface/main/account/conf:all-srcs",
"//app/interface/main/account/dao/account:all-srcs",
"//app/interface/main/account/dao/geetest:all-srcs",
"//app/interface/main/account/dao/passport:all-srcs",
"//app/interface/main/account/dao/realname:all-srcs",
"//app/interface/main/account/dao/relation:all-srcs",
"//app/interface/main/account/dao/reply:all-srcs",
"//app/interface/main/account/dao/usersuit:all-srcs",
"//app/interface/main/account/dao/vip:all-srcs",
"//app/interface/main/account/http:all-srcs",
"//app/interface/main/account/model:all-srcs",
"//app/interface/main/account/service/card:all-srcs",
"//app/interface/main/account/service/coupon:all-srcs",
"//app/interface/main/account/service/geetest:all-srcs",
"//app/interface/main/account/service/member:all-srcs",
"//app/interface/main/account/service/passport:all-srcs",
"//app/interface/main/account/service/point:all-srcs",
"//app/interface/main/account/service/realname:all-srcs",
"//app/interface/main/account/service/relation:all-srcs",
"//app/interface/main/account/service/usersuit:all-srcs",
"//app/interface/main/account/service/vip:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,511 @@
#### Version 1.74.0
> 1. 大会员福利社
#### Version 1.73.0
> 1. 更换大会员落地页banner位接口
> 2. 新增购买页资源位
#### Version 1.72.0
> 1. 代金券【最优选择+兑换功能】
#### Version 1.71.2
> 1. 修改昵称接口文案修改
#### Version 1.71.1
> 1. vip add open limit
#### Version 1.71.0
> 1. 官方认证单月提交限制
#### Version 1.70.0
> 1. 大会员元旦活动
#### Version 1.69.1
> 1. fix coupon/usable,coupon/list接口 参数bug
#### Version 1.69.0
> 1. /pendant/equip 接口添加挂件来源source字段
> 2. rpcusSvc.Equip 接口添加挂件来源source字段
#### Version 1.68.0
> 1. 大会员代金券限制商品
#### Version 1.67.2
> 1. 去掉特色菜&红包活动时间限制
#### Version 1.67.1
> 1. 去掉联合会员对外接口时间限制
#### Version 1.67.0
> 1. 大会员-饿了么&bilibili联合会员
#### Version 1.66.5
> 1. 修正 tag 推荐用户数据的数量
#### Version 1.66.0
> 1. 增加根据 tag 推荐用户的 API
#### Version 1.65.0
> 1. 增加/realname/v2/card/types 返回删除 “护照(境外签发)” 的实名证件列表
#### Version 1.64.3
> 1. 实名认证IOS粉证件列表返回兼容数据
#### Version 1.64.2
> 1. location Info2接口废弃 换Info接口
> 2. 去除 ip 包依赖
#### Version 1.64.1
> 1. remove vip/unfrozen
#### Version 1.64.0
> 1. 价格面板v8
> 2. 包年包季
> 3. 审核态面板
#### Version 1.63.1
> 1. vip unfreeze
#### Version 1.63.0
#### Version 1.62.0
> 1. 官方认证增加提交来源字段
#### Version 1.61.2
> 1. update vip api unfrozen method
#### Version 1.61.1
> 1. 修复实名认证打码逻辑
#### Version 1.61.0
> 1. 增加共同关注接口
#### Version 1.60.0
> 1. 大会员支付结果客制化面板
#### Version 1.59.2
> 1. 购买邀请码加入极验
> 2. 添加clientType字段
#### Version 1.58.1
> 1. 挂件装备接口传参变更
#### Version 1.57.4
> 1. 修正来自 passport 的 -617 错误展示
> 2. setup dao.account unit test
#### Version 1.57.3
> 1. 以 multipart 方式 parse form
#### Version 1.57.2
> 1. 兼容方式获取实名认证图片
#### Version 1.57.1
> 1. 实名认证图片上传日志
#### Version 1.57.0
> 1. 冻结vip解冻接口
#### Version 1.56.0
> 1. 卡片网关
#### Version 1.55.0
> 1. 兼容方式获取上传的头像
> 2. 实名照片上传使用formfile
> 3. 实名申请前端传入参数对齐
#### Version 1.54.2
> 1. 恢复实名照片上传formvalue
#### Version 1.54.1
> 1. 增加芝麻防刷配置项
#### Version 1.54.0
> 1. 增加芝麻实名认证
#### Version 1.53.1
> 1. add ip check log
#### Version 1.53.0
> 1. vip 面板默认选中
#### Version 1.52.0
> 1. vip 权益增加ID字段
#### Version 1.51.0
> 1. 官方认证集成商业产品部逻辑
#### Version 1.50.0
> 1. vip add map ip
#### Version 1.49.0
> 1. vip 新增对外直充接口
#### Version 1.48.3
> 1. 新增挂件红点提醒
> 2. test backround
#### Version 1.48.2
> 1. 增加批量关注错误
#### Version 1.48.1
> 1. 添加挂件装备网关接口
#### Version 1.48.0
> 1. 粉丝提醒功能
#### Version 1.47.3
> 1. 推荐理由不再拼粉丝数
#### Version 1.47.2
> 1. 在 member-job 延迟删缓存
#### Version 1.47.1
> 1. 聚合延迟删除缓存消息
#### Version 1.47.0
> 1. 修改昵称时延迟删除缓存
#### Version 1.46.3
> 1. 修正无推荐理由时的理由展示
#### Version 1.46.2
> 1. 加入辅助清理缓存接口
#### Version 1.46.1
> 1. add reply history oid string field
#### Version 1.46.0
> 1. default choose panel
#### 1.45.0
> 1. AppStore购买页
#### Version 1.44.0
> 1. 粉丝成就 API
#### Version 1.43.0
> 1. 大会员权益
#### Version 1.42.1
> 1. 修复 verify 没有传输 ip
#### Version 1.42.0
> 1. 大会员联名业务
#### Version 1.41.0
> 1. 空白关注列表出推荐 API
#### Version 1.40.5
> 1. add point gateway
#### Version 1.40.4
> 1. unicom search codeopen
#### Version 1.40.3
> 1. 删除remoteIP方法
#### Version 1.40.2
> 1. coupon list resp name
#### Version 1.40.1
> 1. 迁移coupon外网接口
> 2. 解锁券使用rpc -> http
#### Version 1.40.0
> 1. fix vip panel_type code reduction
#### Version 1.39.0
> 1. 代金券
#### Version 1.38.1
> 1. 新增好友赠送平台
#### Version 1.38.0
> 1. 批量关注接口
#### Version 1.37.2
> 1. fix relation tag
#### Version 1.37.1
> 1. update bind tag
#### Version 1.37.0
> 1. remove useless codes
> 2. update bind
#### Version 1.36.1
> 1. 添加审核列表接口增加传递extra字段
#### Version 1.36.0
> 1. 使用 Auth 和 Verify
#### Version 1.35.1
> 1. remove useless model
#### Version 1.35.0
> 1. vip panel add plat check
#### Version 1.34.3
> 1. update vip panel
#### Version 1.34.2
> 1. update medal model
#### Version 1.34.1
> 1. 修复 realname mkdir 权限
#### Version 1.34.0
> 1. 追番列表增加开通提醒
#### Version 1.33.8
> 1. 修正粉丝数只显示 1000 的问题
#### Version 1.33.7
> 1. 修改昵称,判断昵称是否已存在
#### Version 1.33.6
> 1. 昵称,头像,签名增加校验手机号开关
#### Version 1.33.5
> 1. 修改头像不需要校验手机号
#### Version 1.33.4
> 1. 修复用户行为没有初始化的问题
#### Version 1.33.3
> 1. 修复修改昵称行为日志丢失问题
#### Version 1.33.2
> 1. 修复web端昵称修改bug
#### Version 1.33.1
> 1. 修复修改头像日志丢失的问题
#### Version 1.33.0
> 1. 修改昵称调用go相关服务
#### Version 1.32.3
> 1. 增加修改昵称 web 接口
#### Version 1.32.2
> 1. 修复 relaiton follower 空指针
#### Version 1.32.1
> 1. 找不到用户信息时不展示在关系列表里
#### Version 1.32.0
> 1. add vip panel info.
#### Version 1.31.5
> 1. 监控美国,加拿大手机号信息修改
#### Version 1.31.4
> 1. 监控美国,加拿大地区信息修改
#### Version 1.31.3
> 1. 监控香港地区信息修改
#### Version 1.31.2
> 1. 修复图片上传
#### Version 1.31.1
> 1. fix update face
#### Version 1.31.0
> 1. 修改头像接口调用member写新数据库
#### Version 1.30.4
> 1. add log
#### Version 1.30.3
> 1. fix web updateFace
#### Version 1.30.2
> 1. fix web updateFace
#### Version 1.30.1
> 1. 优化realname
#### Version 1.30.0
> 1. 去除全局热门推荐功能
#### Version 1.23.0
> 1. 官方认证去除播放数条件
#### Version 1.22.11
> 1. 小黄条配置
#### Version 1.22.10
> 1. 签名可以直接改为空
#### Version 1.22.1
> 1. 签名修改直接调 member
#### Version 1.21.0
> 1. change pendant url.
#### Version 1.20.1
> 1. add reward interface.
#### Version 1.20.0
> 1. add pendant api.
> 2. fix vipGet api.
#### Version 1.19.3
> 1. config supervisor on update api
#### Version 1.19.2
> 1. fix moral Log
#### Version 1.19.1
> 1. filter login log from internal
#### Version 1.19.0
> 1. add realname api
#### Version 1.18.3
> 1. fix loginLog interface.
#### Version 1.18.2
> 1. fix coinLog Delta.
#### Version 1.18.1
> 1. fix coinLog interface.
#### Version 1.18.0
> 1. add sms antispam
#### Version 1.17.1
> 1. add web updateBirthday interface
#### Version 1.17.0
> 1. add vip code verify and open
#### Version 1.17.2
> 1. changeUname fix response message.
#### Version 1.17.1
> 1. official submit
#### Version 1.17.0
> 1. refine notify
#### Version 1.16.2
> 1. fix update face
#### Version 1.16.1
> 1. initial bm identify
#### Version 1.16.0
> 1. migrate to bm
#### Version 1.15.8
> 1. fix update setting.
#### Version 1.15.7
> 1. web user info delete detail info.
> 2. move identify to account interface
#### Version 1.15.6
> 1.change updateSetting to call java.
#### Version 1.15.6
> 1. remove member notice rpc to account.
#### Version 1.15.5
> 1.使用新的 account service 和 member service
> 1.对外 API 全改为老的官方认证结构
#### Version 1.15.4
> 1.add pendant equip api.
#### Version 1.15.3
> 1.move to main
#### Version 1.15.2
> 1.增加app和web个人资料相关接口
#### Version 1.15.1
> 1.notice add platform&build check
#### Version 1.15.0
> 1.添加实名认证查询接口/identify/info
#### Version 1.14.2
> 1.relation 使用 account-service v7
#### Version 1.14.1
> 1.使用account-service v7
#### Version 1.14.0
> 1.关注推荐功能
> 2.remove statsd
#### Version 1.13.0
> 1.添加total字段
#### Version 1.12.1
> 1.返回空数组处理
#### Version 1.12.0
> 1.添加b+ special接口
#### Version 1.11.0
> 1.change part ut to convey
> 2.fix data race for fetching multi info in concurrency
#### Version 1.10.1
> 1.修复未登录的错误返回
#### Version 1.10.0
> 1.增加MID查询用户信息
#### Version 1.9.2
> 1.关系链:黑名单列表加入分页支持,加入total 字段
#### Version 1.9.1
> 1.关系链:黑名单列表加入分页支持
#### Version 1.8.0
> 1.add usersuit apis: /x/member/invite/stat, /x/member/invite/buy, /x/member/invite/apply
#### Version 1.7.1
> 1.关注分组增加对移动端的支持,特别关注增加默认值
#### Version 1.7.0
> 1.关注分组增加对移动端的支持,区分默认分组、特别关注、自定义分组、全部关注数
#### Version 1.6.0
> 1.关注提示开关
#### Version 1.5.1
> 1.删除/x/member/up/info接口
#### Version 1.5.0
> 1.关注分组增加对移动端的支持,区分默认分组、特别关注、自定义分组
#### Version 1.4.0
> 1.关注分组
#### Version 1.3.0
> 1.移动端获取异地登录、实名制提醒
#### Version 1.2.0
> 1.实名制提示
> 2.获取UP主权限
#### Version 1.1.0
> 1.增加关注列表asc排序
#### Version 1.0.2
> 1.fix time type
#### Version 1.0.1
> 1.del no use config item
#### Version 1.0.0
> 1.从member interface迁移relation和member业务

View File

@@ -0,0 +1,12 @@
# Owner
wanghuan01
zhoujiahui
zhaogangtao
chenjianrong
zhoujixiang
# Author
all
# Reviewer
all

View File

@@ -0,0 +1,14 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- chenjianrong
- wanghuan01
- zhaogangtao
- zhoujiahui
- zhoujixiang
labels:
- interface
- interface/main/account
- main
options:
no_parent_owners: true

View File

@@ -0,0 +1,44 @@
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 = ["account-interface-example.toml"],
importpath = "go-common/app/interface/main/account/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/http:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
"//library/queue/databus/report: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,288 @@
[bm]
[bm.inner]
addr = "0.0.0.0:6951"
maxListen = 1000
timeout = "1s"
[httpClient]
[httpClient.normal]
dial = "500ms"
timeout = "1s"
keepAlive = "60s"
timer = 10
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
[httpClient.normal.host]
"http://cm.bilibili.co" = {key = "test",secret = "e6c4c252dc7e3d8a90805eecd7c73396"}
[httpClient.normal.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[httpClient.slow]
dial = "500ms"
timeout = "1s"
keepAlive = "60s"
timer = 10
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
[httpClient.slow.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[rpcClient2]
[rpcClient2.member]
color = "group1"
timeout = "150ms"
[rpcClient2.account]
color = "group2"
timeout = "200ms"
[rpcClient2.archive]
timeout = "100ms"
[rpcClient2.relation]
token="test"
timeout = "1s"
[rpcClient2.usersuit]
timeout = "1s"
[rpcClient2.article]
timeout = "1s"
[rpcClient2.up]
timeout = "1s"
group = "test"
[rpcClient2.passport]
timeout = "1s"
[rpcClient2.coin]
timeout = "1s"
[rpcClient2.location]
timeout = "1s"
[rpcClient2.secure]
timeout = "1s"
[rpcClient2.vip]
timeout = "200ms"
[app]
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
[antispam]
on=true
second=2
n=1
hour=12
m=500
[antispam.redis]
name = "member/account-interface"
proto = "tcp"
addr = "172.16.33.54:6379"
active = 5
idle = 5
dialTimeout = "90ms"
readTimeout = "100ms"
writeTimeout = "100ms"
idleTimeout = "80s"
expire = "24h"
[smsantispam]
on=true
second=60
n=1
hour=1
m=10
[smsantispam.redis]
name = "member/member-interface"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[vipantispam]
on=true
second=1
n=2
hour=1
m=10
[vipantispam.redis]
name = "member/member-interface"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[host]
acccom = "http://account.bilibili.com"
accco = "http://uat-account.bilibili.co"
passport = "http://passport.bilibili.co"
api = "http://api.bilibili.co"
vip = "http://vip.bilibili.co"
www = "http://www.bilibili.com"
search = "http://s.search.bilibili.co"
cm = "http://cm.bilibili.co"
passportCom = "https://passport.bilibili.com"
[VipProperty]
CodeOpenwhiteIPMap={"b2cf4e9dbe9fd2e3"=["111.203.12.97","111.203.12.98","123.125.99.176","123.125.99.177","123.125.99.178","123.125.99.179","123.125.99.180"],"6e8687402f1ab860"=["219.135.155.76","134.175.201.88"]}
EleOAuthURI="https://open.faas.ele.me/docs/8cd9ba96ee0a53a1fd2c6d84d15727eebd8aa054"
EleConsumerKey="4400479257"
EleOAuthCallBackURI="https://api.bilibili.com/x/oauth2/v1/callback"
ActivityURI="https://uat-www.bilibili.com/blackboard/preview/activity-E2yZx8RLI.html?time=1545580800000"
ActStartTime = 1144488082
ActEndTime = 1154488082
[VipProperty.OAuthClient]
key = "ad4bb9b8f5d9d4a7"
secret = "6912080d78d58be7cb94f57d50d438f6"
[accmemcache]
name = "account-interface"
proto = "tcp"
addr = "172.18.33.61:11212"
idle = 5
active = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
[realname]
dataDir = "/idenfiles"
imageExpire = "1m"
alipayAntispamTTL = 86400
alipayAntispamThreshold = 0
[realname.geetest]
registerURL = "http://api.geetest.com/register.php"
validateURL = "http://api.geetest.com/validate.php"
captchaID = "e81f58b498a0106eb92b985aef20a15f"
privateKey = "a6ccb3f6865c9fabaaa57c8cee5a7609"
[realname.alipay]
gateway = "https://openapi.alipay.com/gateway.do"
appID = "2018062060353784"
[[realname.channel]]
name = "main"
flag = true
[[realname.channel]]
name = "alipay"
flag = true
[nickFreeAppKeys]
aaaa= ""
[SMSAntispam]
on=true
second=2
n=1
hour=12
m=5
[SMSAntispam.redis]
name = "answer"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 100
active = 100
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[bfs]
timeout="500ms"
maxFileSize=8388608
bucket="b"
url="http://bfs.bilibili.co/bfs/"
method="PUT"
key="25bf7f1ec06cf75a"
secret="dba1dc9d43472cced48b9dc9816a46"
faceBucket="face"
facekey="792d70f16e958493"
facesecret="08525fe929bdb26c3a6009afd7318f"
[facebfs]
timeout="500ms"
maxFileSize=8388608
url="http://bfs.bilibili.co/bfs/"
method="PUT"
bucket="face"
key="792d70f16e958493"
secret="08525fe929bdb26c3a6009afd7318f"
[faceantispam]
on=true
second=60
n=10
hour=1
m=100
[faceantispam.redis]
name = "member/account-interface"
proto = "unix"
addr = "/tmp/uat-redisantispam-redis.sock"
active = 10
idle = 1
dialTimeout = "90ms"
readTimeout = "100ms"
writeTimeout = "100ms"
idleTimeout = "80s"
expire = "24h"
[switch]
updatePropertyPhoneRequired = true
[geetest]
[geetest.PC]
captchaId = "a703e7d11eda930ca87be02c1a80ff97"
privateKey = "df5eacf78b4afc79a052f199939e946a"
[geetest.H5]
captchaId = "bf666f87e5cca24ddb4c1dbeb70912b8"
privateKey = "d1e0bc5eadc754f8cd522c6fed5e175d"
[Account]
RemoveLoginLogCIDR = ["222.73.196.18/28", "121.46.231.66/29", "61.130.181.50/28", "61.244.26.110/30", "103.36.115.65/32", "114.134.80.196/32", "218.189.16.245/32", "202.153.91.146/32", "202.153.91.76/32", "202.153.91.97/32", "103.193.127.56/32", "116.211.6.86/30", "123.124.149.6/32", "36.112.7.18/32"]
[accountnotify]
key = "4ba46ba31f9a44ef"
secret = "e4c5a7fce28695209e6b4f0af8cf91c5"
group = "AccountNotify-MainAccount-P"
topic = "AccountNotify-T"
action = "pub"
buffer = 2048
name = "account-notify-job/databus"
proto = "tcp"
addr = "172.18.33.50:6205"
idle = 1
active = 1
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[BatchRelAntispam]
on=true
second=2
n=1
hour=1
m=10
[BatchRelAntispam.redis]
name = "member/account-interface"
proto = "unix"
addr = "/tmp/uat-redisantispam-redis.sock"
active = 10
idle = 1
dialTimeout = "90ms"
readTimeout = "100ms"
writeTimeout = "100ms"
idleTimeout = "80s"
expire = "24h"
[vipThirdVerifyConfig]
authAppkeyMap = {"7xio6i8k93i5e4er"="lc1cqoasuxpeodvkwg5xkemell2eavwa"}

View File

@@ -0,0 +1,48 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/http"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/trace"
"go-common/library/queue/databus/report"
)
func main() {
flag.Parse()
// init conf,log,trace,stat,perf.
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Xlog)
defer log.Close()
trace.Init(conf.Conf.Tracer)
defer trace.Close()
// report init
report.InitUser(conf.Conf.Report)
// service init
ecode.Init(conf.Conf.Ecode)
http.Init(conf.Conf)
// signal handler
log.Info("account-interface start")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("account-interface get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("account-interface exit")
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,47 @@
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/account/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/vip/verify:go_default_library",
"//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/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/antispam:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/supervisor: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/queue/databus: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,267 @@
package conf
import (
"errors"
"flag"
vipverify "go-common/app/service/main/vip/verify"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/antispam"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/supervisor"
"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/queue/databus"
"go-common/library/time"
"github.com/BurntSushi/toml"
)
// Conf global variable.
var (
Conf = &Config{}
confPath string
client *conf.Client
)
// Config struct of conf.
type Config struct {
Xlog *log.Config
Tracer *trace.Config
BM *HTTPServers
AuthN *auth.Config
Verify *verify.Config
RPCClient2 *RPC
HTTPClient *HTTPClient
App *bm.App
Ecode *ecode.Config
Antispam *antispam.Config
BatchRelAntispam *antispam.Config
SMSAntispam *antispam.Config
FaceAntispam *antispam.Config
VIPAntispam *antispam.Config
Host *Host
BFS *BFS
FaceBFS *BFS
AccMemcache *memcache.Config
AccRedis *redis.Config
Realname *Realname
Supervisor *supervisor.Config
NickFreeAppKeys map[string]string
Report *databus.Config
Switch *Switch
Vipproperty *VipProperty
AccountNotify *databus.Config
CardClient *warden.ClientConfig
Geetest *Geetest
Account *Account
VipThirdVerifyConfig *vipverify.Config
VipClient *warden.ClientConfig
CouponClient *warden.ClientConfig
}
// Account is
type Account struct {
RemoveLoginLogCIDR []string
}
// Geetest is
type Geetest struct {
PC GeetestConfig
H5 GeetestConfig
}
// GeetestConfig conf.
type GeetestConfig struct {
CaptchaID string
PrivateKEY string
}
// VipProperty .
type VipProperty struct {
CodeOpenwhiteIPMap map[string][]string
OfficialMid int64
OAuthClient *bm.ClientConfig
EleOAuthURI string
EleConsumerKey string
EleOAuthCallBackURI string
ActivityURI string
ActStartTime int64
ActEndTime int64
AssociateWhiteIPMap map[string][]string
AssociateWhiteMidMap []int64
AssociateWhiteOutOpenIDMap []string
}
// Realname .
type Realname struct {
DataDir string
ImageExpire time.Duration
AlipayAntispamTTL int32
AlipayAntispamThreshold int
Geetest *struct {
RegisterURL string
ValidateURL string
CaptchaID string
PrivateKey string
}
Alipay *struct {
Gateway string
AppID string
}
Channel []*struct {
Name string
Flag bool
}
}
// RsaPub .
func RsaPub() (key string) {
if client == nil {
return ""
}
key, _ = client.Value("realname.rsa.pub")
return
}
// RsaPriv .
func RsaPriv() (key string) {
if client == nil {
return ""
}
key, _ = client.Value("realname.rsa.priv")
return
}
// AlipayPub .
func AlipayPub() (key string) {
if client == nil {
return ""
}
key, _ = client.Value("realname.alipay.pub")
return
}
// AlipayBiliPriv bilibili generate rsa private key
func AlipayBiliPriv() (key string) {
if client == nil {
return ""
}
key, _ = client.Value("realname.alipay.bili.priv")
return
}
// BFS bfs config
type BFS struct {
Timeout time.Duration
MaxFileSize int
URL string
Method string
Bucket string
Key string
Secret string
}
// HTTPServers Http Servers
type HTTPServers struct {
Inner *bm.ServerConfig
// Local *bm.ServerConfig
}
// Host host.
type Host struct {
AccCom string
AccCo string
Passport string
API string
Vip string
WWW string
Search string
CM string
PassportCom string
}
// RPC config
type RPC struct {
Relation *rpc.ClientConfig
Member *rpc.ClientConfig
Account *rpc.ClientConfig
Vip *rpc.ClientConfig
Usersuit *rpc.ClientConfig
Archive *rpc.ClientConfig
UP *rpc.ClientConfig
Article *rpc.ClientConfig
PassPort *rpc.ClientConfig
Coin *rpc.ClientConfig
Location *rpc.ClientConfig
Secure *rpc.ClientConfig
Filter *rpc.ClientConfig
Coupon *rpc.ClientConfig
Point *rpc.ClientConfig
Resource *rpc.ClientConfig
}
// HTTPClient conf.
type HTTPClient struct {
Normal *bm.ClientConfig
Slow *bm.ClientConfig
}
// Switch is.
type Switch struct {
UpdatePropertyPhoneRequired bool
}
func configCenter() (err error) {
if client, err = conf.New(); err != nil {
panic(err)
}
if err = load(); err != nil {
return
}
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
}
func init() {
flag.StringVar(&confPath, "conf", "", "config path")
}
// Init init conf.
func Init() (err error) {
if confPath == "" {
return configCenter()
}
_, err = toml.DecodeFile(confPath, &Conf)
return
}

View File

@@ -0,0 +1,69 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"account_test.go",
"bfs_test.go",
"commercial_test.go",
"official_test.go",
"settings_test.go",
"sms_test.go",
"vip_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"bfs.go",
"commercial.go",
"official.go",
"settings.go",
"sms.go",
"vip.go",
],
importpath = "go-common/app/interface/main/account/dao/account",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//library/cache/memcache: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/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,45 @@
package account
import (
"go-common/app/interface/main/account/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
bm "go-common/library/net/http/blademaster"
xhttp "net/http"
"time"
)
// consts
const (
_cmIsBusinessAccount = "/basc/api/open_api/v1/up/business_account/is_sign_up"
_cmBusinessAccountInfo = "/basc/api/open_api/v1/up/bus_account_info"
)
// Dao dao
type Dao struct {
c *conf.Config
client *bm.Client
accCom string
accCo string
vipHost string
smsSendURI string
bfsClient *xhttp.Client
mc *memcache.Pool
redis *redis.Pool
}
// New new
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Normal),
accCom: c.Host.AccCom,
accCo: c.Host.AccCo,
vipHost: c.Host.Vip,
smsSendURI: c.Host.API + _smsSendURI,
bfsClient: &xhttp.Client{Timeout: time.Duration(c.BFS.Timeout)},
mc: memcache.NewPool(c.AccMemcache),
redis: redis.NewPool(c.AccRedis),
}
return
}

View File

@@ -0,0 +1,35 @@
package account
import (
"flag"
"go-common/app/interface/main/account/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.account-interface")
flag.Set("conf_token", "967eef77ad40b478234f11b0d489d6d6")
flag.Set("tree_id", "3815")
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/account-interface-example.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}

View File

@@ -0,0 +1,75 @@
package account
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"net/http"
"strconv"
"time"
"go-common/app/interface/main/account/conf"
"go-common/library/ecode"
"go-common/library/log"
"github.com/pkg/errors"
)
// UploadImage upload bfs.
func (d *Dao) UploadImage(c context.Context, fileType string, bs []byte, bfs *conf.BFS) (location string, err error) {
url := bfs.URL + bfs.Bucket + "/"
req, err := http.NewRequest(bfs.Method, url, bytes.NewBuffer(bs))
if err != nil {
log.Error("account-interface: http.NewRequest error (%v) | fileType(%s)", err, fileType)
return
}
expire := time.Now().Unix()
authorization := authorize(bfs.Key, bfs.Secret, bfs.Method, bfs.Bucket, expire)
req.Header.Set("Host", url)
req.Header.Add("Date", fmt.Sprint(expire))
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", fileType)
// timeout
ctx, cancel := context.WithTimeout(c, time.Duration(d.c.BFS.Timeout))
req = req.WithContext(ctx)
defer cancel()
resp, err := d.bfsClient.Do(req)
if err != nil {
log.Error("account-interface: d.Client.Do error(%v) | url(%s)", err, url)
err = ecode.BfsUploadServiceUnavailable
return
}
if resp.StatusCode != http.StatusOK {
log.Error("account-interface: Upload http.StatusCode nq http.StatusOK (%d) | url(%s)", resp.StatusCode, d.c.BFS.URL)
err = errors.New("Upload failed")
return
}
header := resp.Header
code := header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
log.Error("account-interface: strconv.Itoa err, code(%s) | url(%s)", code, url)
err = errors.New("Upload failed")
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("%s\n%s\n\n%d\n", 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,39 @@
package account
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountUploadImage(t *testing.T) {
var (
c = context.Background()
fileType = "jpg"
bs = []byte("dangerous")
)
convey.Convey("UploadImage", t, func(ctx convey.C) {
location, err := d.UploadImage(c, fileType, bs, d.c.BFS)
ctx.Convey("Then err should be nil.location should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(location, convey.ShouldNotBeNil)
})
})
}
func TestAccountauthorize(t *testing.T) {
var (
key = ""
secret = ""
method = ""
bucket = ""
expire = int64(0)
)
convey.Convey("authorize", t, 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,149 @@
package account
import (
"context"
"crypto/md5"
"encoding/hex"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/account/model"
"go-common/library/log"
"go-common/library/xstr"
"github.com/pkg/errors"
)
// CommercialSign is
// 商业产品部专用签名
func CommercialSign(params url.Values) (query string, err error) {
if len(params) == 0 {
return
}
if params.Get("appkey") == "" {
err = errors.New("utils http get must have parameter appkey")
return
}
if params.Get("appsecret") == "" {
err = errors.New("utils http get must have parameter appsecret")
return
}
if params.Get("sign") != "" {
err = errors.New("utils http get must have not parameter sign")
return
}
// sign
secret := params.Get("appsecret")
params.Del("appsecret")
tmp := params.Encode()
if strings.IndexByte(tmp, '+') > -1 {
tmp = strings.Replace(tmp, "+", "%20", -1)
}
mh := md5.Sum([]byte(tmp + secret))
params.Set("sign", hex.EncodeToString(mh[:]))
query = params.Encode()
return
}
func (d *Dao) isBusinessAccount(ctx context.Context, mids []int64) (map[int64]bool, error) {
cm := d.c.HTTPClient.Normal.Host[d.c.Host.CM]
params := url.Values{}
params.Set("mids", xstr.JoinInts(mids))
params.Set("appkey", cm.Key)
params.Set("appsecret", cm.Secret)
params.Set("ts", strconv.FormatInt(time.Now().UnixNano()/1000000, 10))
query, err := CommercialSign(params)
if err != nil {
return nil, err
}
u, err := url.Parse(d.c.Host.CM)
if err != nil {
return nil, errors.WithStack(err)
}
u.Path = _cmIsBusinessAccount
u.RawQuery = query
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.WithStack(err)
}
req.Header.Set("Accept", "application/json")
resp := &struct {
Code int `json:"int"`
Success bool `json:"success"`
Message string `json:"message"`
Data map[string]bool `json:"data"`
}{}
if err := d.client.Do(ctx, req, resp); err != nil {
return nil, errors.WithStack(err)
}
if !resp.Success {
return nil, errors.Errorf("Failed to request cm api: %+v", resp)
}
res := make(map[int64]bool, len(resp.Data))
for smid, isBus := range resp.Data {
mid, err := strconv.ParseInt(smid, 10, 64)
if err != nil {
log.Warn("Failed to parse mid: %s: %+v", smid, err)
continue
}
res[mid] = isBus
}
return res, nil
}
// IsBusinessAccount is
func (d *Dao) IsBusinessAccount(ctx context.Context, mid int64) bool {
res, err := d.isBusinessAccount(ctx, []int64{mid})
if err != nil {
log.Error("Failed to check is business account with mid: %d: %+v", mid, err)
return false
}
return res[mid]
}
// BusinessAccountInfo is
func (d *Dao) BusinessAccountInfo(ctx context.Context, mid int64) (*model.CMAccountInfo, error) {
cm := d.c.HTTPClient.Normal.Host[d.c.Host.CM]
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("appkey", cm.Key)
params.Set("appsecret", cm.Secret)
params.Set("ts", strconv.FormatInt(time.Now().UnixNano()/1000000, 10))
query, err := CommercialSign(params)
if err != nil {
return nil, err
}
u, err := url.Parse(d.c.Host.CM)
if err != nil {
return nil, errors.WithStack(err)
}
u.Path = _cmBusinessAccountInfo
u.RawQuery = query
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, errors.WithStack(err)
}
req.Header.Set("Accept", "application/json")
res := &struct {
Code int `json:"int"`
Success bool `json:"success"`
Message string `json:"message"`
Data model.CMAccountInfo `json:"data"`
}{}
if err := d.client.Do(ctx, req, res); err != nil {
return nil, errors.WithStack(err)
}
if !res.Success {
return nil, errors.Errorf("Failed to request cm api: %+v", res)
}
return &res.Data, nil
}

View File

@@ -0,0 +1,75 @@
package account
import (
"context"
"net/url"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountCommercialSign(t *testing.T) {
var (
params = url.Values{}
)
params.Set("appkey", "test")
params.Set("appsecret", "e6c4c252dc7e3d8a90805eecd7c73396")
params.Set("key", "value")
result := url.Values{}
result.Set("appkey", "test")
result.Set("key", "value")
result.Set("sign", "f5c7329e9078e94ebf7d5852dfcd64f9")
convey.Convey("CommercialSign", t, func(ctx convey.C) {
query, err := CommercialSign(params)
ctx.Convey("Then err should be nil.query should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(query, convey.ShouldEqual, result.Encode())
})
})
}
func TestAccountisBusinessAccount(t *testing.T) {
var (
mids = []int64{1, 2, 3}
)
convey.Convey("isBusinessAccount", t, func(ctx convey.C) {
p1, err := d.isBusinessAccount(context.Background(), mids)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
if err != nil {
ctx.Printf("Failed to validate business account: %+v\n", err)
return
}
// ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountIsBusinessAccount(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("IsBusinessAccount", t, func(ctx convey.C) {
p1 := d.IsBusinessAccount(context.Background(), mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountBusinessAccountInfo(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("BusinessAccountInfo", t, func(ctx convey.C) {
p1, err := d.BusinessAccountInfo(context.Background(), mid)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
if err != nil {
ctx.Printf("Failed to get business account info: %+v\n", err)
return
}
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,54 @@
package account
import (
"context"
"fmt"
"time"
"go-common/library/cache/redis"
)
const (
_oneMonth = 31 * 24 * 60 * 60
)
func keyMonthlyOfficialSubmittedTimes(t time.Time, mid int64) string {
return fmt.Sprintf("ot_%d_%d", t.Month(), mid)
}
// IncreaseMonthlyOfficialSubmittedTimes is
func (d *Dao) IncreaseMonthlyOfficialSubmittedTimes(ctx context.Context, mid int64) (int64, error) {
key := keyMonthlyOfficialSubmittedTimes(time.Now(), mid)
conn := d.redis.Get(ctx)
defer conn.Close()
conn.Send("INCR", key)
conn.Send("EXPIRE", key, _oneMonth)
if err := conn.Flush(); err != nil {
return 0, err
}
new, err := redis.Int64(conn.Receive())
if err != nil {
return 0, err
}
conn.Receive() // drain the pipe line
return new, nil
}
// GetMonthlyOfficialSubmittedTimes is
func (d *Dao) GetMonthlyOfficialSubmittedTimes(ctx context.Context, mid int64) (int64, error) {
key := keyMonthlyOfficialSubmittedTimes(time.Now(), mid)
conn := d.redis.Get(ctx)
defer conn.Close()
v, err := redis.Int64(conn.Do("GET", key))
if err != nil {
if err == redis.ErrNil {
return 0, nil
}
return 0, err
}
return v, nil
}

View File

@@ -0,0 +1,38 @@
package account
import (
"context"
"fmt"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestKeyMonthlyOfficialSubmittedTimes(t *testing.T) {
convey.Convey("keyMonthlyOfficialSubmittedTimes", t, func(ctx convey.C) {
now := time.Now()
key := keyMonthlyOfficialSubmittedTimes(now, 1)
ctx.So(key, convey.ShouldEqual, fmt.Sprintf("ot_%d_%d", now.Month(), 1))
})
}
func TestIncreaseMonthlyOfficialSubmittedTimes(t *testing.T) {
convey.Convey("IncreaseMonthlyOfficialSubmittedTimes", t, func(ctx convey.C) {
p1, err := d.IncreaseMonthlyOfficialSubmittedTimes(context.Background(), 1)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestGetMonthlyOfficialSubmittedTimes(t *testing.T) {
convey.Convey("GetMonthlyOfficialSubmittedTimes", t, func(ctx convey.C) {
p1, err := d.GetMonthlyOfficialSubmittedTimes(context.Background(), 1)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,238 @@
package account
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
xhttp "net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
)
var (
updateFaceURI = "/api/user/updateFace"
identifyURI = "/api/internal/identify/info"
updateBirthURI = "/api/internal/member/updateBirthday"
updateSexURI = "/api/internal/member/updateSex"
// updatePerson = "/api/internal/member/updatePerson"
// updateUnameURI = "/api/internal/member/updateUname"
)
// UpdateBirthday is
func (d *Dao) UpdateBirthday(c context.Context, mid int64, ip, birthday string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("birthday", birthday)
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.accCo+updateBirthURI, ip, params, &res); err != nil {
log.Error("UpdateBirthday url(%s) error(%v)", updateBirthURI+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("UpdateBirthday url(%s) code(%v)", updateBirthURI+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}
// UpdateSign update sign.
// func (d *Dao) UpdateSign(c context.Context, mid int64, ip, sign string) (err error) {
// params := url.Values{}
// params.Set("mid", strconv.FormatInt(mid, 10))
// params.Set("user_sign", sign)
// var res struct {
// Code int `json:"code"`
// }
// if err = d.client.Post(c, d.accCo+updateSignURI, ip, params, &res); err != nil {
// log.Error("UpdateSign url(%s) error(%v)", updateBirthURI+"?"+params.Encode(), err)
// return
// }
// if res.Code != 0 {
// log.Error("UpdateSign url(%s) code(%v)", updateBirthURI+"?"+params.Encode(), res.Code)
// err = ParseJavaCode(res.Code)
// }
// return
// }
// UpdateSex update sex
func (d *Dao) UpdateSex(c context.Context, mid, sex int64, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("sex", strconv.FormatInt(sex, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.accCo+updateSexURI, ip, params, &res); err != nil {
log.Error("UpdateSex url(%s) error(%v)", updateSexURI+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("UpdateSex url(%s) error(%v)", updateSexURI+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}
// UpdatePerson update sex
// func (d *Dao) UpdatePerson(c context.Context, mid int64, birthday, ip string, datingType, marital, place int64) (err error) {
// params := url.Values{}
// params.Set("mid", strconv.FormatInt(mid, 10))
// params.Set("birthday", birthday)
// params.Set("datingtype", strconv.FormatInt(datingType, 10))
// params.Set("marital", strconv.FormatInt(marital, 10))
// params.Set("place", strconv.FormatInt(place, 10))
// var res struct {
// Code int `json:"code"`
// }
// if err = d.client.Post(c, d.accCo+updatePerson, ip, params, &res); err != nil {
// log.Error("UpdatePerson url(%s) error(%v)", updatePerson+"?"+params.Encode(), err)
// return
// }
// if res.Code != 0 {
// log.Error("UpdatePerson url(%s) error(%v)", updatePerson+"?"+params.Encode(), res.Code)
// err = ecode.Int(res.Code)
// }
// return
// }
// UpdateUname update uname.
// func (d *Dao) UpdateUname(c context.Context, mid int64, ip, uname string, isUpNickFree bool) (err error) {
// params := url.Values{}
// params.Set("mid", strconv.FormatInt(mid, 10))
// params.Set("uname", uname)
// params.Set("isupnick_free", strconv.FormatBool(isUpNickFree))
// var res struct {
// Code int `json:"code"`
// }
// if err = d.client.Post(c, d.accCo+updateUnameURI, ip, params, &res); err != nil {
// log.Error("UpdateUname url(%s) error(%v)", updateUnameURI+"?"+params.Encode(), err)
// return
// }
// if res.Code != 0 {
// log.Error("UpdateUname url(%s) code(%v)", updateUnameURI+"?"+params.Encode(), res.Code)
// err = ParseJavaCode(res.Code)
// }
// return
// }
// UpdateFace update face
func (d *Dao) UpdateFace(c context.Context, mid int64, face string, ip, cookie, accessKey string) (faceURL string, err error) {
var (
params = url.Values{}
fu = url.Values{}
req *xhttp.Request
)
log.Info("start UpdateFace %d,cookie: %v", mid, cookie)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("access_key", accessKey)
var url = d.accCom + updateFaceURI + "?" + d.sign(&params)
fu.Set("face", face)
if req, err = xhttp.NewRequest("POST", url, bytes.NewBuffer([]byte(fu.Encode()))); err != nil {
log.Error("http.NewRequest, err(%v)", err)
return
}
req.Header.Set("Cookie", cookie)
req.Header.Set("content-type", "application/x-www-form-urlencoded")
var res struct {
Code int `json:"code"`
Data struct {
Face string `json:"face"`
} `json:"data"`
Message string `json:"message"`
}
if err = d.client.Do(c, req, &res); err != nil {
log.Error("UpdateFace url(%v), err(%v)", url, err)
return
}
if res.Code != 0 {
log.Error("UpdateFace failed, url(%v) res(%v)", url, res)
err = ParseJavaCode(res.Code)
return
}
faceURL = res.Data.Face
log.Info("end success UpdateFace %d, %v", mid, faceURL)
return
}
// ParseJavaCode is
func ParseJavaCode(code int) (err error) {
switch code {
case -617:
err = ecode.UpdateUnameHadLocked
case -618:
err = ecode.UpdateUnameRepeated
case -655:
err = ecode.UpdateUnameMoneyIsNot
case -610:
err = ecode.MemberBlocked
case -602:
err = ecode.UpdateUnameTooShort
case -603:
err = ecode.UpdateUnameSensitive
case -601:
err = ecode.UpdateUnameTooLong
case -605:
err = ecode.UpdateUnameFormat
case -1001:
err = ecode.MemberSignHasEmoji
case -40012:
err = ecode.UpdateFaceFormat
case -40013:
err = ecode.UpdateFaceSize
default:
err = ecode.Int(code)
}
return
}
func (d *Dao) sign(params *url.Values) (query string) {
params.Set("appkey", d.c.App.Key)
tmp := params.Encode()
if strings.IndexByte(tmp, '+') > -1 {
tmp = strings.Replace(tmp, "+", "%20", -1)
}
var b bytes.Buffer
b.WriteString(tmp)
b.WriteString(d.c.App.Secret)
mh := md5.Sum(b.Bytes())
// query
var qb bytes.Buffer
qb.WriteString(tmp)
qb.WriteString("&sign=")
qb.WriteString(hex.EncodeToString(mh[:]))
query = qb.String()
return
}
// IdentifyInfo get identify info by calling api.
func (d *Dao) IdentifyInfo(c context.Context, mid int64, ip string) (idt *model.IdentifyInfo, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data *model.IdentifyInfo `json:"data"`
}
err = d.client.Get(c, d.accCo+identifyURI, ip, params, &res)
if err != nil {
log.Error("dao.client.Get(%s) error(%v)", d.accCo+identifyURI+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("identifyInfo url(%s) error(%v)", d.accCo+identifyURI+"?"+params.Encode(), err)
err = ecode.Int(res.Code)
return
}
idt = res.Data
return
}

View File

@@ -0,0 +1,131 @@
package account
import (
"context"
"go-common/library/ecode"
"net/url"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountUpdateBirthday(t *testing.T) {
var (
c = context.Background()
mid = int64(2345)
ip = ""
birthday = "2018-01-01"
)
convey.Convey("UpdateBirthday", t, func(ctx convey.C) {
err := d.UpdateBirthday(c, mid, ip, birthday)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
// func TestAccountUpdateSex(t *testing.T) {
// var (
// c = context.Background()
// mid = int64(0)
// sex = int64(0)
// ip = ""
// )
// convey.Convey("UpdateSex", t, func(ctx convey.C) {
// err := d.UpdateSex(c, mid, sex, ip)
// ctx.Convey("Then err should be nil.", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// })
// })
// }
// func TestAccountUpdatePerson(t *testing.T) {
// var (
// c = context.Background()
// mid = int64(2345)
// birthday = "2018-01-01"
// ip = ""
// datingType = int64(1)
// marital = int64(2)
// place = int64(3)
// )
// convey.Convey("UpdatePerson", t, func(ctx convey.C) {
// err := d.UpdatePerson(c, mid, birthday, ip, datingType, marital, place)
// ctx.Convey("Then err should be nil.", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// })
// })
// }
// func TestAccountUpdateUname(t *testing.T) {
// var (
// c = context.Background()
// mid = int64(2345)
// ip = ""
// uname = "dangerous" + strconv.FormatInt(rand.Intn(10))
// isUpNickFree = true
// )
// convey.Convey("UpdateUname", t, func(ctx convey.C) {
// err := d.UpdateUname(c, mid, ip, uname, isUpNickFree)
// ctx.Convey("Then err should be nil.", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// })
// })
// }
// func TestAccountUpdateFace(t *testing.T) {
// var (
// c = context.Background()
// mid = int64(0)
// face = ""
// ip = ""
// cookie = ""
// accessKey = ""
// )
// convey.Convey("UpdateFace", t, func(ctx convey.C) {
// faceURL, err := d.UpdateFace(c, mid, face, ip, cookie, accessKey)
// ctx.Convey("Then err should be nil.faceURL should not be nil.", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// ctx.So(faceURL, convey.ShouldNotBeNil)
// })
// })
// }
func TestAccountParseJavaCode(t *testing.T) {
var (
code = int(-617)
)
convey.Convey("ParseJavaCode", t, func(ctx convey.C) {
err := ParseJavaCode(code)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.UpdateUnameHadLocked)
})
})
}
func TestAccountsign(t *testing.T) {
var (
params = &url.Values{}
)
convey.Convey("sign", t, func(ctx convey.C) {
query := d.sign(params)
ctx.Convey("Then query should not be nil.", func(ctx convey.C) {
ctx.So(query, convey.ShouldNotBeNil)
})
})
}
func TestAccountIdentifyInfo(t *testing.T) {
var (
c = context.Background()
mid = int64(2345)
ip = ""
)
convey.Convey("IdentifyInfo", t, func(ctx convey.C) {
idt, err := d.IdentifyInfo(c, mid, ip)
ctx.Convey("Then err should be nil.idt should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(idt, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,99 @@
package account
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net/url"
"strconv"
"go-common/library/cache/memcache"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_smsSendURI = "/x/internal/sms/send"
_offTcode = "acc_20"
_vcExpire = 30 * 60 // 30min
)
func vcodeKey(mid int64, mobile string) string {
return fmt.Sprintf("mv_%d_%s", mid, mobile)
}
// SendMobileVerify is.
func (d *Dao) SendMobileVerify(ctx context.Context, vcode, country int64, mobile, ip string) error {
params := url.Values{}
// params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("mobile", mobile)
params.Set("country", strconv.FormatInt(country, 10))
params.Set("tcode", _offTcode)
tparam, err := OffiVerifyParam(vcode)
if err != nil {
return err
}
params.Set("tparam", tparam)
var res struct {
Code int `json:"code"`
}
if err := d.client.Post(ctx, d.smsSendURI, ip, params, &res); err != nil {
log.Error("Failed to send sms send request: %+v: %+v", params, err)
return err
}
if res.Code != 0 {
log.Error("Failed to send sms send requets: %+v: %d", params, res.Code)
return ecode.Int(res.Code)
}
return nil
}
// OffiVerifyParam is.
func OffiVerifyParam(vcode int64) (string, error) {
p := map[string]string{
"identify_code": strconv.FormatInt(vcode, 10),
}
ps, err := json.Marshal(p)
return string(ps), err
}
// GenVerifyCode is.
func (d *Dao) GenVerifyCode(ctx context.Context, mid int64, mobile string) (int64, error) {
vcode := int64(rand.Intn(9999-1000) + 1000)
key := vcodeKey(mid, mobile)
conn := d.mc.Get(ctx)
vcs := strconv.FormatInt(vcode, 10)
defer conn.Close()
if err := conn.Set(&memcache.Item{
Key: key,
Value: []byte(vcs),
Expiration: _vcExpire,
}); err != nil {
log.Error("conn.Set(%s, %d) error(%v)", key, vcode, err)
return 0, err
}
return vcode, nil
}
// GetVerifyCode is.
func (d *Dao) GetVerifyCode(ctx context.Context, mid int64, mobile string) (int64, error) {
key := vcodeKey(mid, mobile)
conn := d.mc.Get(ctx)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
return 0, err
}
return strconv.ParseInt(string(item.Value), 10, 64)
}
// DelVerifyCode is.
func (d *Dao) DelVerifyCode(ctx context.Context, mid int64, mobile string) error {
key := vcodeKey(mid, mobile)
conn := d.mc.Get(ctx)
defer conn.Close()
return conn.Delete(key)
}

View File

@@ -0,0 +1,90 @@
package account
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountvcodeKey(t *testing.T) {
var (
mid = int64(0)
mobile = ""
)
convey.Convey("vcodeKey", t, func(ctx convey.C) {
p1 := vcodeKey(mid, mobile)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountSendMobileVerify(t *testing.T) {
var (
vcode = int64(1234)
country = int64(86)
mobile = "13488888888"
ip = ""
)
convey.Convey("SendMobileVerify", t, func(ctx convey.C) {
err := d.SendMobileVerify(context.Background(), vcode, country, mobile, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAccountOffiVerifyParam(t *testing.T) {
var (
vcode = int64(0)
)
convey.Convey("OffiVerifyParam", t, func(ctx convey.C) {
p1, err := OffiVerifyParam(vcode)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountGenVerifyCode(t *testing.T) {
var (
mid = int64(0)
mobile = ""
)
convey.Convey("GenVerifyCode", t, func(ctx convey.C) {
p1, err := d.GenVerifyCode(context.Background(), mid, mobile)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountGetVerifyCode(t *testing.T) {
var (
mid = int64(0)
mobile = ""
)
convey.Convey("GetVerifyCode", t, func(ctx convey.C) {
p1, err := d.GetVerifyCode(context.Background(), mid, mobile)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountDelVerifyCode(t *testing.T) {
var (
mid = int64(0)
mobile = ""
)
convey.Convey("DelVerifyCode", t, func(ctx convey.C) {
err := d.DelVerifyCode(context.Background(), mid, mobile)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,36 @@
package account
import (
"context"
"net/url"
"strconv"
"go-common/library/ecode"
"go-common/library/log"
)
var (
_vipPointBalance = "/internal/v1/point/"
)
// VipPointBalance vip point
func (d *Dao) VipPointBalance(c context.Context, mid int64, ip string) (pointBalance int64, err error) {
params := url.Values{}
var res struct {
Code int `json:"code"`
Data struct {
PointBalance int64 `json:"pointBalance"`
} `json:"data"`
}
if err = d.client.Get(c, d.vipHost+_vipPointBalance+strconv.FormatInt(mid, 10), ip, params, &res); err != nil {
log.Error("VipPointBalance() failed url(%v), err(%v)", d.vipHost+_vipPointBalance, err)
return
}
if res.Code != 0 {
log.Error("VipPointBalance() url(%v), res(%v)", d.vipHost+_vipPointBalance, res)
err = ecode.Int(res.Code)
return
}
pointBalance = res.Data.PointBalance
return
}

View File

@@ -0,0 +1,23 @@
package account
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountVipPointBalance(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
ip = ""
)
convey.Convey("VipPointBalance", t, func(ctx convey.C) {
pointBalance, err := d.VipPointBalance(c, mid, ip)
ctx.Convey("Then err should be nil.pointBalance should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(pointBalance, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["geetest.go"],
importpath = "go-common/app/interface/main/account/dao/geetest",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata: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"],
)
go_test(
name = "go_default_test",
srcs = ["geetest_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,159 @@
package geetest
import (
"context"
"crypto/tls"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_register = "http://api.geetest.com/register.php"
_validate = "http://api.geetest.com/validate.php"
)
// Dao is account dao.
type Dao struct {
c *conf.Config
// url
registerURI string
validateURI string
// http client
client *http.Client
clientx *bm.Client
}
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
registerURI: _register,
validateURI: _validate,
// http client
client: NewClient(c.HTTPClient),
clientx: bm.NewClient(c.HTTPClient.Slow),
}
return
}
// PreProcess preprocessing the geetest and get to challenge
func (d *Dao) PreProcess(c context.Context, mid int64, geeType string, gc conf.GeetestConfig, newCaptcha int) (challenge string, err error) {
var (
req *http.Request
res *http.Response
bs []byte
params url.Values
)
params = url.Values{}
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("new_captcha", strconv.Itoa(newCaptcha))
params.Set("ip_address", metadata.String(c, metadata.RemoteIP))
params.Set("client_type", geeType)
params.Set("gt", gc.CaptchaID)
if req, err = http.NewRequest("GET", d.registerURI+"?"+params.Encode(), nil); err != nil {
log.Error("d.preprocess uri(%s) params(%s) error(%v)", d.registerURI, params.Encode(), err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if res, err = d.client.Do(req); err != nil {
log.Error("client.Do(%s) error(%v)", d.registerURI+"?"+params.Encode(), err)
return
}
defer res.Body.Close()
if res.StatusCode >= http.StatusInternalServerError {
err = errors.New("http status code 5xx")
log.Error("gtServerErr uri(%s) error(%v)", d.validateURI+"?"+params.Encode(), err)
return
}
if bs, err = ioutil.ReadAll(res.Body); err != nil {
log.Error("ioutil.ReadAll(%s) uri(%s) error(%v)", bs, d.validateURI+"?"+params.Encode(), err)
return
}
if len(bs) != 32 {
log.Error("d.preprocess len(%s) the length not equate 32byte", string(bs))
return
}
challenge = string(bs)
return
}
// Validate recheck the challenge code and get to seccode
func (d *Dao) Validate(c context.Context, challenge, seccode, clientType, captchaID string, mid int64) (res *model.ValidateRes, err error) {
params := url.Values{}
params.Set("seccode", seccode)
params.Set("challenge", challenge)
params.Set("captchaid", captchaID)
params.Set("client_type", clientType)
params.Set("ip_address", metadata.String(c, metadata.RemoteIP))
params.Set("json_format", "1")
params.Set("sdk", "golang_3.0.0")
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
req, err := http.NewRequest("POST", d.validateURI, strings.NewReader(params.Encode()))
if err != nil {
log.Error("http.NewRequest error(%v) | uri(%s) params(%s)", err, d.validateURI, params.Encode())
return
}
log.Info("Validate(%v) start", params)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res = new(model.ValidateRes)
if err = d.clientx.Do(c, req, &res); err != nil {
log.Error("d.client.Do error(%v) | uri(%s) params(%s) res(%v)", err, d.validateURI, params.Encode(), res)
return
}
log.Info("Validate(%v) suc", res)
return
}
// NewClient new a http client.
func NewClient(c *conf.HTTPClient) (client *http.Client) {
var (
transport *http.Transport
dialer *net.Dialer
)
dialer = &net.Dialer{
Timeout: time.Duration(c.Slow.Dial),
KeepAlive: time.Duration(c.Slow.KeepAlive),
}
transport = &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: transport,
}
return
}
// GeeConfig get geetest config.
func (d *Dao) GeeConfig(ct string, c *conf.Geetest) (gc conf.GeetestConfig, clientType string) {
if ct == "" {
return c.PC, "web"
}
switch ct {
case "web":
gc = c.PC
clientType = "web"
case "h5":
gc = c.H5
clientType = "h5"
default:
gc = c.PC
clientType = "web"
}
return
}

View File

@@ -0,0 +1,78 @@
package geetest
import (
"context"
"flag"
"os"
"testing"
"go-common/app/interface/main/account/conf"
"github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.account-interface")
flag.Set("conf_token", "967eef77ad40b478234f11b0d489d6d6")
flag.Set("tree_id", "3815")
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/account-interface-example.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func TestGeetestPreProcess(t *testing.T) {
convey.Convey("PreProcess", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(11)
geeType = ""
gc = d.c.Geetest.PC
newCaptcha = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
challenge, err := d.PreProcess(c, mid, geeType, gc, newCaptcha)
ctx.Convey("Then err should be nil.challenge should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(challenge, convey.ShouldNotBeNil)
})
})
})
}
func TestGeetestValidate(t *testing.T) {
convey.Convey("Validate", t, func(ctx convey.C) {
var (
c = context.Background()
challenge = "ac7e67bb9b8e3e567186159e63df2153cs"
seccode = "7bda121544bd035032b2b5e390bce5d7"
clientType = "web"
captchaID = "0926f406a4a5433a45faf33ae9a721c3"
mid = int64(11)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Validate(c, challenge, seccode, clientType, captchaID, mid)
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,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["passport_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["passport.go"],
importpath = "go-common/app/interface/main/account/dao/passport",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/dao/account:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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,143 @@
package passport
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/dao/account"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
var (
fastRegUri = "/intranet/acc/user/source"
useridUri = "/intranet/acc/userid"
testUsername = "/api/reg/testUserName"
queryByMidUri = "/intranet/acc/queryByMid"
updateName = "/intranet/acc/updateUname"
)
// Dao dao
type Dao struct {
c *conf.Config
client *bm.Client
}
// New new
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Normal),
}
return
}
func (d *Dao) FastReg(c context.Context, mid int64, ip string) (isRegFast bool, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
FastReg bool `json:"fastReg"`
} `json:"data"`
Message string `json:"message"`
}
if err = d.client.Get(c, d.c.Host.Passport+fastRegUri, ip, params, &res); err != nil {
log.Error("fastReg url(%s) error(%v)", fastRegUri+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("fastReg url(%s) res(%v)", fastRegUri+"?"+params.Encode(), res)
err = ecode.Int(res.Code)
return
}
isRegFast = res.Data.FastReg
return
}
//UserID user id.
func (d *Dao) UserID(c context.Context, mid int64, ip string) (userID string, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
UserID string `json:"userid"`
} `json:"data"`
Message string `json:"message"`
}
if err = d.client.Get(c, d.c.Host.Passport+useridUri, ip, params, &res); err != nil {
log.Error("UserID url(%s) error(%v)", useridUri+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("userID url(%s) res(%v)", useridUri+"?"+params.Encode(), res)
err = ecode.Int(res.Code)
return
}
userID = res.Data.UserID
return
}
// TestUserName is.
func (d *Dao) TestUserName(c context.Context, name string, mid int64, ip string) error {
params := url.Values{}
params.Set("user_name", name)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err := d.client.Get(c, d.c.Host.Passport+testUsername, ip, params, &res); err != nil {
log.Error("Failed to test username: %+v: %+v", params, err)
return err
}
if res.Code != 0 {
log.Error("Failed to test username with code: %+v: %d", params, res.Code)
return account.ParseJavaCode(res.Code)
}
return nil
}
// QueryByMid is.
func (d *Dao) QueryByMid(c context.Context, mid int64, ip string) (*model.PassportProfile, error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data *model.PassportProfile `json:"data"`
}
if err := d.client.Get(c, d.c.Host.Passport+queryByMidUri, ip, params, &res); err != nil {
log.Error("Failed to query by mid: %+v: %+v", params, err)
return nil, err
}
if res.Code != 0 {
log.Error("Failed to query by mid with code: %+v: %d", params, res.Code)
return nil, account.ParseJavaCode(res.Code)
}
return res.Data, nil
}
// UpdateName is.
func (d *Dao) UpdateName(c context.Context, mid int64, name, ip string) error {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("uname", name)
var res struct {
Code int `json:"code"`
}
if err := d.client.Post(c, d.c.Host.Passport+updateName, ip, params, &res); err != nil {
log.Error("Failed to update uname params: %+v: %v", params, err)
return err
}
if res.Code != 0 {
log.Error("Failed to update uname, params: %+v,code: %d", params, res.Code)
return account.ParseJavaCode(res.Code)
}
return nil
}

View File

@@ -0,0 +1,39 @@
package passport
import (
"context"
"flag"
"testing"
"go-common/app/interface/main/account/conf"
"github.com/smartystreets/goconvey/convey"
)
var d *Dao
func init() {
flag.Parse()
flag.Set("conf", "../../cmd/account-interface-example.toml")
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
}
func TestDao_UserID(t *testing.T) {
convey.Convey("ReplyHistoryList", t, func() {
id, err := d.UserID(context.TODO(), 1, "")
convey.So(err, convey.ShouldBeNil)
convey.So(id, convey.ShouldNotBeEmpty)
})
}
func TestDao_FastReg(t *testing.T) {
convey.Convey("ReplyHistoryList", t, func() {
fastReg, err := d.FastReg(context.TODO(), 111001347, "")
convey.So(err, convey.ShouldBeNil)
convey.So(fastReg, convey.ShouldNotBeEmpty)
})
}

View File

@@ -0,0 +1,55 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_library(
name = "go_default_library",
srcs = [
"alipay.go",
"antispam.go",
"geetest.go",
"realname.go",
],
importpath = "go-common/app/interface/main/account/dao/realname",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//library/cache/memcache: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",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["realname_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,91 @@
package realname
import (
"context"
"net/http"
"net/url"
"go-common/app/interface/main/account/conf"
"go-common/library/log"
"github.com/pkg/errors"
)
type respAlipay struct {
Code string `json:"code"`
Msg string `json:"msg"`
SubCode string `json:"sub_code"`
SubMsg string `json:"sub_msg"`
}
func (r *respAlipay) Error() error {
if r.Code == "10000" {
return nil
}
return errors.Errorf("alipay response failed , code : %s, msg : %s, sub_code : %s, sub_msg : %s", r.Code, r.Msg, r.SubCode, r.SubMsg)
}
// AlipayInit .
func (d *Dao) AlipayInit(c context.Context, param url.Values) (bizno string, err error) {
var (
req *http.Request
)
url := conf.Conf.Realname.Alipay.Gateway + "?" + param.Encode()
if req, err = http.NewRequest("GET", url, nil); err != nil {
err = errors.Wrapf(err, "http.NewRequest(GET,%s)", url)
return
}
var resp struct {
Resp struct {
respAlipay
Bizno string `json:"biz_no"`
} `json:"zhima_customer_certification_initialize_response"`
Sign string `json:"sign"`
}
if err = d.client.Do(c, req, &resp); err != nil {
return
}
log.Info("Realname alipay init \n\tparam : %+v \n\tresp : %+v", param, resp)
if err = resp.Resp.Error(); err != nil {
return
}
bizno = resp.Resp.Bizno
return
}
// AlipayQuery .
func (d *Dao) AlipayQuery(c context.Context, param url.Values) (pass bool, reason string, err error) {
var (
req *http.Request
)
url := conf.Conf.Realname.Alipay.Gateway + "?" + param.Encode()
if req, err = http.NewRequest("GET", url, nil); err != nil {
err = errors.Wrapf(err, "http.NewRequest(GET,%s)", url)
return
}
var resp struct {
Resp struct {
respAlipay
Passed string `json:"passed"`
FailedReason string `json:"failed_reason"`
IdentityInfo string `json:"identity_info"`
AttributeInfo string `json:"attribute_info"`
ChannelStatuses string `json:"channel_statuses"`
} `json:"zhima_customer_certification_query_response"`
Sign string `json:"sign"`
}
if err = d.client.Do(c, req, &resp); err != nil {
return
}
log.Info("Realname alipay query \n\tparam : %+v \n\tresp : %+v", param, resp)
if err = resp.Resp.Error(); err != nil {
return
}
if resp.Resp.Passed == "true" {
pass = true
} else {
pass = false
}
reason = resp.Resp.FailedReason
return
}

View File

@@ -0,0 +1,105 @@
package realname
import (
"context"
"fmt"
"go-common/app/interface/main/account/conf"
"go-common/library/cache/memcache"
"github.com/pkg/errors"
)
func alipayAntispamKey(mid int64) string {
return fmt.Sprintf("raa_%d", mid)
}
//AlipayAntispamValue 最低位为pass flag ,高位为计数
//计数:判断用户的申请次数
//flag:是否通过本次防刷验证(极验是否通过)
type AlipayAntispamValue int
// IncreaseCount add antispam count
func (a *AlipayAntispamValue) IncreaseCount() {
*a = AlipayAntispamValue((a.Count()+1)<<1 + a.Flag())
}
// SetPass set is antispam verified (such as when geetest passed)
func (a *AlipayAntispamValue) SetPass(pass bool) {
var flag int
if pass {
flag = 1
}
*a = AlipayAntispamValue(a.Count()<<1 + flag)
}
// Count return antispam hit count
func (a *AlipayAntispamValue) Count() int {
return int(*a) >> 1
}
// Flag return antispam pass flag
func (a *AlipayAntispamValue) Flag() int {
return int(*a) & 0x1
}
// Pass return is antispam passed (such as when geetest passed)
func (a *AlipayAntispamValue) Pass() bool {
return a.Flag() > 0
}
// AlipayAntispam get alipay antispam count by mid
func (d *Dao) AlipayAntispam(c context.Context, mid int64) (value *AlipayAntispamValue, err error) {
var (
key = alipayAntispamKey(mid)
conn = d.mc.Get(c)
item *memcache.Item
)
defer conn.Close()
if item, err = conn.Get(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
return
}
value = new(AlipayAntispamValue)
if err = conn.Scan(item, &value); err != nil {
err = errors.Wrapf(err, "conn.Scan(%+v)", item)
return
}
return
}
// SetAlipayAntispam set alipay antispam count by mid
func (d *Dao) SetAlipayAntispam(c context.Context, mid int64, value *AlipayAntispamValue) (err error) {
var (
key = alipayAntispamKey(mid)
conn = d.mc.Get(c)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: key, Object: value, Flags: memcache.FlagJSON, Expiration: conf.Conf.Realname.AlipayAntispamTTL}); err != nil {
err = errors.Wrapf(err, "conn.Set(%s,%+v)", key, value)
return
}
return
}
// DeleteAlipayAntispam delete alipay antispam count by mid
func (d *Dao) DeleteAlipayAntispam(c context.Context, mid int64) (err error) {
var (
key = alipayAntispamKey(mid)
conn = d.mc.Get(c)
)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Delete(%s)", key)
return
}
return
}

View File

@@ -0,0 +1,79 @@
package realname
import (
"context"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/account/conf"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// RealnameCaptchaGTRegister register a geetest apply
func (d *Dao) RealnameCaptchaGTRegister(c context.Context, mid int64, ip, clientType string, newCaptcha int) (challenge string, err error) {
var (
params = url.Values{}
req *http.Request
url = conf.Conf.Realname.Geetest.RegisterURL
)
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("new_captcha", strconv.Itoa(newCaptcha))
params.Set("ip_address", ip)
params.Set("client_type", clientType)
params.Set("gt", conf.Conf.Realname.Geetest.CaptchaID)
if req, err = http.NewRequest("GET", url+"?"+params.Encode(), nil); err != nil {
err = errors.Wrapf(err, "dao.RealnameCaptchaGTRegister url(%s) params(%s)", url, params.Encode())
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var challengeBytes []byte
if challengeBytes, err = d.client.Raw(c, req); err != nil {
return
}
challenge = string(challengeBytes)
if len(challenge) != 32 {
log.Error("dao.RealnameCaptchaGTRegister challenge : %s ,length not equate 32bit", challenge)
}
return
}
// RealnameCaptchaGTRegisterValidate recheck the challenge code and get to seccode
func (d *Dao) RealnameCaptchaGTRegisterValidate(c context.Context, challenge, seccode, clientType, ip, captchaID string, mid int64) (realSeccode string, err error) {
var (
params = url.Values{}
req *http.Request
url = conf.Conf.Realname.Geetest.ValidateURL
)
params.Set("seccode", seccode)
params.Set("challenge", challenge)
params.Set("captchaid", captchaID)
params.Set("client_type", clientType)
params.Set("ip_address", metadata.String(c, metadata.RemoteIP))
params.Set("json_format", "1")
params.Set("sdk", "golang_3.0.0")
params.Set("user_id", strconv.FormatInt(mid, 10))
params.Set("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
log.Info("gt validate url : %s , params : %s", url, params.Encode())
if req, err = http.NewRequest("POST", url, strings.NewReader(params.Encode())); err != nil {
err = errors.Wrapf(err, "dao.RealnameCaptchaGTRegister url(%s) params(%s)", url, params.Encode())
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
var resp struct {
Seccode string `json:"seccode"`
}
if err = d.client.Do(c, req, &resp); err != nil {
return
}
realSeccode = resp.Seccode
return
}

View File

@@ -0,0 +1,60 @@
package realname
import (
"context"
"fmt"
"net/url"
"go-common/app/interface/main/account/conf"
"go-common/library/cache/memcache"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"github.com/pkg/errors"
)
var (
telInfoURI = "/intranet/acc/telInfo/mid"
)
// Dao dao
type Dao struct {
c *conf.Config
client *bm.Client
mc *memcache.Pool
}
// New new
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Normal),
mc: memcache.NewPool(c.AccMemcache),
}
return
}
// TelInfo tel info.
func (d *Dao) TelInfo(c context.Context, mid int64) (tel string, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
var resp struct {
Code int `json:"code"`
Data struct {
Mid int64 `json:"mid"`
Tel string `json:"tel"`
JoinIP string `json:"join_ip"`
JoinTime int64 `json:"join_time"`
} `json:"data"`
}
if err = d.client.Get(c, d.c.Host.Passport+telInfoURI, "", params, &resp); err != nil {
err = errors.Errorf("realname TelInfo d.httpClient.Do() error(%+v)", err)
return
}
if resp.Code != 0 {
err = errors.Errorf("realname TelInfo url(%s) res(%+v) err(%+v)", telInfoURI+"?"+params.Encode(), resp, ecode.Int(resp.Code))
return
}
tel = resp.Data.Tel
return
}

View File

@@ -0,0 +1,50 @@
package realname
import (
"context"
"flag"
"testing"
"go-common/app/interface/main/account/conf"
"github.com/smartystreets/goconvey/convey"
)
var d *Dao
func init() {
flag.Parse()
flag.Set("conf", "../../cmd/account-interface-example.toml")
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
}
func TestTelInfo(t *testing.T) {
convey.Convey("ReplyHistoryList", t, func() {
res, err := d.TelInfo(context.TODO(), 46333)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestAntispam(t *testing.T) {
convey.Convey("antispam", t, func() {
anti := new(AlipayAntispamValue)
anti.IncreaseCount()
c := anti.Count()
convey.So(c, convey.ShouldEqual, 1)
p := anti.Pass()
convey.So(p, convey.ShouldBeFalse)
anti.IncreaseCount()
c = anti.Count()
convey.So(c, convey.ShouldEqual, 2)
anti.SetPass(true)
p = anti.Pass()
convey.So(p, convey.ShouldBeTrue)
})
}

View File

@@ -0,0 +1,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["relation.go"],
importpath = "go-common/app/interface/main/account/dao/relation",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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"],
)
go_test(
name = "go_default_test",
srcs = ["relation_test.go"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)

View File

@@ -0,0 +1,112 @@
package relation
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// Dao is
type Dao struct {
conf *conf.Config
httpClient *bm.Client
recommendURL string
}
const (
_recommendURI = "/main/recommend"
)
// New is
func New(conf *conf.Config) *Dao {
return &Dao{
conf: conf,
httpClient: bm.NewClient(conf.HTTPClient.Normal),
recommendURL: conf.Host.Search + _recommendURI,
}
}
func paltform(device *bm.Device) string {
if device.RawMobiApp == "" {
return "web"
}
if device.IsAndroid() {
return "android"
}
if device.IsIOS() {
return "ios"
}
return "web"
}
func buvid(device *bm.Device) string {
if device.RawMobiApp == "" {
return device.Buvid3
}
return device.Buvid
}
// Recommend is
func (d *Dao) Recommend(ctx context.Context, mid int64, serviceArea string, mainTids string, subTids string, device *bm.Device, pagesize int64, ip string) (*model.RecommendResponse, error) {
params := url.Values{}
params.Set("platform", paltform(device))
params.Set("mobi_app", device.MobiApp())
params.Set("device", device.Device)
params.Set("build", strconv.FormatInt(device.Build, 10))
params.Set("clientip", ip)
params.Set("userid", strconv.FormatInt(mid, 10))
params.Set("buvid", buvid(device))
params.Set("pagesize", strconv.FormatInt(pagesize, 10))
params.Set("rec_type", "up_rec")
params.Set("service_area", serviceArea)
if mainTids != "" {
params.Set("main_tids", mainTids)
}
if subTids != "" {
params.Set("sub_tids", subTids)
}
resp := &model.RecommendResponse{}
if err := d.httpClient.Get(ctx, d.recommendURL, ip, params, resp); err != nil {
return nil, err
}
if resp.Code != 0 {
log.Error("Failed to call recommendation service with error code: %d, params: %+v, trackid(%s)", resp.Code, params, resp.TrackID)
return nil, ecode.Int(int(resp.Code))
}
return resp, nil
}
// TagSuggestRecommend is
func (d *Dao) TagSuggestRecommend(ctx context.Context, mid int64, contextID string, tagname string, device *bm.Device, pagesize int64, ip string) (*model.TagSuggestRecommendResponse, error) {
params := url.Values{}
params.Set("platform", paltform(device))
params.Set("mobi_app", device.MobiApp())
params.Set("device", device.Device)
params.Set("build", strconv.FormatInt(device.Build, 10))
params.Set("clientip", ip)
params.Set("userid", strconv.FormatInt(mid, 10))
params.Set("buvid", buvid(device))
params.Set("pagesize", strconv.FormatInt(pagesize, 10))
params.Set("rec_type", "tagup_rec")
params.Set("service_area", "tag_suggest")
params.Set("context_id", contextID)
if tagname != "" {
params.Set("tagname", tagname)
}
resp := &model.TagSuggestRecommendResponse{}
if err := d.httpClient.Get(ctx, d.recommendURL, ip, params, resp); err != nil {
return nil, err
}
if resp.Code != 0 {
log.Error("Failed to call recommendation service with error code: %d, params: %+v, trackid(%s)", resp.Code, params, resp.TrackID)
return nil, ecode.Int(int(resp.Code))
}
return resp, nil
}

View File

@@ -0,0 +1,117 @@
package relation
import (
"context"
"flag"
"os"
"strings"
"testing"
"go-common/app/interface/main/account/conf"
bm "go-common/library/net/http/blademaster"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.account-interface")
flag.Set("conf_token", "967eef77ad40b478234f11b0d489d6d6")
flag.Set("tree_id", "3815")
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/account-interface-example.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.httpClient.SetTransport(gock.DefaultTransport)
m.Run()
os.Exit(0)
}
func TestRelationpaltform(t *testing.T) {
var (
device = &bm.Device{}
)
convey.Convey("paltform", t, func(ctx convey.C) {
p1 := paltform(device)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestRelationbuvid(t *testing.T) {
var (
device = &bm.Device{}
)
convey.Convey("buvid", t, func(ctx convey.C) {
p1 := buvid(device)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestRelationRecommend(t *testing.T) {
var (
ctx = context.Background()
mid = int64(0)
serviceArea = ""
mainTids = ""
subTids = ""
device = &bm.Device{}
pagesize = int64(0)
ip = ""
)
convey.Convey("Recommend", t, func(c convey.C) {
httpMock("GET", d.recommendURL).Reply(200).JSON(`{"code":0,"message":"0","data":[]}`)
defer gock.OffAll()
p1, err := d.Recommend(ctx, mid, serviceArea, mainTids, subTids, device, pagesize, ip)
c.Convey("Then err should be nil.p1 should not be nil.", func(c convey.C) {
c.So(err, convey.ShouldBeNil)
c.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestRelationTagSuggestRecommend(t *testing.T) {
var (
ctx = context.Background()
mid = int64(0)
contextID = ""
tagname = ""
device = &bm.Device{}
pagesize = int64(0)
ip = ""
)
convey.Convey("TagSuggestRecommend", t, func(c convey.C) {
httpMock("GET", d.recommendURL).Reply(200).JSON(`{"code":0,"message":"0","data":[]}`)
defer gock.OffAll()
p1, err := d.TagSuggestRecommend(ctx, mid, contextID, tagname, device, pagesize, ip)
c.Convey("Then err should be nil.p1 should not be nil.", func(c convey.C) {
c.So(err, convey.ShouldBeNil)
c.So(p1, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,49 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["reply_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["reply.go"],
importpath = "go-common/app/interface/main/account/dao/reply",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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"],
)

View File

@@ -0,0 +1,160 @@
package reply
import (
"context"
xhttp "net/http"
"net/url"
"strconv"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
var (
_replyHistoryURI = "/x/internal/v2/reply/record"
_activityPagesURI = "/activity/pages"
)
// Dao dao
type Dao struct {
c *conf.Config
client *bm.Client
replyHistory string
activityPages string
}
// New Dao
func New(c *conf.Config) (d *Dao) {
return &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Normal),
replyHistory: c.Host.API + _replyHistoryURI,
activityPages: c.Host.WWW + _activityPagesURI,
}
}
// ReplyHistoryList reply history list
func (d *Dao) ReplyHistoryList(c context.Context, mid int64, stime, etime, order, sort string, pn, ps int64, accessKey, cookie, ip string) (rhl *model.ReplyHistory, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("stime", stime)
params.Set("etime", etime)
params.Set("order", order)
params.Set("sort", sort)
params.Set("pn", strconv.FormatInt(pn, 10))
params.Set("ps", strconv.FormatInt(ps, 10))
params.Set("access_key", accessKey)
req, err := d.client.NewRequest(xhttp.MethodGet, d.replyHistory, ip, params)
if err != nil {
return
}
var res struct {
Code int `json:"code"`
Data struct {
Page struct {
Num int `json:"num"`
Size int `json:"size"`
Total int `json:"total"`
} `json:"page"`
Records []struct {
ID int `json:"id"`
Oid int64 `json:"oid"`
Type int64 `json:"type"`
Floor int `json:"floor"`
Like int `json:"like"`
Rcount int `json:"rcount"`
Mid int64 `json:"mid"`
State int `json:"state"`
Message string `json:"message"`
Ctime string `json:"ctime"`
Members []*model.Info `json:"members"`
} `json:"records"`
} `json:"data"`
Message string `json:"message"`
TTL int `json:"ttl"`
}
if err = d.client.Do(c, req, &res); err != nil {
log.Error("member interface reply request reply history list failed, err(%v)", err)
return
}
if res.Code != 0 {
log.Error("member interface reply request reply history list code(%d), err(%v)", res.Code, err)
err = ecode.Int(res.Code)
return
}
rhl = &model.ReplyHistory{
Page: res.Data.Page,
Records: make([]*model.Record, 0),
}
for _, v := range res.Data.Records {
tme := make([]*model.Member, 0)
for _, vt := range v.Members {
m, _ := strconv.ParseInt(vt.Mid, 10, 64)
tmp := &model.Member{
Mid: m,
Uname: vt.Name,
}
tme = append(tme, tmp)
}
rhlt := &model.Record{
ID: v.ID,
Oid: v.Oid,
OidStr: strconv.FormatInt(v.Oid, 10),
Type: v.Type,
Floor: v.Floor,
Like: v.Like,
Rcount: v.Rcount,
Mid: v.Mid,
State: v.State,
Message: v.Message,
Ctime: v.Ctime,
Members: tme,
}
rhl.Records = append(rhl.Records, rhlt)
}
return
}
// ActivityPages activity pages api
func (d *Dao) ActivityPages(c context.Context, mid int64, aids []int64, accessKey, cookie, ip string) (at map[int64]*model.RecordAppend, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("pids", xstr.JoinInts(aids))
params.Set("all", "isOne")
params.Set("access_key", accessKey)
req, err := d.client.NewRequest(xhttp.MethodGet, d.activityPages, ip, params)
if err != nil {
return
}
var res struct {
Code int `json:"code"`
Data struct {
List []struct {
ID int64 `json:"id"`
Name string `json:"name"`
PcURL string `json:"pc_url"`
} `json:"list"`
} `json:"data"`
}
at = make(map[int64]*model.RecordAppend)
if err = d.client.Do(c, req, &res); err != nil {
log.Error("member interface reply request activity failed, err(%v)", err)
return
}
if res.Code != 0 {
log.Error("member interface reply request activity code != 0, err(%v)", err)
err = ecode.Int(res.Code)
return
}
for _, v := range res.Data.List {
at[v.ID] = &model.RecordAppend{
Title: v.Name,
URL: v.PcURL,
}
}
return
}

View File

@@ -0,0 +1,31 @@
package reply
import (
"context"
"flag"
"testing"
"go-common/app/interface/main/account/conf"
"github.com/smartystreets/goconvey/convey"
)
var d *Dao
func init() {
flag.Parse()
flag.Set("conf", "../../cmd/account-interface-example.toml")
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
}
func TestReplyHistoryList(t *testing.T) {
convey.Convey("ReplyHistoryList", t, func() {
res, err := d.ReplyHistoryList(context.TODO(), 1, "2017-3-21", "2017-3-21", "time", "desc", 1, 50, "access_key", "cookie", "0.0.0.0")
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,54 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
],
importpath = "go-common/app/interface/main/account/dao/usersuit",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/service/main/usersuit/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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"],
)
go_test(
name = "go_default_test",
srcs = [
"api_test.go",
"dao_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,170 @@
package usersuit
import (
"context"
"net/url"
"strconv"
usmdl "go-common/app/service/main/usersuit/model"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_groupInfo = "/x/internal/pendant/groupInfo"
_entryGroup = "/x/internal/pendant/entryGroup"
_vipGroup = "/x/internal/pendant/vipGroup"
_pendantInfo = "/x/internal/pendant/pendantByID"
_packageInfo = "/x/internal/pendant/package"
_orderInfo = "/x/internal/pendant/order"
_orderHistory = "/x/internal/pendant/orderHistory"
)
// Group get pendant group info.
func (d *Dao) Group(c context.Context, ip string) (groups []*usmdl.PendantGroupInfo, err error) {
var res struct {
Code int `json:"code"`
Data []*usmdl.PendantGroupInfo `json:"data"`
}
if err = d.http.Get(c, d.groupURL, ip, nil, &res); err != nil {
log.Error("d.http.Get(%s) error(%v)", d.groupURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.groupURL, err)
return
}
groups = res.Data
return
}
// GroupEntry get entry group.
func (d *Dao) GroupEntry(c context.Context, ip string) (group *usmdl.PendantGroupInfo, err error) {
var res struct {
Code int `json:"code"`
Data *usmdl.PendantGroupInfo `json:"data"`
}
if err = d.http.Get(c, d.entryGroupURL, ip, nil, &res); err != nil {
log.Error("d.http.Get(%s) error(%v)", d.entryGroupURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.entryGroupURL, err)
return
}
group = res.Data
return
}
// GroupVip get vip group.
func (d *Dao) GroupVip(c context.Context, ip string) (group *usmdl.PendantGroupInfo, err error) {
var res struct {
Code int `json:"code"`
Data *usmdl.PendantGroupInfo `json:"data"`
}
if err = d.http.Get(c, d.vipGroupURL, ip, nil, &res); err != nil {
log.Error("d.http.Get(%s) error(%v)", d.vipGroupURL, err)
return
}
if res.Code != 0 {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.vipGroupURL, err)
return
}
group = res.Data
return
}
// Pendant get pendant info.
func (d *Dao) Pendant(c context.Context, pid int64, ip string) (pendant *usmdl.Pendant, err error) {
var res struct {
Code int `json:"code"`
Data *usmdl.Pendant `json:"data"`
}
params := url.Values{}
params.Set("pid", strconv.FormatInt(pid, 10))
if err = d.http.Get(c, d.pendantURL, ip, params, &res); err != nil {
log.Error("d.http.Get(%s) error(%v)", d.pendantURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.pendantURL, err)
return
}
pendant = res.Data
return
}
// Packages get package info.
func (d *Dao) Packages(c context.Context, mid int64, ip string) (pkg []*usmdl.PendantPackage, err error) {
var res struct {
Code int `json:"code"`
Data []*usmdl.PendantPackage `json:"data"`
}
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
if err = d.http.Get(c, d.packageURL, ip, params, &res); err != nil {
log.Error("d.http.Get(%s) error(%v)", d.packageURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.packageURL, err)
return
}
pkg = res.Data
return
}
// Order order pendant.
func (d *Dao) Order(c context.Context, mid, pid, expires int64, moneyType int8, ip string) (payInfo *usmdl.PayInfo, err error) {
params := url.Values{}
params.Set("moneytype", strconv.Itoa(int(expires)))
params.Set("expires", strconv.FormatInt(expires, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("pid", strconv.FormatInt(pid, 10))
var res struct {
Code int `json:"code"`
Data *usmdl.PayInfo `json:"data"`
}
if err = d.http.Post(c, d.orderURL, ip, params, &res); err != nil {
log.Error("d.http.Post(%d) url(%s) error(%v)", mid, d.orderURL, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Post(%d) url(%s) error(%v)", mid, d.orderURL, err)
return
}
payInfo = res.Data
return
}
// OrderHistory get order history by mid.
func (d *Dao) OrderHistory(c context.Context, mid, page int64, payType int8, orderID, ip string) (hs []*usmdl.PendantOrderInfo, count map[string]int64, err error) {
params := url.Values{}
params.Set("orderID", orderID)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("page", strconv.FormatInt(page, 10))
params.Set("payType", strconv.Itoa(int(payType)))
var res struct {
Code int `json:"code"`
Orders []*usmdl.PendantOrderInfo `json:"data"`
Count map[string]int64 `json:"count"`
}
if err = d.http.Get(c, d.orderHistory, ip, params, &res); err != nil {
log.Error("d.http.Get(%d) url(%s) error(%v)", mid, d.orderHistory, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.http.Get(%s) error(%v)", d.orderHistory, err)
return
}
hs = res.Orders
count = res.Count
return
}

View File

@@ -0,0 +1,16 @@
package usersuit
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_Group(t *testing.T) {
convey.Convey("Group", t, func() {
groups, err := d.Group(context.TODO(), "")
convey.So(err, convey.ShouldBeNil)
convey.So(groups, convey.ShouldNotBeEmpty)
})
}

View File

@@ -0,0 +1,35 @@
package usersuit
import (
"go-common/app/interface/main/account/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao struct.
type Dao struct {
c *conf.Config
http *bm.Client
orderURL string
orderHistory string
groupURL string
entryGroupURL string
vipGroupURL string
pendantURL string
packageURL string
}
// New new a Dao
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
http: bm.NewClient(c.HTTPClient.Normal),
groupURL: c.Host.API + _groupInfo,
orderURL: c.Host.API + _orderInfo,
orderHistory: c.Host.API + _orderHistory,
entryGroupURL: c.Host.API + _entryGroup,
vipGroupURL: c.Host.API + _vipGroup,
pendantURL: c.Host.API + _pendantInfo,
packageURL: c.Host.API + _packageInfo,
}
return
}

View File

@@ -0,0 +1,19 @@
package usersuit
import (
"flag"
"go-common/app/interface/main/account/conf"
)
var d *Dao
func init() {
flag.Parse()
flag.Set("conf", "../../cmd/account-interface-example.toml")
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
}

View File

@@ -0,0 +1,66 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"api_test.go",
"dao_test.go",
"oauth2_api_test.go",
"oauth2_client_test.go",
"vip_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
"oauth2_api.go",
"oauth2_client.go",
],
importpath = "go-common/app/interface/main/account/dao/vip",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//library/conf/env: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",
"//vendor/github.com/pkg/errors:go_default_library",
],
)

View File

@@ -0,0 +1,150 @@
package vip
import (
"context"
"fmt"
"net/url"
"strconv"
"go-common/app/interface/main/account/model"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_vipCodeVerify = "/x/internal/vip/code/verify"
_vipCodeOpen = "/x/internal/vip/code/open"
_viptips = "/x/internal/vip/tips"
_couponCancel = "/x/internal/vip/coupon/cancel"
_vipCodeOpened = "/x/internal/vip/code/opened"
// vip with java
_vipInfo = "/internal/v1/user/"
)
//CodeVerify code verify
func (d *Dao) CodeVerify(c context.Context) (token *model.Token, err error) {
ip := metadata.String(c, metadata.RemoteIP)
var tokenResq *model.TokenResq
val := url.Values{}
if err = d.client.Get(c, d.codeVerifyURL, ip, val, &tokenResq); err != nil {
err = errors.WithStack(err)
return
}
if tokenResq.Code == int64(ecode.OK.Code()) {
token = tokenResq.Data
}
return
}
//CodeOpen http code open
func (d *Dao) CodeOpen(c context.Context, mid int64, code, token, verify string) (data *model.ResourceCodeResq, err error) {
ip := metadata.String(c, metadata.RemoteIP)
val := url.Values{}
val.Add("mid", fmt.Sprintf("%v", mid))
val.Add("token", token)
val.Add("verify", verify)
val.Add("code", code)
defer func() {
log.Info("qingqiu url(%+v) params(%+v) return(%+v)", d.codeOpenURL, val, data)
}()
if err = d.client.Post(c, d.codeOpenURL, ip, val, &data); err != nil {
err = errors.WithStack(err)
return
}
if data.Code > int64(ecode.OK.Code()) {
err = ecode.Int(int(data.Code))
return
}
return
}
// Info get vip info
func (d *Dao) Info(c context.Context, mid int64, ip string) (info *model.VIPInfo, err error) {
var res struct {
Code int `json:"code"`
Data *model.VIPInfo `json:"data"`
}
if err = d.client.Get(c, d.infoURL+strconv.FormatInt(mid, 10), ip, nil, &res); err != nil {
log.Error("d.client.Get(%d) error(%v)", mid, err)
return
}
if res.Code != ecode.OK.Code() {
err = ecode.Int(res.Code)
log.Error("d.client.Get(%d) error(%v)", mid, err)
return
}
info = res.Data
return
}
// Tips tips info.
func (d *Dao) Tips(c context.Context, version int64, platform string) (data *vipmol.TipsResp, err error) {
params := url.Values{}
params.Add("version", fmt.Sprintf("%v", version))
params.Add("platform", platform)
var resp struct {
Code int `json:"code"`
Data *vipmol.TipsResp `json:"data"`
}
if err = d.client.Get(c, d.tipsURL, "", params, &resp); err != nil {
err = errors.Errorf("vip tips d.httpClient.Do(%s) error(%+v)", d.tipsURL+"?"+params.Encode(), err)
return
}
if resp.Code != ecode.OK.Code() {
err = errors.Errorf("vip tips url(%s) res(%+v) err(%+v)", d.tipsURL+"?"+params.Encode(), resp, ecode.Int(resp.Code))
}
data = resp.Data
return
}
// CancelUseCoupon cancel use coupon.
func (d *Dao) CancelUseCoupon(c context.Context, arg *vipmol.ArgCancelUseCoupon) (err error) {
params := url.Values{}
params.Add("mid", fmt.Sprintf("%d", arg.Mid))
params.Add("coupon_token", arg.CouponToken)
var resp struct {
Code int `json:"code"`
}
if err = d.clientSlow.Post(c, d.cancelCouponURL, "", params, &resp); err != nil {
err = errors.Errorf("vip cancel coupon d.httpClient.Do(%s) error(%+v)", d.cancelCouponURL+"?"+params.Encode(), err)
return
}
if resp.Code != ecode.OK.Code() {
err = ecode.Int(resp.Code)
}
return
}
//CodeOpeneds sel code opened data
func (d *Dao) CodeOpeneds(c context.Context, arg *model.CodeInfoReq, ip string) (resp []*vipmol.CodeInfoResp, err error) {
val := url.Values{}
val.Add("bis_appkey", arg.Appkey)
val.Add("bis_sign", arg.Sign)
val.Add("bis_ts", strconv.FormatInt(arg.Ts.Time().Unix(), 10))
val.Add("start_time", strconv.FormatInt(arg.StartTime.Time().Unix(), 10))
val.Add("end_time", strconv.FormatInt(arg.EndTime.Time().Unix(), 10))
val.Add("cursor", strconv.FormatInt(arg.Cursor, 10))
rep := new(struct {
Code int `json:"code"`
Data []*vipmol.CodeInfoResp `json:"data"`
})
defer func() {
log.Info("vip code opened url:%+v params:%+v return:%+v", d.codeOpenedURL, val, rep)
}()
if err = d.client.Get(c, d.codeOpenedURL, ip, val, rep); err != nil {
err = errors.Errorf("vip code opened url:%+v params:%+v return:%+v,err:%+v", d.codeOpenedURL, val, rep, err)
return
}
if rep.Code != ecode.OK.Code() {
err = ecode.Int(rep.Code)
return
}
resp = rep.Data
return
}

View File

@@ -0,0 +1,42 @@
package vip
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestVipCodeVerify(t *testing.T) {
convey.Convey("CodeVerify", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
token, err := d.CodeVerify(c)
convCtx.Convey("Then err should be nil.token should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(token, convey.ShouldNotBeNil)
})
})
})
}
func TestVipCodeOpen(t *testing.T) {
convey.Convey("CodeOpen", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
code = ""
token = ""
verify = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
data, err := d.CodeOpen(c, mid, code, token, verify)
convCtx.Convey("Then err should be nil.data should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(data, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,38 @@
package vip
import (
"go-common/app/interface/main/account/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao dao
type Dao struct {
c *conf.Config
client *bm.Client
clientSlow *bm.Client
infoURL string
codeOpenURL string
codeVerifyURL string
tipsURL string
cancelCouponURL string
codeOpenedURL string
cl *Clientl
}
// New new
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Normal),
clientSlow: bm.NewClient(c.HTTPClient.Slow),
infoURL: c.Host.Vip + _vipInfo,
codeOpenURL: c.Host.API + _vipCodeOpen,
codeVerifyURL: c.Host.API + _vipCodeVerify,
tipsURL: c.Host.API + _viptips,
cancelCouponURL: c.Host.API + _couponCancel,
codeOpenedURL: c.Host.API + _vipCodeOpened,
}
// http client for had url md5 sign.
d.cl = NewClientl(c.Vipproperty.OAuthClient, d.client)
return
}

View File

@@ -0,0 +1,35 @@
package vip
import (
"flag"
"os"
"testing"
"go-common/app/interface/main/account/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.account-interface")
flag.Set("conf_token", "967eef77ad40b478234f11b0d489d6d6")
flag.Set("tree_id", "3815")
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/account-interface-example.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,36 @@
package vip
import (
"context"
"net/url"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
pkgerr "github.com/pkg/errors"
)
const (
_oauth2UserInfoPath = "/oauth2/user_info"
)
//OAuth2ByCode get user info by oauth2 code.
func (d *Dao) OAuth2ByCode(c context.Context, a *model.ArgAuthCode) (data *model.OAuth2InfoResp, err error) {
params := url.Values{}
params.Add("code", a.Code)
params.Add("grant_type", "authorization_code")
var res struct {
Code int `json:"code"`
Data *model.OAuth2InfoResp `json:"data"`
}
if err = d.cl.get(c, d.c.Host.PassportCom, _oauth2UserInfoPath, a.IP, params, &res); err != nil {
return
}
if res.Code != 0 {
err = ecode.Int(res.Code)
err = pkgerr.Wrap(err, "dao oauth2 userinfo")
return
}
data = res.Data
return
}

View File

@@ -0,0 +1,25 @@
package vip
import (
"context"
"fmt"
"testing"
"go-common/app/interface/main/account/model"
. "github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestDaoOAuth2
func TestDaoOAuth2(t *testing.T) {
Convey("TestDaoOAuth2", t, func() {
data, err := d.OAuth2ByCode(context.Background(), &model.ArgAuthCode{
Code: "778b91c87a43e4fdab6c647010b77566",
})
if fmt.Sprintf("%v", err) != "dao oauth2 userinfo: -907" {
So(err, ShouldBeNil)
So(data, ShouldNotBeNil)
}
So(fmt.Sprintf("%v", err) == "dao oauth2 userinfo: -907", ShouldBeTrue)
})
}

View File

@@ -0,0 +1,95 @@
package vip
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
xhttp "net/http"
"net/url"
"strings"
"go-common/library/conf/env"
bm "go-common/library/net/http/blademaster"
pkgerr "github.com/pkg/errors"
)
//Clientl Client is http client, for url sign.
type Clientl struct {
client *bm.Client
conf *bm.ClientConfig
}
// NewClientl new a http client.
func NewClientl(c *bm.ClientConfig, client *bm.Client) *Clientl {
// check appkey
if c.Key == "" || c.Secret == "" {
panic("http client must config appkey and appsecret")
}
cl := new(Clientl)
cl.client = client
cl.conf = c
return cl
}
const (
_httpHeaderRemoteIP = "x-backend-bili-real-ip"
_noKickUserAgent = "haoguanwei@bilibili.com "
)
func (cl *Clientl) get(c context.Context, host, path, realIP string, params url.Values, res interface{}) (err error) {
req, err := cl.newGetRequest(host, path, realIP, params)
if err != nil {
return
}
return cl.client.Do(c, req, res)
}
// newGetRequest new get http request with host, path, ip, values and headers, without sign.
func (cl *Clientl) newGetRequest(host, path, realIP string, params url.Values) (req *xhttp.Request, err error) {
if params == nil {
params = url.Values{}
}
params.Add("client_id", cl.conf.App.Key)
enc := sign(params, path, cl.conf.App.Secret)
ru := host + path
if enc != "" {
ru = ru + "?" + enc
}
req, err = xhttp.NewRequest(xhttp.MethodGet, ru, nil)
if err != nil {
err = pkgerr.Wrapf(err, "uri:%s", ru)
return
}
const (
_userAgent = "User-Agent"
)
if realIP != "" {
req.Header.Set(_httpHeaderRemoteIP, realIP)
}
req.Header.Set(_userAgent, _noKickUserAgent+" "+env.AppID)
return
}
func sign(params url.Values, path, secret string) string {
if params == nil {
params = url.Values{}
}
tmp := params.Encode()
if strings.IndexByte(tmp, '+') > -1 {
tmp = strings.Replace(tmp, "+", "%20", -1)
}
var b bytes.Buffer
b.WriteString(path)
b.WriteString("?")
b.WriteString(tmp)
b.WriteString(secret)
mh := md5.Sum(b.Bytes())
// query
var qb bytes.Buffer
qb.WriteString(tmp)
qb.WriteString("&sign=")
qb.WriteString(hex.EncodeToString(mh[:]))
return qb.String()
}

View File

@@ -0,0 +1,24 @@
package vip
import (
"net/url"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestVipsign(t *testing.T) {
convey.Convey("sign", t, func(convCtx convey.C) {
var (
params url.Values
path = ""
secret = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := sign(params, path, secret)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,29 @@
package vip
import (
"context"
"testing"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
. "github.com/smartystreets/goconvey/convey"
)
func TestDao_CodeVerify(t *testing.T) {
Convey("code verify", t, func() {
_, err := d.CodeVerify(context.TODO())
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestDaoCancelUseCoupon
func TestDaoCancelUseCoupon(t *testing.T) {
Convey("TestDaoCancelUseCoupon", t, func() {
err := d.CancelUseCoupon(context.TODO(), &vipmol.ArgCancelUseCoupon{
CouponToken: "672889783020180721180426",
Mid: 1,
})
So(err == ecode.CouPonTokenNotFoundErr, ShouldBeTrue)
})
}

View File

@@ -0,0 +1,85 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"app_info.go",
"card.go",
"coupon.go",
"geetest.go",
"http.go",
"invite.go",
"medal.go",
"member.go",
"notice.go",
"passport.go",
"pendant.go",
"pendant_new.go",
"point.go",
"realname.go",
"relation.go",
"remotelogin.go",
"sudo.go",
"vip.go",
"vip_associate.go",
"vip_third.go",
"vip_welfare.go",
"web_info.go",
],
importpath = "go-common/app/interface/main/account/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/account/conf:go_default_library",
"//app/interface/main/account/model:go_default_library",
"//app/interface/main/account/service/card:go_default_library",
"//app/interface/main/account/service/coupon:go_default_library",
"//app/interface/main/account/service/geetest:go_default_library",
"//app/interface/main/account/service/member:go_default_library",
"//app/interface/main/account/service/passport:go_default_library",
"//app/interface/main/account/service/point:go_default_library",
"//app/interface/main/account/service/realname:go_default_library",
"//app/interface/main/account/service/relation:go_default_library",
"//app/interface/main/account/service/usersuit:go_default_library",
"//app/interface/main/account/service/vip:go_default_library",
"//app/service/main/card/api/grpc/v1:go_default_library",
"//app/service/main/coupon/api:go_default_library",
"//app/service/main/coupon/model:go_default_library",
"//app/service/main/identify/api/grpc:go_default_library",
"//app/service/main/point/model:go_default_library",
"//app/service/main/relation/model:go_default_library",
"//app/service/main/usersuit/model:go_default_library",
"//app/service/main/vip/api:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//app/service/main/vip/verify:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/antispam:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/supervisor:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/metadata: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,173 @@
package http
import (
"io/ioutil"
"net/http"
"strconv"
usrmdl "go-common/app/service/main/usersuit/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"github.com/pkg/errors"
)
func updateFace(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
defer c.Request.Form.Del("face") // 防止日志不出现
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.Request.ParseMultipartForm(32 << 20)
face, err := func() ([]byte, error) {
fs := c.Request.FormValue("face")
if fs != "" {
log.Info("Succeeded to parse face file from form value: mid: %d, length: %d", mid, len(fs))
return []byte(fs), nil
}
log.Warn("Failed to parse face file from form value, fallback to form file: mid: %d", mid)
f, _, err := c.Request.FormFile("face")
if err != nil {
return nil, errors.Wrapf(err, "parse face form file: mid: %d", mid)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Wrapf(err, "read face form file: mid: %d", mid)
}
if len(data) <= 0 {
return nil, errors.Wrapf(err, "form file data: mid: %d, length: %d", mid, len(data))
}
log.Info("Succeeded to parse file from form file: mid: %d, length: %d", mid, len(data))
return data, nil
}()
if err != nil {
log.Error("Failed to parse face file: mid: %d: %+v", mid, err)
c.JSON(nil, ecode.RequestErr)
return
}
log.Info("Succeeded to parse face data: mid: %d, face-length: %d", mid, len(face))
if len(face) > 2*1024*1024 {
c.JSON(nil, ecode.UpdateFaceSize)
return
}
ftype := http.DetectContentType(face)
if ftype != "image/jpeg" && ftype != "image/png" && ftype != "image/jp2" {
c.JSON(nil, ecode.UpdateFaceFormat)
return
}
c.JSON(memberSvc.UpdateFace(c, mid.(int64), face, ftype))
}
func updateSex(c *bm.Context) {
var (
err error
sex int64
//ip = c.RemoteIP()
params = c.Request.Form
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
if sex, err = strconv.ParseInt(params.Get("sex"), 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, memberSvc.UpdateSex(c, mid.(int64), sex))
}
func updateSign(c *bm.Context) {
var (
//ip = c.RemoteIP()
params = c.Request.Form
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
sign := params.Get("user_sign")
c.JSON(nil, memberSvc.UpdateSign(c, mid.(int64), sign))
}
func updateBirthday(c *bm.Context) {
var (
birthday string
//ip = c.RemoteIP()
params = c.Request.Form
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
if birthday = params.Get("birthday"); len(birthday) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, memberSvc.UpdateBirthday(c, mid.(int64), birthday))
}
func updateUname(c *bm.Context) {
var (
uname string
//ip = c.RemoteIP()
params = c.Request.Form
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
if uname = params.Get("uname"); len(uname) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, memberSvc.UpdateName(c, mid.(int64), uname, params.Get("appkey")))
}
func nickFree(c *bm.Context) {
var (
mid, ok = c.Get("mid")
//ip = c.RemoteIP()
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.NickFree(c, mid.(int64)))
}
func pendantEquip(c *bm.Context) {
var (
mid, ok = c.Get("mid")
params = c.Request.Form
err error
pid int64
status int64
source int64
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
if pid, err = strconv.ParseInt(params.Get("pid"), 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if status, err = strconv.ParseInt(params.Get("status"), 10, 64); err != nil || (status != usrmdl.PendantPutOn && status != usrmdl.PendantPickOff) {
c.JSON(nil, ecode.RequestErr)
return
}
// source 挂件来源 可选, 默认0 0未知 1 背包挂件 2大会员挂件
source = usrmdl.ParseSource(params.Get("source"))
c.JSON(nil, usSvc.Equip(c, mid.(int64), pid, int8(status), source))
}

View File

@@ -0,0 +1,71 @@
package http
import (
"go-common/app/interface/main/account/model"
cardv1 "go-common/app/service/main/card/api/grpc/v1"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func userCard(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(cardSvc.UserCard(c, mid.(int64)))
}
func cardInfo(c *bm.Context) {
var err error
arg := new(model.ArgCardID)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(cardSvc.Card(c, arg.ID))
}
func cardHots(c *bm.Context) {
c.JSON(cardSvc.CardHots(c))
}
func cardGroups(c *bm.Context) {
var mid int64
midi, exists := c.Get("mid")
if exists {
mid = midi.(int64)
}
c.JSON(cardSvc.AllGroup(c, mid))
}
func cardsByGid(c *bm.Context) {
var err error
arg := new(model.ArgGroupID)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(cardSvc.CardsByGid(c, arg.ID))
}
func equip(c *bm.Context) {
var err error
arg := new(model.ArgCardID)
if err = c.Bind(arg); err != nil {
return
}
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(nil, cardSvc.Equip(c, &cardv1.ModelArgEquip{Mid: mid.(int64), CardId: arg.ID}))
}
func demount(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(nil, cardSvc.Demount(c, mid.(int64)))
}

View File

@@ -0,0 +1,111 @@
package http
import (
"go-common/app/interface/main/account/model"
v1 "go-common/app/service/main/coupon/api"
col "go-common/app/service/main/coupon/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
func allowanceList(c *bm.Context) {
var (
err error
)
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
arg := new(model.ArgAllowanceList)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(couponSvc.AllowanceList(c, mid.(int64), arg.State))
}
func couponPage(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
arg := new(model.ArgCouponPage)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(couponSvc.CouponPage(c, &col.ArgRPCPage{
Mid: mid.(int64),
State: arg.State,
Pn: arg.Pn,
Ps: arg.Ps,
}))
}
// func couponCartoonPage(c *bm.Context) {
// var err error
// mid, exists := c.Get("mid")
// if !exists {
// c.JSON(nil, ecode.AccountNotLogin)
// return
// }
// arg := new(model.ArgCouponPage)
// if err = c.Bind(arg); err != nil {
// return
// }
// c.JSON(couponSvc.CouponCartoonPage(c, &col.ArgRPCPage{
// Mid: mid.(int64),
// State: arg.State,
// Pn: arg.Pn,
// Ps: arg.Ps,
// }))
// }
func prizeCards(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(couponSvc.PrizeCards(c, &col.ArgCount{Mid: mid.(int64)}))
}
func prizeDraw(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
arg := new(model.ArgPrizeDraw)
if err = c.Bind(arg); err != nil {
return
}
if arg.CardType == -1 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(couponSvc.PrizeDraw(c, &col.ArgPrizeDraw{Mid: mid.(int64), CardType: arg.CardType}))
}
func captchaToken(c *bm.Context) {
c.JSON(couponSvc.CaptchaToken(c, &v1.CaptchaTokenReq{Ip: metadata.String(c, metadata.RemoteIP)}))
}
func useCouponCode(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
arg := new(col.ArgUseCouponCode)
if err = c.Bind(arg); err != nil {
return
}
arg.IP = metadata.String(c, metadata.RemoteIP)
arg.Mid = mid.(int64)
c.JSON(couponSvc.UseCouponCode(c, arg))
}

View File

@@ -0,0 +1,51 @@
package http
import (
"strings"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
// getChallenge get geetest params gt ,challenge
func getChallenge(c *bm.Context) {
params := new(model.GeeCaptchaRequest)
var (
mid, ok = c.Get("mid")
mobile = strings.Contains(c.Request.UserAgent(), model.MobileUserAgentFlag)
)
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
if mobile {
params.ClientType = model.PlatH5
} else {
params.ClientType = model.PlatPC
}
params.MID = mid.(int64)
c.JSON(geetestSvr.PreProcess(c, params))
}
func geetestValidate(c *bm.Context) {
params := new(model.GeeCheckRequest)
if err := c.Bind(params); err != nil {
return
}
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
params.MID = mid.(int64)
if params.MID == 0 {
c.JSON(nil, ecode.RequestErr)
}
if strings.Contains(c.Request.UserAgent(), model.MobileUserAgentFlag) {
params.ClientType = model.PlatH5
} else {
params.ClientType = model.PlatPC
}
c.JSON(geetestSvr.Validate(c, params), nil)
}

View File

@@ -0,0 +1,355 @@
package http
import (
"net/http"
"go-common/app/interface/main/account/conf"
"go-common/app/interface/main/account/service/card"
"go-common/app/interface/main/account/service/coupon"
"go-common/app/interface/main/account/service/geetest"
"go-common/app/interface/main/account/service/member"
"go-common/app/interface/main/account/service/passport"
"go-common/app/interface/main/account/service/point"
"go-common/app/interface/main/account/service/realname"
rls "go-common/app/interface/main/account/service/relation"
us "go-common/app/interface/main/account/service/usersuit"
"go-common/app/interface/main/account/service/vip"
vipverify "go-common/app/service/main/vip/verify"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/antispam"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/supervisor"
v "go-common/library/net/http/blademaster/middleware/verify"
)
var (
relationSvc *rls.Service
memberSvc *member.Service
passSvc *passport.Service
vipSvc *vip.Service
realnameSvc *realname.Service
usSvc *us.Service
couponSvc *coupon.Service
pointSvc *point.Service
cardSvc *card.Service
geetestSvr *geetest.Service
// api middleware
authn *auth.Auth
verify *v.Verify
anti *antispam.Antispam
batchRelAnti *antispam.Antispam
smsAnti *antispam.Antispam
faceAnti *antispam.Antispam
vipAnti *antispam.Antispam
spv *supervisor.Supervisor
// vip third verify
vipThirdVerify *vipverify.Verify
)
// Init init http sever instance.
func Init(c *conf.Config) {
// service
initService(c)
vipThirdVerify = vipverify.NewThirdVerify(c.VipThirdVerifyConfig)
// init outer router
// innerEngine := bm.DefaultServer(c.BM.Inner)
innerEngine := bm.NewServer(c.BM.Inner)
innerEngine.Use(bm.Recovery(), bm.Trace(), bm.Logger(), bm.Mobile())
setupInnerEngine(innerEngine)
if err := innerEngine.Start(); err != nil {
log.Error("innerEngine.Start() error(%v)", err)
panic(err)
}
}
func setupInnerEngine(e *bm.Engine) {
e.Ping(ping)
e.Register(register)
// member
mr := e.Group("/x/member", bm.CSRF())
mr.GET("/notice", authn.User, notice)
mr.POST("/notice/close", authn.User, closeNotice)
sec := mr.Group("/security", authn.User)
sec.GET("/status", status)
sec.POST("/feedback", feedback)
sec.POST("/close", closeNotify)
app := mr.Group("/app", authn.UserMobile)
app.GET("/nickfree", nickFree)
app.POST("/uname/update", spv.ServeHTTP, updateUname)
app.POST("/sign/update", spv.ServeHTTP, updateSign)
app.POST("/sex/update", updateSex)
app.POST("/birthday/update", updateBirthday)
app.POST("/face/update", spv.ServeHTTP, faceAnti.ServeHTTP, updateFace)
app.POST("/pendant/equip", pendantEquip)
app.GET("/point/flag", pointFlagMobile)
web := mr.Group("/web", authn.User)
web.POST("/update", spv.ServeHTTP, update)
web.POST("/face/update", spv.ServeHTTP, faceAnti.ServeHTTP, updateFace)
web.POST("/sign/update", spv.ServeHTTP, updateSign)
web.POST("/uname/update", spv.ServeHTTP, updateUname)
web.GET("/account", account)
web.GET("/reply/list", replyHistoryList)
web.GET("/coin/log", logCoin)
web.GET("/moral/log", logMoral)
web.GET("/exp/log", logExp)
web.GET("/exp/reward", reward)
web.GET("/login/log", logLogin)
web.GET("/coin", coin)
web.POST("/birthday/update", updateBirthday)
web.POST("/pendant/equip", pendantEquip)
web.GET("/point/flag", pointFlag)
sudo := mr.Group("/sudo", sudo)
sudo.POST("/notify-purge-cache", notityPurgeCache)
// captcha 验证码
cap := mr.Group("/captcha", authn.UserWeb)
cap.GET("/geetest", getChallenge) //获取极验图形验证
cap.POST("/geetest/check", geetestValidate) //校验极验验证码
// vip
vip := e.Group("/x/vip", bm.CSRF())
vip.GET("/code/verify", authn.User, codeVerify)
vip.POST("/code/open", authn.User, codeOpen)
vip.GET("/tips", authn.User, tips)
vip.GET("/price/panel", authn.User, vipAnti.ServeHTTP, vipPanel)
vip.GET("/coupon/list", authn.User, vipAnti.ServeHTTP, couponList)
vip.GET("/coupon/usable", authn.User, vipAnti.ServeHTTP, couponUsable)
vip.POST("/coupon/unlock", authn.User, vipAnti.ServeHTTP, couponUnlock)
vip.GET("/privilege/bysid", vipAnti.ServeHTTP, privilegeBySid)
vip.GET("/privilege/bytype", vipAnti.ServeHTTP, privilegeByType)
vip.GET("/manager", authn.User, vipAnti.ServeHTTP, vipManagerInfo)
vip.POST("/unfreeze", authn.UserWeb, vipAnti.ServeHTTP, unfrozen)
vip.GET("/frozenTime", authn.UserWeb, vipAnti.ServeHTTP, frozenTime)
vip.GET("/code/openeds", vipAnti.ServeHTTP, codeOpeneds)
vip.GET("/public/panel", authn.Guest, vipAnti.ServeHTTP, publicPriceList)
vip.POST("/batch/use", vipAnti.ServeHTTP, useBatch)
vip.GET("/order/status", authn.UserWeb, orderStatus)
vip.GET("/price/panel/v8", authn.Guest, vipAnti.ServeHTTP, vipPanelV8)
vip.GET("/prize/cards", authn.UserWeb, vipAnti.ServeHTTP, prizeCards)
vip.POST("/prize/draw", authn.UserWeb, vipAnti.ServeHTTP, prizeDraw)
vip.GET("/resource/banner", authn.UserMobile, vipAnti.ServeHTTP, resourceBanner) // 大会员落地页
vip.GET("/resource/buy", authn.UserMobile, vipAnti.ServeHTTP, resourceBuy) // 大会员购买页
vip.GET("/coupon/usable/v2", authn.Guest, vipAnti.ServeHTTP, couponBySuitIDV2)
vip.GET("/price/panel/v9", authn.Guest, vipAnti.ServeHTTP, vipPanelV9)
// associate
vip.GET("/associate/info", authn.User, bindInfoByMid)
vip.GET("/associate/panel", authn.User, actlimit, associatePanel)
vip.POST("/associate/create/order", authn.User, actlimit, createAssociateOrder)
vip.GET("/associate/ele/oauth", authn.User, actlimit, eleOAuthURL)
vip.GET("/associate/ele/redpackets", redpackets)
vip.GET("/associate/ele/specailfoods", specailfoods)
//vip welfare
vip.GET("/welfare/list", authn.Guest, welfareList)
vip.GET("/welfare/type", authn.Guest, welfareTypeList)
vip.GET("/welfare/info", authn.Guest, welfareInfo)
vip.POST("/welfare", authn.User, vipAnti.ServeHTTP, receiveWelfare)
vip.GET("/welfare/my", authn.User, myWelfare)
// vip third verify.
// ele oauth callback.
e.GET("/x/oauth2/v1/callback", authn.User, actlimit, openAuthCallBack)
// bilibili third.
oauth2 := e.Group("/x/oauth2/v1", iplimit, vipThirdVerify.Verify, bm.CSRF())
oauth2.POST("/access_token", openIDByOAuth2Code)
// bilibili third vip.
vipThird := oauth2.Group("/vip", iplimit, openlimit)
vipThird.POST("/bind", openBindByOutOpenID)
vipThird.GET("/account", userInfoByOpenID)
vipThird.POST("/delivery", bilibiliVipGrant)
vipThird.POST("/prize/grant", bilibiliPrizeGrant)
// vip app api
vip.GET("/v1/order/status", authn.UserMobile, orderStatus)
vip.GET("/v1/frozenTime", authn.UserMobile, vipAnti.ServeHTTP, frozenTime)
vip.POST("/v1/unfrozen", authn.UserMobile, vipAnti.ServeHTTP, unfrozen)
vip.GET("/v2/tips", authn.User, tipsv2)
vip.GET("/v2/price/panel", authn.Guest, vipAnti.ServeHTTP, vipPanelV2)
invite := mr.Group("/invite", authn.UserWeb)
invite.GET("/stat", inviteStat)
invite.POST("/buy", buy)
invite.POST("/apply", apply)
// medal 勋章
medal := mr.Group("/medal")
// medal.GET("/user/info", authn.User, medalHomeInfo)
medal.GET("/user/info", authn.User, medalUserInfo)
medal.POST("/install", authn.User, medalInstall)
medal.GET("/popup", authn.User, medalPopup)
medal.GET("/my/info", authn.User, medalMyInfo)
medal.GET("/all/info", authn.User, medalAllInfo)
official := mr.Group("/official", bm.CSRF(), authn.User)
official.POST("/submit", submitOffical)
official.GET("/doc", officialDoc)
official.GET("/conditions", officialConditions)
official.POST("/upload/image", uploadImage)
official.POST("/mobile/verify", smsAnti.ServeHTTP, mobileVerify)
official.GET("/permission", officialPermission)
official.GET("/auto/fill/doc", officialAutoFillDoc)
official.GET("/monthly/times", monthlyOfficialSubmittedTimes)
identifyG := mr.Group("/identify", authn.UserWeb)
identifyG.GET("/info", identifyInfo)
// realname
realnameG := mr.Group("/realname", authn.User)
realnameG.GET("/channel", realnameChannel)
realnameG.GET("/status", realnameStatus)
realnameG.GET("/apply/status", realnameApplyStatus)
realnameG.POST("/apply", realnameApply)
realnameG.POST("/upload", realnameUpload)
realnameG.GET("/preview", realnamePreview)
realnameG.GET("/countrylist", realnameCountryList)
realnameG.GET("/card/types", realnameCardTypes)
realnameG.GET("/v2/card/types", realnameCardTypesV2)
realnameG.POST("/tel/capture", realnameTelCapture)
realnameG.GET("/tel/info", realnameTelInfo)
realnameG.GET("/captcha", realnameCaptcha)
realnameG.GET("/captcha/refresh", realnameCaptchaRefresh)
realnameG.GET("/captcha/confirm", realnameCaptchaConfirm)
realnameG.POST("/alipay/apply", realnameAlipayApply)
realnameG.GET("/alipay/confirm", realnameAlipayConfirm)
// passport
passportR := mr.Group("/passport", authn.User)
passportR.GET("/testUserName", testUserName)
// member v2
memberV2 := e.Group("x/member/v2", bm.CSRF())
memberV2.GET("/notice", authn.UserMobile, noticeV2)
memberV2.POST("/notice/close", authn.UserMobile, closeNoticeV2)
// relation
relationG := e.Group("/x/relation", bm.CSRF())
relationG.GET("", authn.User, relation)
relationG.GET("/relations", authn.User, relations)
relationG.GET("/blacks", authn.User, blacks)
relationG.GET("/whispers", authn.User, whispers)
relationG.GET("/friends", authn.User, friends)
relationG.POST("/modify", authn.User, anti.ServeHTTP, modify)
relationG.POST("/batch/modify", authn.User, batchRelAnti.ServeHTTP, batchModify)
relationG.GET("/followings", authn.Guest, followings)
relationG.GET("/same/followings", authn.User, sameFollowings)
relationG.GET("/followers", authn.Guest, followers)
relationG.GET("/stat", authn.Guest, stat)
relationG.GET("/stats", authn.Guest, stats)
relationG.GET("/recommend", authn.User, recommend)
relationG.GET("/recommend/followlist_empty", authn.User, bm.Mobile(), recommendFollowlistEmpty)
relationG.GET("/recommend/answer_ok", authn.User, bm.Mobile(), recommendAnswerOK)
relationG.GET("/recommend/tag_suggest", authn.User, bm.Mobile(), recommendTagSuggest)
relationG.GET("/recommend/tag_suggest/detail", authn.User, bm.Mobile(), recommendTagSuggestDetail)
// relation tag
relationG.GET("/tag", authn.User, tag)
relationG.GET("/tags", authn.User, tags)
relationG.POST("/tag/special/add", authn.User, addSpecial)
relationG.POST("/tag/special/del", authn.User, delSpecial)
relationG.GET("/tag/special", authn.User, special)
relationG.GET("/tag/user", authn.User, tagUser)
relationG.POST("/tag/create", authn.User, tagCreate)
relationG.POST("/tag/update", authn.User, tagUpdate)
relationG.POST("/tag/del", authn.User, tagDel)
relationG.POST("/tags/addUsers", authn.User, tagsAddUsers)
relationG.POST("/tags/copyUsers", authn.User, tagsCopyUsers)
relationG.POST("/tags/moveUsers", authn.User, tagsMoveUsers)
// for mobile.
relationG.GET("/tag/m/tags", authn.User, mobileTags)
// 提示用户关注该up主
relationG.POST("/prompt", authn.User, prompt)
relationG.POST("/prompt/close", authn.User, closePrompt)
// 粉丝提醒功能
relationG.GET("/followers/unread", authn.User, unread)
relationG.POST("/followers/unread/reset", authn.User, unreadReset)
relationG.GET("/followers/unread/count", authn.User, unreadCount)
relationG.POST("/followers/unread/count/reset", authn.User, unreadCountReset)
relationG.GET("/followers/notify", authn.User, followerNotifySetting)
relationG.POST("/followers/notify/enable", authn.User, enableFollowerNotify)
relationG.POST("/followers/notify/disable", authn.User, disableFollowerNotify)
// achieve
relationG.POST("/achieve/award/get", authn.User, achieveGet)
relationG.GET("/achieve/award", authn.Guest, achieve)
// pendant group
pendant := e.Group("/x/pendant", bm.CSRF())
// pendant with web
pendant.GET("/current", authn.UserWeb, pendantCurrent)
pendant.GET("/all", authn.UserWeb, pendantAll)
pendant.GET("/my", authn.UserWeb, pendantMy)
pendant.GET("/myHistory", authn.UserWeb, pendantMyHistory)
pendant.GET("/bigEntry", authn.UserWeb, pendantEntry)
pendant.GET("/vipRecommend", authn.UserWeb, pendantVIP)
pendant.POST("/checkOrder", authn.UserWeb, pendantCheckOrder)
pendant.POST("/vipGet", authn.UserWeb, pendantVIPGet)
pendant.POST("/order", authn.UserWeb, pendantOrder)
// pendant with app
pendant.GET("/pointEntry", authn.UserMobile, pendantEntry)
// pendent with vri
pendant.GET("/single", verify.Verify, pendantSingle)
coupon := e.Group("/x/coupon", bm.CSRF(), authn.User)
coupon.GET("/allowance/list", allowanceList)
coupon.GET("/list", couponPage)
coupon.GET("/code/verify", captchaToken)
coupon.POST("/code/exchange", useCouponCode)
point := e.Group("/x/point", bm.CSRF(), authn.User)
point.GET("/info", pointInfo)
point.GET("/history", pointPage)
card := e.Group("/x/card", bm.CSRF())
card.GET("/bymid", authn.User, userCard)
card.GET("/info", cardInfo)
card.GET("/hots", cardHots)
card.GET("/groups", authn.Guest, cardGroups)
card.GET("/bytype", cardsByGid)
card.POST("/equip", authn.User, equip)
card.POST("/demount", authn.User, demount)
}
// ping check server ok.
func ping(c *bm.Context) {
var err error
if err = memberSvc.Ping(c); err != nil {
c.JSON(nil, err)
log.Error("service ping error(%v)", err)
c.Writer.WriteHeader(http.StatusServiceUnavailable)
}
}
func register(ctx *bm.Context) {
ctx.JSON(nil, nil)
}
func initService(c *conf.Config) {
relationSvc = rls.New(c)
memberSvc = member.New(c)
realnameSvc = realname.New(c, conf.RsaPub(), conf.RsaPriv(), conf.AlipayPub(), conf.AlipayBiliPriv())
passSvc = passport.New(c)
cardSvc = card.New(c)
vipSvc = vip.New(c)
usSvc = us.New(c)
geetestSvr = geetest.New(c)
// api middleware
authn = auth.New(c.AuthN)
verify = v.New(c.Verify)
anti = antispam.New(c.Antispam)
batchRelAnti = antispam.New(c.BatchRelAntispam)
smsAnti = antispam.New(c.SMSAntispam)
faceAnti = antispam.New(c.FaceAntispam)
vipAnti = antispam.New(c.VIPAntispam)
spv = supervisor.New(c.Supervisor)
couponSvc = coupon.New(c)
pointSvc = point.New(c)
}

View File

@@ -0,0 +1,70 @@
package http
import (
"strconv"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// stat get invite stat.
func inviteStat(c *bm.Context) {
mid, _ := c.Get("mid")
var err error
var stat *model.RichInviteStat
if stat, err = usSvc.Stat(c, mid.(int64)); err != nil {
log.Error("memberService.Stat(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(stat, nil)
}
// buy buy invite code.
func buy(c *bm.Context) {
mid, _ := c.Get("mid")
var err error
var num int64
req := c.Request.Form
numStr := req.Get("num")
if num, err = strconv.ParseInt(numStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
geeParam := new(model.GeeCheckRequest)
if err = c.Bind(geeParam); err != nil {
return
}
geeParam.MID = mid.(int64)
if isPass := geetestSvr.Validate(c, geeParam); !isPass {
c.JSON(nil, ecode.CaptchaErr)
return
}
var invs []*model.RichInvite
if invs, err = usSvc.Buy(c, mid.(int64), num); err != nil {
log.Error("memberService.Buy(%d, %d) error(%v)", mid, num, err)
c.JSON(nil, err)
return
}
c.JSON(invs, nil)
}
// apply apply invite code.
func apply(c *bm.Context) {
mid, _ := c.Get("mid")
var err error
var num int64
code := c.Request.Form.Get("invite_code")
if code == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if err = usSvc.Apply(c, mid.(int64), code, c.Request.Header.Get("Cookie")); err != nil {
log.Error("memberService.Apply(%d, %d) error(%v)", mid, num, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}

View File

@@ -0,0 +1,84 @@
package http
import (
"strconv"
"go-common/app/service/main/usersuit/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func medalUserInfo(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
//ip = c.RemoteIP()
data *model.MedalUserInfo
)
if data, err = memberSvc.MedalUserInfo(c, mid.(int64)); err != nil {
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}
func medalInstall(c *bm.Context) {
var (
err error
nid, isActivated int64
mid, _ = c.Get("mid")
)
nidStr := c.Request.Form.Get("nid")
if nid, err = strconv.ParseInt(nidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
isActivatedStr := c.Request.Form.Get("isActivated")
if isActivated, err = strconv.ParseInt(isActivatedStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
err = memberSvc.MedalInstall(c, mid.(int64), nid, int8(isActivated))
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func medalPopup(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
data *model.MedalPopup
)
if data, err = memberSvc.MedalPopup(c, mid.(int64)); err != nil {
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}
func medalMyInfo(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
data, err := memberSvc.MedalMyInfo(c, mid.(int64))
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}
func medalAllInfo(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
data, err := memberSvc.MedalAllInfo(c, mid.(int64))
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}

View File

@@ -0,0 +1,133 @@
package http
import (
"io/ioutil"
"net/http"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func identifyInfo(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
var (
resData struct {
Status model.IdentifyStatus `json:"identification"`
}
status int8
err error
)
if status, err = realnameSvc.Status(c, mid.(int64)); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
switch status {
case 1:
resData.Status = model.IdentifyOK
case 0:
resData.Status = model.IdentifyNotOK
}
c.JSON(resData, nil)
}
func submitOffical(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
params := new(model.OfficialApply)
if err := c.Bind(params); err != nil {
return
}
c.JSON(nil, memberSvc.SubmitOfficial(c, mid.(int64), params))
}
func officialDoc(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(memberSvc.OfficialDoc(c, mid.(int64)))
}
func officialConditions(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(memberSvc.OfficialConditions(c, mid.(int64)))
}
func uploadImage(c *bm.Context) {
midI, _ := c.Get("mid")
mid := midI.(int64)
log.Infov(c, log.KV("log", "account-interface: upload image"), log.KV("mid", mid))
file, _, err := c.Request.FormFile("file")
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
defer file.Close()
bs, err := ioutil.ReadAll(file)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
ftype := http.DetectContentType(bs)
if ftype != "image/jpeg" && ftype != "image/jpg" && ftype != "image/png" && ftype != "image/gif" {
log.Error("account-interface: file type not allow file type(%s, mid: %v)", ftype, mid)
c.JSON(nil, ecode.RequestErr)
return
}
url, err := memberSvc.UploadImage(c, ftype, bs)
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"url": url,
"size": len(bs),
}, nil)
}
func mobileVerify(c *bm.Context) {
midI, _ := c.Get("mid")
arg := &model.ArgMobileVerify{}
if err := c.Bind(arg); err != nil {
return
}
if arg.Country == 0 {
arg.Country = 86
}
c.JSON(nil, memberSvc.MobileVerify(c, midI.(int64), arg.Mobile, arg.Country))
}
func officialPermission(ctx *bm.Context) {
resp := &model.OfficialPermissionResponse{
DeniedRoles: []int8{},
Metadata: map[string]interface{}{},
}
ctx.JSON(resp, nil)
}
func monthlyOfficialSubmittedTimes(ctx *bm.Context) {
midI, _ := ctx.Get("mid")
ctx.JSON(memberSvc.MonthlyOfficialSubmittedTimes(ctx, midI.(int64)), nil)
}
func officialAutoFillDoc(ctx *bm.Context) {
midI, _ := ctx.Get("mid")
ctx.JSON(memberSvc.OfficialAutoFillDoc(ctx, midI.(int64)))
}

View File

@@ -0,0 +1,63 @@
package http
import (
"strconv"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func notice(c *bm.Context) {
c.JSON(struct{}{}, nil)
}
func closeNotice(c *bm.Context) {
c.JSON(struct{}{}, nil)
}
func noticeV2(c *bm.Context) {
var (
params = c.Request.Form
pf string
build int64
)
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
uuid := params.Get("uuid")
if uuid == "" {
c.JSON(nil, ecode.RequestErr)
return
}
pf = params.Get("platform")
build, _ = strconv.ParseInt(params.Get("build"), 10, 64)
n, err := memberSvc.NoticeV2(c, mid.(int64), uuid, pf, build)
if err != nil {
log.Error("memberSvc.NoticeV2(%d, %s) error(%v)", mid, uuid, err)
c.JSON(nil, err)
return
}
c.JSON(n, nil)
}
func closeNoticeV2(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
uuid := c.Request.Form.Get("uuid")
if uuid == "" {
c.JSON(nil, ecode.RequestErr)
return
}
err := memberSvc.CloseNoticeV2(c, mid.(int64), uuid)
if err != nil {
log.Error("memberSvc.CloseNoticeV2(%d, %s) error(%v)", mid, uuid, err)
c.JSON(nil, err)
}
c.JSON(nil, nil)
}

View File

@@ -0,0 +1,20 @@
package http
import (
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func testUserName(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
name := c.Request.Form.Get("name")
if name == "" {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, passSvc.TestUserName(c, name, mid.(int64)))
}

View File

@@ -0,0 +1,166 @@
package http
import (
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"strconv"
)
func pendantAll(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(usSvc.Group(c, mid.(int64)))
}
func pendantMy(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(usSvc.My(c, mid.(int64)))
}
func pendantMyHistory(c *bm.Context) {
//ip := c.RemoteIP()
mid, ok := c.Get("mid")
pageStr := c.Request.Form.Get("page")
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
page, _ := strconv.ParseInt(pageStr, 10, 64)
c.JSON(usSvc.MyHistory(c, mid.(int64), page))
}
func pendantCurrent(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(usSvc.Equipment(c, mid.(int64)))
}
func pendantEntry(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(usSvc.GroupEntry(c, mid.(int64)))
}
func pendantSingle(c *bm.Context) {
pidStr := c.Request.Form.Get("pid")
//ip := c.RemoteIP()
pid, err := strconv.ParseInt(pidStr, 10, 64)
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(usSvc.Pendant(c, pid))
}
func pendantVIP(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(usSvc.GroupVIP(c, mid.(int64)))
}
func pendantCheckOrder(c *bm.Context) {
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
orderID := c.Request.Form.Get("orderId")
c.JSON(nil, usSvc.CheckOrder(c, mid.(int64), orderID))
}
func pendantVIPGet(c *bm.Context) {
params := c.Request.Form
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
pidStr := params.Get("pid")
pid, err := strconv.ParseInt(pidStr, 10, 64)
if err != nil {
c.JSON(nil, err)
return
}
if pid == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
activatedStr := params.Get("isActivated")
activated, err := strconv.Atoi(activatedStr)
if err != nil {
c.JSON(nil, err)
return
}
if activated == 0 {
activated = 1
} else {
activated = 2
}
c.JSON(nil, usSvc.VipGet(c, mid.(int64), pid, int8(activated)))
}
func pendantOrder(c *bm.Context) {
params := c.Request.Form
mid, ok := c.Get("mid")
//ip := c.RemoteIP()
if !ok {
c.JSON(nil, ecode.AccountNotLogin)
return
}
pidStr := params.Get("pid")
pid, err := strconv.ParseInt(pidStr, 10, 64)
if err != nil {
c.JSON(nil, err)
return
}
timeLengthStr := params.Get("timeLength")
timeLength, err := strconv.ParseInt(timeLengthStr, 10, 64)
if err != nil {
c.JSON(nil, err)
return
}
if pid <= 0 || timeLength <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
var (
moneyType int8
moneyTypeStr string
)
moneyTypeStr = params.Get("moneyType")
switch moneyTypeStr {
case "coin":
moneyType = 0
case "bcoin":
moneyType = 1
case "point":
moneyType = 2
default:
c.JSON(nil, ecode.PendantPayTypeErr)
return
}
c.JSON(usSvc.Order(c, mid.(int64), pid, timeLength, moneyType))
}

View File

@@ -0,0 +1,42 @@
package http
import (
usmdl "go-common/app/service/main/usersuit/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
const _mobilePendant = "http://account.bilibili.com/mobile/pendant/#/my"
func pointFlagMobile(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
var (
err error
pointFlag struct {
Link struct {
PendantLink string `json:"pendant_link"`
MedalLink string `json:"medal_link"`
} `json:"link"`
Flag *usmdl.PointFlag `json:"flag"`
}
)
if pointFlag.Flag, err = usSvc.PointFlag(c, &usmdl.ArgMID{MID: mid.(int64)}); err != nil {
c.JSON(nil, err)
return
}
pointFlag.Link.PendantLink = _mobilePendant
c.JSON(pointFlag, nil)
}
func pointFlag(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(usSvc.PointFlag(c, &usmdl.ArgMID{MID: mid.(int64)}))
}

View File

@@ -0,0 +1,31 @@
package http
import (
"go-common/app/service/main/point/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func pointInfo(c *bm.Context) {
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(pointSvc.PointInfo(c, mid.(int64)))
}
func pointPage(c *bm.Context) {
var err error
mid, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
arg := new(model.ArgRPCPointHistory)
if err = c.Bind(arg); err != nil {
return
}
arg.Mid = mid.(int64)
c.JSON(pointSvc.PointPage(c, arg))
}

View File

@@ -0,0 +1,328 @@
package http
import (
"io/ioutil"
"net/http"
"strconv"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// modify modify user relation.
func realnameStatus(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
)
var resData struct {
Status int8 `json:"status"`
}
if resData.Status, err = realnameSvc.Status(c, mid.(int64)); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameApplyStatus(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
)
var resData struct {
Status int8 `json:"status"`
Remark string `json:"remark"`
Realname string `json:"realname"`
Card string `json:"card"`
}
if resData.Status, resData.Remark, resData.Realname, resData.Card, err = realnameSvc.ApplyStatus(c, mid.(int64)); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameCardTypes(c *bm.Context) {
var (
err error
params = c.Request.Form
platform = params.Get("platform")
buildStr = params.Get("build")
mobiapp = params.Get("mobi_app")
device = params.Get("device")
build int
)
if build, err = strconv.Atoi(buildStr); err != nil {
log.Error("%+v", errors.WithStack(err))
c.JSON(nil, ecode.RequestErr)
return
}
var resData []*model.RealnameCardType
if resData, err = realnameSvc.CardTypes(c, platform, mobiapp, device, build); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameCardTypesV2(c *bm.Context) {
var (
err error
)
var resData []*model.RealnameCardType
if resData, err = realnameSvc.CardTypesV2(c); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameCountryList(c *bm.Context) {
var (
err error
)
var resData []*model.RealnameCountry
if resData, err = realnameSvc.CountryList(c); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameTelCapture(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
)
if err = realnameSvc.TelCapture(c, mid.(int64)); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func realnameTelInfo(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
)
var resData struct {
Tel string `json:"tel"`
}
if resData.Tel, err = realnameSvc.TelInfo(c, mid.(int64)); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnameApply(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
params = c.Request.Form
realname = params.Get("real_name")
cardTypeStr = params.Get("card_type")
cardType int
cardNum = params.Get("card_num")
countryIDStr = params.Get("country")
countryID int
captureStr = params.Get("capture")
capture int
handIMGToken = params.Get("img1_token")
frontIMGToken = params.Get("img2_token")
backIMGToken = params.Get("img3_token")
)
if cardType, err = strconv.Atoi(cardTypeStr); err != nil {
log.Error("%+v", errors.WithStack(err))
c.JSON(nil, ecode.RequestErr)
return
}
if countryIDStr == "" {
countryID = 0 // 默认0中国
} else {
if countryID, err = strconv.Atoi(countryIDStr); err != nil {
log.Error("%+v", errors.WithStack(err))
c.JSON(nil, ecode.RequestErr)
return
}
}
if countryID < 0 {
countryID = 0
}
if capture, err = strconv.Atoi(captureStr); err != nil {
log.Error("%+v", errors.WithStack(err))
c.JSON(nil, ecode.RequestErr)
return
}
if err = realnameSvc.Apply(c, mid.(int64), realname, cardType, cardNum, countryID, capture, handIMGToken, frontIMGToken, backIMGToken); err != nil {
log.Error("%+v")
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func realnameUpload(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
defer c.Request.Form.Del("img") // 防止日志不出现
c.Request.ParseMultipartForm(32 << 20)
imgBytes, err := func() ([]byte, error) {
img := c.Request.FormValue("img")
if img != "" {
log.Info("Succeeded to parse img file from form value: mid: %d, length: %d", mid, len(img))
return []byte(img), nil
}
log.Warn("Failed to parse img file from form value, fallback to form file: mid: %d", mid)
f, _, err := c.Request.FormFile("img")
if err != nil {
return nil, errors.Wrapf(err, "parse img form file: mid: %d", mid)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Wrapf(err, "read img form file: mid: %d", mid)
}
if len(data) <= 0 {
return nil, errors.Wrapf(err, "form file data: mid: %d, length: %d", mid, len(data))
}
log.Info("Succeeded to parse file from form file: mid: %d, length: %d", mid, len(data))
return data, nil
}()
if err != nil {
log.Error("Failed to parse realname upload file: mid: %d: %+v", mid, err)
c.JSON(nil, ecode.RequestErr)
return
}
var resData struct {
SRC string `json:"token"`
}
if resData.SRC, err = realnameSvc.Upload(c, mid.(int64), imgBytes); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.JSON(resData, nil)
}
func realnamePreview(c *bm.Context) {
var (
img []byte
err error
mid, _ = c.Get("mid")
params = c.Request.Form
src = params.Get("src")
)
if img, err = realnameSvc.Preview(c, mid.(int64), src); err != nil {
log.Error("%+v", err)
c.JSON(nil, err)
return
}
c.Writer.Header().Set("Content-Type", http.DetectContentType(img))
c.JSON(img, err)
}
// alipay api
func realnameChannel(c *bm.Context) {
c.JSON(realnameSvc.Channel(c))
}
func realnameCaptcha(c *bm.Context) {
var (
mid, _ = c.Get("mid")
userAgent = c.Request.UserAgent()
ip = metadata.String(c, metadata.RemoteIP)
err error
)
var resp struct {
URL string `json:"url"`
Remote int `json:"remote"`
}
resp.URL, resp.Remote, err = realnameSvc.CaptchaGTRegister(c, mid.(int64), ip, geetestClientType(userAgent))
c.JSON(resp, err)
}
func realnameCaptchaRefresh(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
userAgent = c.Request.UserAgent()
ip = metadata.String(c, metadata.RemoteIP)
v = &model.ParamRealnameCaptchaGTRefresh{}
)
if err = c.Bind(v); err != nil {
return
}
var resp struct {
CaptureType int `json:"captcha_type"`
CaptureInfo struct {
Success int `json:"success"`
GT string `json:"gt"`
Challenge string `json:"challenge"`
} `json:"captcha_info"`
}
resp.CaptureType = 1
resp.CaptureInfo.Challenge, resp.CaptureInfo.GT, resp.CaptureInfo.Success, err = realnameSvc.CaptchaGTRefresh(c, mid.(int64), ip, geetestClientType(userAgent), v.Hash)
c.JSON(resp, err)
}
func realnameCaptchaConfirm(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
userAgent = c.Request.UserAgent()
ip = metadata.String(c, metadata.RemoteIP)
v = &model.ParamRealnameCaptchaGTCheck{}
)
if err = c.Bind(v); err != nil {
return
}
if v.Remote == 1 && len(v.Challenge) != 34 {
err = ecode.RequestErr
return
}
c.JSON(realnameSvc.CaptchaGTValidate(c, mid.(int64), ip, geetestClientType(userAgent), v))
}
func realnameAlipayApply(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
v = &model.ParamRealnameAlipayApply{}
)
if err = c.Bind(v); err != nil {
return
}
c.JSON(realnameSvc.AlipayApply(c, mid.(int64), v))
}
func realnameAlipayConfirm(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
c.JSON(realnameSvc.AlipayConfirm(c, mid.(int64)))
}
func geetestClientType(userAgent string) string {
return "h5"
}

View File

@@ -0,0 +1,927 @@
package http
import (
"strconv"
"go-common/app/interface/main/account/model"
mrl "go-common/app/service/main/relation/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
"go-common/library/xstr"
)
var (
_defaultPS int64 = 50
)
// modify modify user relation.
func modify(c *bm.Context) {
var (
err error
act, fid int64
src uint64
params = c.Request.Form
mid, _ = c.Get("mid")
actStr = params.Get("act")
fidStr = params.Get("fid")
srcStr = params.Get("re_src")
ua = c.Request.Header.Get("User-Agent")
referer = c.Request.Header.Get("Referer")
sid string
realIP = metadata.String(c, metadata.RemoteIP)
)
if act, err = strconv.ParseInt(actStr, 10, 8); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if fid, err = strconv.ParseInt(fidStr, 10, 64); err != nil || fid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if src, err = strconv.ParseUint(srcStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
sidCookie, err := c.Request.Cookie("sid")
if err != nil {
log.Warn("relation infoc get sid failed error(%v)", err)
} else {
sid = sidCookie.Value
}
buvid := c.Request.Header.Get("Buvid")
if buvid == "" {
buvidCookie, _ := c.Request.Cookie("buvid3")
if buvidCookie != nil {
buvid = buvidCookie.Value
}
}
ric := map[string]string{
"ip": realIP,
"User-Agent": ua,
"sid": sid,
"buvid": buvid,
"Referer": referer,
}
c.JSON(nil, relationSvc.Modify(c, mid.(int64), fid, int8(act), uint8(src), ric))
}
func batchModify(c *bm.Context) {
var (
err error
act int64
fids []int64
src uint64
params = c.Request.Form
// res = c.Result()
mid, _ = c.Get("mid")
actStr = params.Get("act")
fidsStr = params.Get("fids")
srcStr = params.Get("re_src")
ua = c.Request.Header.Get("User-Agent")
referer = c.Request.Header.Get("Referer")
sid string
realIP = metadata.String(c, metadata.RemoteIP)
)
if act, err = strconv.ParseInt(actStr, 10, 8); err != nil {
// res["code"] = ecode.RequestErr
c.JSON(nil, ecode.RequestErr)
return
}
if fids, err = xstr.SplitInts(fidsStr); err != nil || len(fids) <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if src, err = strconv.ParseUint(srcStr, 10, 64); err != nil {
// res["code"] = ecode.RequestErr
c.JSON(nil, ecode.RequestErr)
return
}
sidCookie, err := c.Request.Cookie("sid")
if err != nil {
log.Warn("relation infoc get sid failed error(%v)", err)
} else {
sid = sidCookie.Value
}
buvid := c.Request.Header.Get("Buvid")
if buvid == "" {
buvidCookie, _ := c.Request.Cookie("buvid3")
if buvidCookie != nil {
buvid = buvidCookie.Value
}
}
ric := map[string]string{
"ip": realIP,
"User-Agent": ua,
"sid": sid,
"buvid": buvid,
"Referer": referer,
}
// res["code"] = relationSvc.Modify(c, mid.(int64), fid, int8(act), uint8(src), ric)
c.JSON(relationSvc.BatchModify(c, mid.(int64), fids, int8(act), uint8(src), ric))
}
// relation get relation between mid and fid.
func relation(c *bm.Context) {
var (
err error
fid int64
f *mrl.Following
params = c.Request.Form
fidStr = params.Get("fid")
mid, _ = c.Get("mid")
)
if fid, err = strconv.ParseInt(fidStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if f, err = relationSvc.Relation(c, mid.(int64), fid); err != nil {
log.Error("relationSvc.Relation(%d, %d) error(%v)", mid, fid, err)
c.JSON(nil, err)
return
}
c.JSON(f, nil)
}
// relations get relations between mid and fids.
func relations(c *bm.Context) {
var (
err error
fm map[int64]*mrl.Following
fids []int64
params = c.Request.Form
fidsStr = params.Get("fids")
mid, _ = c.Get("mid")
)
if fids, err = xstr.SplitInts(fidsStr); err != nil {
c.JSON(nil, ecode.RequestErr)
log.Error("xstr.SplitInts(fids %v) err(%v)", fidsStr, err)
return
}
if fm, err = relationSvc.Relations(c, mid.(int64), fids); err != nil {
log.Error("relationSvc.Relations(%d, %v) error(%v)", mid, fids, err)
c.JSON(nil, err)
return
}
c.JSON(fm, nil)
}
// followings get user's following list.
func followings(c *bm.Context) {
var (
err error
mid, vmid int64
pn, ps int64
self bool
followings []*model.Following
params = c.Request.Form
vmidStr = params.Get("vmid")
psStr = params.Get("ps")
pnStr = params.Get("pn")
order = params.Get("order")
version uint64
versionStr = params.Get("re_version")
crc32v uint32
total int
)
midS, ok := c.Get("mid")
if ok {
mid = midS.(int64)
} else {
mid = 0
}
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
self = mid == vmid
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn <= 0 {
pn = 1
}
if !self && pn > 5 {
c.JSON(nil, ecode.RelFollowingGuestLimit)
return
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if ps <= 0 || ps > _defaultPS {
ps = _defaultPS
}
if versionStr != "" {
if version, err = strconv.ParseUint(versionStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if order != "asc" {
order = "desc"
}
if followings, crc32v, total, err = relationSvc.Followings(c, vmid, mid, pn, ps, version, order); err != nil {
log.Error("relationSvc.Followings(%d) error(%v)", vmid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": followings,
"total": total,
}, nil)
}
// followers get user's follower list.
func followers(c *bm.Context) {
var (
err error
mid, vmid int64
pn, ps int64
self bool
fs []*model.Following
params = c.Request.Form
vmidStr = params.Get("vmid")
psStr = params.Get("ps")
pnStr = params.Get("pn")
version uint64
total int
versionStr = params.Get("re_version")
crc32v uint32
)
midS, ok := c.Get("mid")
if ok {
mid = midS.(int64)
} else {
mid = 0
}
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
self = mid == vmid
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn <= 0 {
pn = 1
}
if !self && pn > 5 {
c.JSON(nil, ecode.RelFollowingGuestLimit)
return
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if ps <= 0 || ps > _defaultPS {
ps = _defaultPS
}
if versionStr != "" {
if version, err = strconv.ParseUint(versionStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if fs, crc32v, total, err = relationSvc.Followers(c, vmid, mid, pn, ps, version); err != nil {
log.Error("relationSvc.Followers(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": fs,
"total": total,
}, nil)
}
// friends get user's friends list: follow eachother.
func friends(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
followings []*model.Following
params = c.Request.Form
version uint64
versionStr = params.Get("re_version")
crc32v uint32
)
if versionStr != "" {
if version, err = strconv.ParseUint(versionStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if followings, crc32v, err = relationSvc.Friends(c, mid.(int64), version); err != nil {
log.Error("relationSvc.Followings(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": followings,
}, nil)
}
// Blacks get user's black list.
func blacks(c *bm.Context) {
var (
err error
blacks []*model.Following
mid, _ = c.Get("mid")
params = c.Request.Form
version uint64
pn, ps int64
total int
pnStr = params.Get("pn")
psStr = params.Get("ps")
versionStr = params.Get("re_version")
crc32v uint32
)
if versionStr != "" {
if version, err = strconv.ParseUint(versionStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn <= 0 {
pn = 1
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if ps <= 0 || ps > _defaultPS {
ps = _defaultPS
}
if blacks, crc32v, total, err = relationSvc.Blacks(c, mid.(int64), version, pn, ps); err != nil {
log.Error("relationSvc.Blacks(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": blacks,
"total": total,
}, nil)
}
// whispers get user's whisper list.
func whispers(c *bm.Context) {
var (
err error
pn, ps int64
version uint64
crc32v uint32
whispers []*model.Following
mid, _ = c.Get("mid")
params = c.Request.Form
psStr = params.Get("ps")
pnStr = params.Get("pn")
versionStr = params.Get("re_version")
)
if versionStr != "" {
if version, err = strconv.ParseUint(versionStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn <= 0 {
pn = 1
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if ps <= 0 || ps > _defaultPS {
ps = _defaultPS
}
if whispers, crc32v, err = relationSvc.Whispers(c, mid.(int64), pn, ps, version); err != nil {
log.Error("relationSvc.Whispers(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": whispers,
}, nil)
}
// stat get user's follower list.
func stat(c *bm.Context) {
var (
err error
mid, vmid int64
self bool
st *mrl.Stat
params = c.Request.Form
vmidStr = params.Get("vmid")
)
midS, ok := c.Get("mid")
if ok {
mid = midS.(int64)
} else {
mid = 0
}
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
self = mid == vmid
if st, err = relationSvc.Stat(c, vmid, self); err != nil {
log.Error("relationSvc.Followers(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(st, nil)
}
// stat get user's follower list.
func stats(c *bm.Context) {
var (
err error
params = c.Request.Form
midsStr = params.Get("mids")
)
mids, err := xstr.SplitInts(midsStr)
if err != nil || len(mids) > 20 {
c.JSON(nil, ecode.RequestErr)
return
}
sts, err := relationSvc.Stats(c, mids)
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(sts, nil)
}
// tag 单个标签
func tag(c *bm.Context) {
var (
err error
pn, ps int64
mid, _ = c.Get("mid")
params = c.Request.Form
tagIDStr = params.Get("tagid")
tagid int64
psStr = params.Get("ps")
pnStr = params.Get("pn")
ti []*model.Tag
)
if tagIDStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tagid, err = strconv.ParseInt(tagIDStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
log.Error("pn parse")
c.JSON(nil, ecode.RequestErr)
return
}
}
if pn <= 0 {
pn = 1
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if ps <= 0 || ps > _defaultPS {
ps = _defaultPS
}
if ti, err = relationSvc.Tag(c, mid.(int64), tagid, pn, ps); err != nil {
log.Error("relationSvc.Tag(%d).tag(%d) error(%v)", mid, tagid, err)
c.JSON(nil, err)
return
}
c.JSON(ti, nil)
}
// tags 列表:标签-计数
func tags(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
tc []*mrl.TagCount
)
if tc, err = relationSvc.Tags(c, mid.(int64)); err != nil {
log.Error("relationSvc.Tags(%d). error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(tc, nil)
}
// mobileTags 移动端 列表:标签-计数
func mobileTags(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
tc map[string][]*mrl.TagCount
)
if tc, err = relationSvc.MobileTags(c, mid.(int64)); err != nil {
log.Error("relationSvc.Tags(%d). error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(tc, nil)
}
// tagUser 用户-fid 标签列表
func tagUser(c *bm.Context) {
var (
err error
fid int64
mid, _ = c.Get("mid")
params = c.Request.Form
fidStr = params.Get("fid")
tc map[int64]string
)
if fid, err = strconv.ParseInt(fidStr, 10, 64); err != nil || fid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if tc, err = relationSvc.UserTag(c, mid.(int64), fid); err != nil {
log.Error("relationSvc.UserTag(%d).fid(%d) error(%v)", mid, fid, err)
c.JSON(nil, err)
return
}
c.JSON(tc, nil)
}
// tagCreate create tag.
func tagCreate(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
params = c.Request.Form
tagStr = params.Get("tag")
cres int64
)
if tagStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if cres, err = relationSvc.CreateTag(c, mid.(int64), tagStr); err != nil {
c.JSON(nil, err)
return
}
c.JSON(map[string]int64{
"tagid": cres,
}, nil)
}
// tagUpdate update tag.
func tagUpdate(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
params = c.Request.Form
tagIDStr = params.Get("tagid")
tagID int64
newStr = params.Get("name")
)
if tagIDStr == "" || newStr == "" {
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(nil, relationSvc.UpdateTag(c, mid.(int64), tagID, newStr))
}
// tagDel del tag.
func tagDel(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
params = c.Request.Form
tagIDStr = params.Get("tagid")
tagID int64
)
if tagIDStr == "" {
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(nil, relationSvc.DelTag(c, mid.(int64), tagID))
}
// tagsAddUsers tags add users.
func tagsAddUsers(c *bm.Context) {
var (
mid, _ = c.Get("mid")
params = c.Request.Form
tagidsStr = params.Get("tagids")
fidsStr = params.Get("fids")
)
if tagidsStr == "" || fidsStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, relationSvc.TagsAddUsers(c, mid.(int64), tagidsStr, fidsStr))
}
// tagsCopyUsers tags copy users.
func tagsCopyUsers(c *bm.Context) {
var (
mid, _ = c.Get("mid")
params = c.Request.Form
tagidsStr = params.Get("tagids")
fidsStr = params.Get("fids")
)
if tagidsStr == "" || fidsStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, relationSvc.TagsCopyUsers(c, mid.(int64), tagidsStr, fidsStr))
}
// tagsMoveUsers tags move users.
func tagsMoveUsers(c *bm.Context) {
var (
mid, _ = c.Get("mid")
params = c.Request.Form
beforeTagIdsStr = params.Get("beforeTagids")
afterTagIdsStr = params.Get("afterTagids")
fidsStr = params.Get("fids")
)
if beforeTagIdsStr == "" || afterTagIdsStr == "" || fidsStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
bid, err := strconv.ParseInt(beforeTagIdsStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, relationSvc.TagsMoveUsers(c, mid.(int64), bid, afterTagIdsStr, fidsStr))
}
func prompt(c *bm.Context) {
mid, _ := c.Get("mid")
arg := new(mrl.ArgPrompt)
if err := c.Bind(arg); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
arg.Mid = mid.(int64)
b, err := relationSvc.Prompt(c, arg)
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"prompt": b,
}, nil)
}
func closePrompt(c *bm.Context) {
mid, _ := c.Get("mid")
arg := new(mrl.ArgPrompt)
if err := c.Bind(arg); err != nil {
return
}
arg.Mid = mid.(int64)
c.JSON(nil, relationSvc.ClosePrompt(c, arg))
}
func addSpecial(c *bm.Context) {
mid, _ := c.Get("mid")
arg := new(mrl.ArgFollowing)
if err := c.Bind(arg); err != nil {
return
}
arg.Mid = mid.(int64)
c.JSON(nil, relationSvc.AddSpecial(c, arg))
}
func delSpecial(c *bm.Context) {
mid, _ := c.Get("mid")
arg := new(mrl.ArgFollowing)
if err := c.Bind(arg); err != nil {
return
}
arg.Mid = mid.(int64)
c.JSON(nil, relationSvc.DelSpecial(c, arg))
}
func special(c *bm.Context) {
mid, _ := c.Get("mid")
c.JSON(relationSvc.Special(c, mid.(int64)))
}
// recommend get global recommend upper.
// deprecated
func recommend(c *bm.Context) {
c.JSON([]interface{}{}, nil)
}
func recommendFollowlistEmpty(c *bm.Context) {
dev, _ := c.Get("device")
mid, _ := c.Get("mid")
arg := &model.ArgRecommend{}
if err := c.Bind(arg); err != nil {
return
}
arg.Device = dev.(*bm.Device)
arg.Mid = mid.(int64)
arg.RemoteIP = metadata.String(c, metadata.RemoteIP)
c.JSON(relationSvc.RecommendFollowlistEmpty(c, arg))
}
func recommendAnswerOK(c *bm.Context) {
dev, _ := c.Get("device")
mid, _ := c.Get("mid")
arg := &model.ArgRecommend{}
if err := c.Bind(arg); err != nil {
return
}
arg.Device = dev.(*bm.Device)
arg.Mid = mid.(int64)
arg.RemoteIP = metadata.String(c, metadata.RemoteIP)
c.JSON(relationSvc.RecommendAnswerOK(c, arg))
}
func recommendTagSuggest(c *bm.Context) {
dev, _ := c.Get("device")
mid, _ := c.Get("mid")
arg := &model.ArgTagSuggestRecommend{}
if err := c.Bind(arg); err != nil {
return
}
arg.Device = dev.(*bm.Device)
arg.Mid = mid.(int64)
arg.RemoteIP = metadata.String(c, metadata.RemoteIP)
c.JSON(relationSvc.RecommendTagSuggest(c, arg))
}
func recommendTagSuggestDetail(c *bm.Context) {
dev, _ := c.Get("device")
mid, _ := c.Get("mid")
arg := &model.ArgTagSuggestRecommend{}
if err := c.Bind(arg); err != nil {
return
}
if arg.TagName == "" {
c.JSON(nil, ecode.RequestErr)
return
}
arg.Device = dev.(*bm.Device)
arg.Mid = mid.(int64)
arg.RemoteIP = metadata.String(c, metadata.RemoteIP)
c.JSON(relationSvc.RecommendTagSuggestDetail(c, arg))
}
// unread check unread status, for the 'show red point' function.
func unread(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
show bool
)
disbaleAutoReset := c.Request.Form.Get("disableautoreset") == "1"
if show, err = relationSvc.Unread(c, mid.(int64), disbaleAutoReset); err != nil {
log.Error("relationSvc.Unread(%d) err(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"show": show,
}, nil)
}
func unreadReset(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
c.JSON(nil, relationSvc.ResetUnread(c, mid.(int64)))
}
func unreadCount(c *bm.Context) {
var (
err error
mid, _ = c.Get("mid")
count int64
)
disbaleAutoReset := c.Request.Form.Get("disableautoreset") == "1"
if count, err = relationSvc.UnreadCount(c, mid.(int64), disbaleAutoReset); err != nil {
log.Error("relationSvc.UnreadCount(%d) err(%v)", mid, err)
return
}
c.JSON(map[string]interface{}{
"count": count,
}, nil)
}
func unreadCountReset(c *bm.Context) {
var (
mid, _ = c.Get("mid")
)
c.JSON(nil, relationSvc.ResetUnreadCount(c, mid.(int64)))
}
func achieveGet(ctx *bm.Context) {
arg := new(model.ArgAchieveGet)
if err := ctx.Bind(arg); err != nil {
return
}
mid, _ := ctx.Get("mid")
arg.Mid = mid.(int64)
if arg.Award != "10k" {
ctx.JSON(nil, ecode.RequestErr)
return
}
ctx.JSON(relationSvc.AchieveGet(ctx, arg))
}
func achieve(ctx *bm.Context) {
arg := new(model.ArgAchieve)
if err := ctx.Bind(arg); err != nil {
return
}
ctx.JSON(relationSvc.Achieve(ctx, arg))
}
func followerNotifySetting(c *bm.Context) {
var mid, _ = c.Get("mid")
c.JSON(relationSvc.FollowerNotifySetting(c, mid.(int64)))
}
func enableFollowerNotify(c *bm.Context) {
var mid, _ = c.Get("mid")
c.JSON(nil, relationSvc.EnableFollowerNotify(c, mid.(int64)))
}
func disableFollowerNotify(c *bm.Context) {
var mid, _ = c.Get("mid")
c.JSON(nil, relationSvc.DisableFollowerNotify(c, mid.(int64)))
}
func sameFollowings(c *bm.Context) {
arg := new(model.ArgSameFollowing)
if err := c.Bind(arg); err != nil {
return
}
mid, _ := c.Get("mid")
arg.Mid = mid.(int64)
if arg.Order != "asc" {
arg.Order = "desc"
}
if arg.PN <= 0 {
arg.PN = 1
}
if arg.PS <= 0 || arg.PS > _defaultPS {
arg.PS = _defaultPS
}
followings, crc32v, total, err := relationSvc.SameFollowings(c, arg)
if err != nil {
log.Error("relationSvc.SameFollowings(%+v) error(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(map[string]interface{}{
"re_version": uint64(crc32v),
"list": followings,
"total": total,
}, nil)
}

View File

@@ -0,0 +1,32 @@
package http
import (
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func status(c *bm.Context) {
var (
params = c.Request.Form
mid, ok = c.Get("mid")
uuid = params.Get("uuid")
)
if !ok {
c.JSON(nil, ecode.RequestErr)
return
}
msg, err := memberSvc.Status(c, mid.(int64), uuid)
if err != nil {
c.JSON(nil, ecode.RemoteLoginStatusQueryError)
return
}
c.JSON(msg, nil)
}
func closeNotify(c *bm.Context) {
c.JSON(struct{}{}, nil)
}
func feedback(c *bm.Context) {
c.JSON(struct{}{}, nil)
}

View File

@@ -0,0 +1,46 @@
package http
import (
"encoding/json"
bm "go-common/library/net/http/blademaster"
)
func sudo(ctx *bm.Context) {
cmd := ctx.Request.Form.Get("cmd")
if cmd == "" {
ctx.AbortWithStatus(400)
return
}
ctx.Set("command", cmd)
}
func notityPurgeCache(ctx *bm.Context) {
cmd, ok := ctx.Get("command")
if !ok {
ctx.AbortWithStatus(400)
return
}
plain, ok := cmd.(string)
if !ok {
ctx.AbortWithStatus(400)
return
}
var param struct {
Mid int64 `json:"mid"`
Action string `json:"action"`
}
if err := json.Unmarshal([]byte(plain), &param); err != nil {
ctx.AbortWithStatus(400)
return
}
if param.Mid <= 0 {
ctx.AbortWithStatus(400)
return
}
if param.Action == "" {
param.Action = "updateByAdmin"
}
ctx.JSON(nil, memberSvc.NotityPurgeCache(ctx, param.Mid, param.Action))
}

View File

@@ -0,0 +1,358 @@
package http
import (
"strings"
"go-common/app/interface/main/account/model"
col "go-common/app/service/main/coupon/model"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
const (
_headerBuvid = "Buvid"
)
func codeVerify(c *bm.Context) {
c.JSON(vipSvc.CodeVerify(c))
}
func codeOpen(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(struct {
Token string `form:"token" validate:"required"`
Code string `form:"code" validate:"required"`
Verify string `form:"verify" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
arg.Code = strings.Trim(arg.Code, " ")
c.JSON(vipSvc.CodeOpen(c, mid.(int64), arg.Code, arg.Token, arg.Verify))
}
// tips info.
func tips(c *bm.Context) {
var (
res *vipmol.TipsResp
arg = new(model.TipsReq)
err error
)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.Tips(c, arg); err != nil {
log.Error("vipSvc.Tips(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
// tips info.
func tipsv2(c *bm.Context) {
var (
res []*vipmol.TipsResp
arg = new(model.TipsReq)
err error
)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.TipsV2(c, arg); err != nil {
log.Error("vipSvc.Tips(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func vipPanel(c *bm.Context) {
var (
err error
res *vipmol.VipPirceResp5
)
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.VipPanelRes)
if err = c.Bind(arg); err != nil {
return
}
if res, err = vipSvc.VipPanel5(c, mid.(int64), arg); err != nil {
log.Error("vipSvc.VipPanel(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func couponUsable(c *bm.Context) {
var (
err error
res *col.CouponAllowancePanelInfo
)
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.ArgVipCoupon)
if err = c.Bind(arg); err != nil {
return
}
if res, err = vipSvc.CouponBySuitID(c, mid.(int64), arg.ID); err != nil {
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func couponList(c *bm.Context) {
var (
err error
res *col.CouponAllowancePanelResp
)
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.ArgVipCoupon)
if err = c.Bind(arg); err != nil {
return
}
if res, err = vipSvc.CouponsForPanelV2(c, mid.(int64), arg.ID); err != nil {
log.Error("vipSvc.CouponsForPanelV2(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func couponUnlock(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.ArgVipCancelPay)
if err = c.Bind(arg); err != nil {
return
}
if err = vipSvc.CancelUseCoupon(c, &vipmol.ArgCancelUseCoupon{
Mid: mid.(int64),
CouponToken: arg.CouponToken,
}); err != nil {
log.Error("vipSvc.CancelUseCoupon(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(model.CouponCancelExplain, nil)
}
func vipPanelV2(c *bm.Context) {
var err error
arg := new(model.ArgVipPanel)
if err = c.Bind(arg); err != nil {
return
}
mid, exists := c.Get("mid")
if exists {
arg.Mid = mid.(int64)
}
arg.IP = metadata.String(c, metadata.RemoteIP)
c.JSON(vipSvc.VipPanelV2(c, arg))
}
func vipPanelV8(c *bm.Context) {
var err error
arg := new(model.ArgVipPanel)
if err = c.Bind(arg); err != nil {
return
}
mid, exists := c.Get("mid")
if exists {
arg.Mid = mid.(int64)
}
arg.IP = metadata.String(c, metadata.RemoteIP)
c.JSON(vipSvc.VipPanelV8(c, arg))
}
func privilegeBySid(c *bm.Context) {
var err error
arg := new(vipmol.ArgPrivilegeBySid)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.PrivilegebySid(c, arg))
}
func privilegeByType(c *bm.Context) {
var err error
arg := new(vipmol.ArgPrivilegeDetail)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.PrivilegebyType(c, arg))
}
func vipManagerInfo(c *bm.Context) {
c.JSON(vipSvc.ManagerInfo(c))
}
func codeOpeneds(c *bm.Context) {
var (
err error
)
arg := new(model.CodeInfoReq)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.CodeOpeneds(c, arg, metadata.String(c, metadata.RemoteIP)))
}
func unfrozen(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(nil, vipSvc.Unfrozen(c, mid.(int64)))
}
func frozenTime(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
c.JSON(vipSvc.FrozenTime(c, mid.(int64)))
}
func publicPriceList(c *bm.Context) {
var (
err error
res *vipmol.VipPirceResp
mid int64
)
midStr, exists := c.Get("mid")
if exists {
mid = midStr.(int64)
}
arg := new(model.VipPanelRes)
if err = c.Bind(arg); err != nil {
return
}
if res, err = vipSvc.VipPanel(c, mid, arg); err != nil {
log.Error("vipSvc.VipPanel(%+v) err(%v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func useBatch(c *bm.Context) {
var err error
arg := new(vipmol.ArgUseBatch)
if err = c.Bind(arg); err != nil {
log.Error("use batch bind err(%+v) arg(%+v)", err, arg)
return
}
c.JSON(nil, vipSvc.UseBatch(c, arg))
}
func orderStatus(c *bm.Context) {
var (
err error
)
midI, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(vipmol.ArgDialog)
if err = c.Bind(arg); err != nil {
return
}
arg.Mid = midI.(int64)
c.JSON(vipSvc.OrderStatus(c, arg))
}
func resourceBanner(c *bm.Context) {
var (
err error
)
midI, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.ArgResource)
if err = c.Bind(arg); err != nil {
return
}
arg.MID = midI.(int64)
arg.Buvid = c.Request.Header.Get(_headerBuvid)
arg.Plat = model.Plat(arg.MobiApp, arg.Device)
c.JSON(vipSvc.ResourceBanner(c, arg))
}
func resourceBuy(c *bm.Context) {
var (
err error
)
midI, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(model.ArgResource)
if err = c.Bind(arg); err != nil {
return
}
arg.MID = midI.(int64)
arg.Buvid = c.Request.Header.Get(_headerBuvid)
arg.Plat = model.Plat(arg.MobiApp, arg.Device)
c.JSON(vipSvc.ResourceBuy(c, arg))
}
func couponBySuitIDV2(c *bm.Context) {
var err error
arg := new(model.ArgCouponBySuitID)
if err = c.Bind(arg); err != nil {
return
}
mid, exists := c.Get("mid")
if exists {
arg.Mid = mid.(int64)
}
c.JSON(vipSvc.CouponBySuitIDV2(c, arg))
}
func vipPanelV9(c *bm.Context) {
var err error
arg := new(model.ArgVipPanel)
if err = c.Bind(arg); err != nil {
return
}
mid, exists := c.Get("mid")
if exists {
arg.Mid = mid.(int64)
}
arg.IP = metadata.String(c, metadata.RemoteIP)
c.JSON(vipSvc.VipPanelV9(c, arg))
}

View File

@@ -0,0 +1,109 @@
package http
import (
"go-common/app/interface/main/account/model"
v1 "go-common/app/service/main/vip/api"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
func bindInfoByMid(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
a := new(model.ArgBindInfo)
if err = c.Bind(a); err != nil {
return
}
a.Mid = mid.(int64)
a.AppID = vipmol.EleAppID
c.JSON(vipSvc.BindInfoByMid(c, a))
}
func createAssociateOrder(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
a := new(model.ArgCreateAssociateOrder)
if err = c.Bind(a); err != nil {
return
}
a.Mid = mid.(int64)
a.IP = metadata.String(c, metadata.RemoteIP)
c.JSON(vipSvc.CreateAssociateOrder(c, a))
}
func associatePanel(c *bm.Context) {
var err error
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.AccountNotLogin)
return
}
a := new(vipmol.ArgAssociatePanel)
if err = c.Bind(a); err != nil {
return
}
a.Mid = mid.(int64)
a.IP = metadata.String(c, metadata.RemoteIP)
res := new(struct {
PriceList []*v1.AssociatePanelInfo `json:"price_list"`
})
res.PriceList, err = vipSvc.AssociatePanel(c, a)
if res.PriceList == nil {
res.PriceList = []*v1.AssociatePanelInfo{}
}
c.JSON(res, err)
}
func redpackets(c *bm.Context) {
c.JSON(vipSvc.EleRedPackages(c))
}
func specailfoods(c *bm.Context) {
c.JSON(vipSvc.EleSpecailFoods(c))
}
func actlimit(ctx *bm.Context) {
var mid int64
midi, exists := ctx.Get("mid")
if exists {
mid = midi.(int64)
}
if err := vipSvc.ActivityTimeLimit(mid); err != nil {
ctx.JSON(nil, err)
ctx.Abort()
return
}
}
func iplimit(ctx *bm.Context) {
req := ctx.Request
params := req.Form
sappkey := params.Get("appkey")
ip := metadata.String(ctx, metadata.RemoteIP)
if err := vipSvc.ActivityWhiteIPLimit(sappkey, ip); err != nil {
ctx.JSON(nil, err)
ctx.Abort()
return
}
}
func openlimit(ctx *bm.Context) {
req := ctx.Request
params := req.Form
outOpenID := params.Get("out_open_id")
if err := vipSvc.ActivityWhiteOutOpenIDLimit(outOpenID); err != nil {
ctx.JSON(nil, err)
ctx.Abort()
return
}
}

View File

@@ -0,0 +1,122 @@
package http
import (
"net/http"
"go-common/app/interface/main/account/model"
idtv1 "go-common/app/service/main/identify/api/grpc"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/metadata"
)
//
// vip 第三方[ele]接入gateway
//
// openID
func openIDByOAuth2Code(c *bm.Context) {
var err error
a := new(model.ArgAuthCode)
if err = c.Bind(a); err != nil {
return
}
a.IP = metadata.String(c, metadata.RemoteIP)
a.APPID = vipmol.EleAppID
c.JSON(vipSvc.OpenIDByAuthCode(c, a))
}
func openBindByOutOpenID(c *bm.Context) {
var err error
a := new(model.ArgBind)
if err = c.Bind(a); err != nil {
return
}
a.AppID = vipmol.EleAppID
c.JSON(nil, vipSvc.OpenBindByOutOpenID(c, a))
}
func userInfoByOpenID(c *bm.Context) {
var err error
a := new(model.ArgUserInfoByOpenID)
if err = c.Bind(a); err != nil {
return
}
a.AppID = vipmol.EleAppID
c.JSON(vipSvc.UserInfoByOpenID(c, a))
}
func bilibiliVipGrant(c *bm.Context) {
var err error
a := new(model.ArgBilibiliVipGrant)
if err = c.Bind(a); err != nil {
return
}
a.AppID = vipmol.EleAppID
c.JSON(nil, vipSvc.BilibiliVipGrant(c, a))
}
func bilibiliPrizeGrant(c *bm.Context) {
var err error
a := new(model.ArgBilibiliPrizeGrant)
if err = c.Bind(a); err != nil {
return
}
a.AppID = vipmol.EleAppID
c.JSON(vipSvc.BilibiliPrizeGrant(c, a))
}
func openAuthCallBack(c *bm.Context) {
var err error
midI, ok := c.Get("mid")
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
a := new(model.ArgOpenAuthCallBack)
if err = c.Bind(a); err != nil {
return
}
// verify csrf.
verifyState(c, authn, a.State)
a.AppID = vipmol.EleAppID
a.Mid = midI.(int64)
c.Redirect(http.StatusFound, vipSvc.OpenAuthCallBack(c, a))
}
func eleOAuthURL(c *bm.Context) {
var (
state string
err error
)
if state, err = csrf(c, authn); err != nil {
return
}
c.JSON(vipSvc.ElemeOAuthURI(c, state), nil)
}
func verifyState(ctx *bm.Context, a *auth.Auth, state string) (err error) {
var csrfStr string
if csrfStr, err = csrf(ctx, a); err != nil {
return
}
if csrfStr != state {
return ecode.CsrfNotMatchErr
}
return
}
func csrf(ctx *bm.Context, a *auth.Auth) (string, error) {
req := ctx.Request
cookie := req.Header.Get("Cookie")
reply, err := a.GetCookieInfo(ctx, &idtv1.GetCookieInfoReq{Cookie: cookie})
if err != nil {
return "", err
}
if !reply.IsLogin {
return "", ecode.NoLogin
}
return reply.Csrf, nil
}

View File

@@ -0,0 +1,66 @@
package http
import (
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func welfareList(c *bm.Context) {
arg := new(struct {
Tid int64 `form:"tid"`
Recommend int64 `form:"recommend"`
Pn int64 `form:"pn"`
Ps int64 `form:"ps"`
})
if err := c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
c.JSON(vipSvc.WelfareList(c, arg.Tid, arg.Recommend, arg.Pn, arg.Ps))
}
func welfareTypeList(c *bm.Context) {
c.JSON(vipSvc.WelfareTypeList(c))
}
func welfareInfo(c *bm.Context) {
userId := int64(0)
mid, exists := c.Get("mid")
if exists {
userId = mid.(int64)
}
arg := new(struct {
Wid int64 `form:"id"`
})
if err := c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
c.JSON(vipSvc.WelfareInfo(c, arg.Wid, userId))
}
func receiveWelfare(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
arg := new(struct {
Wid int64 `form:"id"`
})
if err := c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
c.JSON(vipSvc.WelfareReceive(c, arg.Wid, mid.(int64)))
}
func myWelfare(c *bm.Context) {
mid, exists := c.Get("mid")
if !exists {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(vipSvc.MyWelfare(c, mid.(int64)))
}

View File

@@ -0,0 +1,155 @@
package http
import (
"strconv"
"go-common/app/interface/main/account/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// replyHistoryList
func replyHistoryList(c *bm.Context) {
var (
err error
//ip = c.RemoteIP()
header = c.Request.Header
params = c.Request.Form
mid, _ = c.Get("mid")
cookie = header.Get("Cookie")
accessKey = params.Get("access_key")
stime = params.Get("stime")
etime = params.Get("etime")
order = params.Get("order")
sort = params.Get("sort")
pnStr = params.Get("pn")
psStr = params.Get("ps")
pn, ps int64
)
if pnStr != "" {
if pn, err = strconv.ParseInt(pnStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if psStr != "" {
if ps, err = strconv.ParseInt(psStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
c.JSON(memberSvc.ReplyHistoryList(c, mid.(int64), stime, etime, order, sort, pn, ps, accessKey, cookie))
}
// updateSettings
func update(c *bm.Context) {
var (
params = c.Request.Form
mid, ok = c.Get("mid")
//ip = c.RemoteIP()
unameStr = params.Get("uname")
signStr = params.Get("usersign")
sexStr = params.Get("sex")
birthdayStr = params.Get("birthday")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
settings := &model.Settings{
Uname: unameStr,
Sign: signStr,
Sex: sexStr,
Birthday: birthdayStr,
}
log.Error("request(%v)", settings)
c.JSON(nil, memberSvc.UpdateSettings(c, mid.(int64), settings))
}
func account(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.SettingsInfo(c, mid.(int64)))
}
// logCoin
func logCoin(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.LogCoin(c, mid.(int64)))
}
// coin
func coin(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.Coin(c, mid.(int64)))
}
func logMoral(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.LogMoral(c, mid.(int64)))
}
func logExp(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.LogExp(c, mid.(int64)))
}
// logLogin
func logLogin(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.LogLogin(c, mid.(int64)))
}
func reward(c *bm.Context) {
var (
//ip = c.RemoteIP()
mid, ok = c.Get("mid")
)
if !ok {
c.JSON(nil, ecode.NoLogin)
return
}
c.JSON(memberSvc.Reward(c, mid.(int64)))
}

View File

@@ -0,0 +1,68 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["regular_test.go"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = ["//vendor/github.com/smartystreets/goconvey/convey:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = [
"app_info.go",
"card.go",
"coupon.go",
"enum.go",
"geetest.go",
"http.go",
"invite.go",
"model.go",
"notice.go",
"pendant.go",
"realname.go",
"regular.go",
"relation.go",
"reply.go",
"usersuit.go",
"vip.go",
"vip_outer.go",
"vip_welfare.go",
"web_info.go",
],
importpath = "go-common/app/interface/main/account/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/account/api:go_default_library",
"//app/service/main/account/model:go_default_library",
"//app/service/main/coupon/model:go_default_library",
"//app/service/main/relation/model:go_default_library",
"//app/service/main/usersuit/model:go_default_library",
"//app/service/main/vip/api:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//library/net/http/blademaster: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,59 @@
package model
import xtime "go-common/library/time"
// const .
const (
UpNameLogID = 14
UpNameAction = "log_name_update"
)
// Account account.
type Account struct {
Mid int64 `json:"mid"`
Uname string `json:"uname"`
Face string `json:"face"`
Sex int8 `json:"sex"`
Birthday string `json:"birthday"`
Sign string `json:"sign"`
NickFree bool `json:"nick_free"`
}
// NickFree nickFree.
type NickFree struct {
NickFree bool `json:"nick_free"`
}
// PassportProfile is
/*
"mid": 288840748,
"uname": "小学生pasami",
"userid": "bili_43796499903",
"telphone": "9028005779",
"nickLock": 0,
"bind_qq": false,
"bind_sina": true,
"spacesta": 2,
"login_time": 1529165291,
"login_ip": "103.228.109.204",
"join_ip": "119.135.161.112",
"join_time": 1518286685,
"safe_question": 0,
"country_code": 1
*/
type PassportProfile struct {
Mid int64 `json:"mid"`
UName string `json:"uname"`
UserID string `json:"user_id"`
Telphone string `json:"telphone"`
NickLock int `json:"nick_lock"`
BindQQ bool `json:"bind_qq"`
BindSina bool `json:"bind_sina"`
SpaceSta int `json:"spacesta"`
LoginTime xtime.Time `json:"login_time"`
LoginIP string `json:"login_ip"`
JoinIP string `json:"join_ip"`
JoinTime xtime.Time `json:"join_time"`
SafeQuestion int `json:"safe_question"`
CountryCode int64 `json:"country_code"`
}

View File

@@ -0,0 +1,11 @@
package model
// ArgCardID arg card id.
type ArgCardID struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
}
// ArgGroupID arg group id.
type ArgGroupID struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
}

View File

@@ -0,0 +1,18 @@
package model
// ArgAllowanceList req.
type ArgAllowanceList struct {
State int8 `form:"state"`
}
// ArgCouponPage req .
type ArgCouponPage struct {
State int8 `form:"state"`
Pn int `form:"pn"`
Ps int `form:"ps"`
}
// ArgPrizeDraw struct .
type ArgPrizeDraw struct {
CardType int8 `form:"card_type" validate:"min=0,gte=0,lte=2"`
}

View File

@@ -0,0 +1,530 @@
package model
//Type type.
type Type struct {
ID int64 `json:"id"`
Type string `json:"type"`
}
// Origin coin origin
var Origin = map[int64]string{
1: "举报奖励",
2: "违规惩罚",
3: "撤销奖励",
4: "撤销惩罚",
5: "自动恢复",
6: "管理员操作",
}
// var .
var (
unmarried = &Type{1, "未婚"}
married = &Type{2, "已婚"}
divorce = &Type{3, "离异"}
widowed = &Type{4, "丧偶"}
Maritals = map[int]*Type{
1: unmarried,
2: married,
3: divorce,
4: widowed,
}
netFriend = &Type{1, "网友"}
lover = &Type{2, "恋人"}
playmate = &Type{3, "玩伴"}
commonInterest = &Type{3, "共同兴趣"}
boyFriend = &Type{5, "男性朋友"}
girFriend = &Type{6, "女性朋友"}
DatingTypes = map[int]*Type{
1: netFriend,
2: lover,
3: playmate,
4: commonInterest,
5: boyFriend,
6: girFriend,
}
Places = map[int]*Type{
500: {500, "北京市"},
501: {501, "西城区"},
502: {502, "崇文区"},
503: {503, "宣武区"},
504: {504, "朝阳区"},
505: {505, "海淀区"},
506: {506, "丰台区"},
507: {507, "石景山区"},
508: {508, "门头沟区"},
509: {509, "房山区"},
510: {510, "通州区"},
511: {511, "顺义区"},
512: {512, "昌平区"},
513: {513, "大兴区"},
514: {514, "平谷县"},
515: {515, "怀柔县"},
516: {516, "密云县"},
517: {517, "延庆县"},
518: {518, "东城区"},
1000: {1000, "上海市"},
1001: {1001, "黄浦区"},
1002: {1002, "卢湾区"},
1003: {1003, "徐汇区"},
1004: {1004, "长宁区"},
1005: {1005, "静安区"},
1006: {1006, "普陀区"},
1007: {1007, "闸北区"},
1008: {1008, "虹口区"},
1009: {1009, "杨浦区"},
1010: {1010, "宝山区"},
1011: {1011, "闵行区"},
1012: {1012, "嘉定区"},
1013: {1013, "浦东新区"},
1014: {1014, "松江区"},
1015: {1015, "金山区"},
1016: {1016, "青浦区"},
1017: {1017, "南汇区"},
1018: {1018, "奉贤区"},
1019: {1019, "崇明县"},
1500: {1500, "天津市"},
1501: {1501, "和平区"},
1502: {1502, "河东区"},
1503: {1503, "河西区"},
1504: {1504, "南开区"},
1505: {1505, "河北区"},
1506: {1506, "红桥区"},
1507: {1507, "塘沽区"},
1508: {1508, "汉沽区"},
1509: {1509, "大港区"},
1510: {1510, "东丽区"},
1511: {1511, "西青区"},
1512: {1512, "北辰区"},
1513: {1513, "津南区"},
1514: {1514, "武清区"},
1515: {1515, "宝坻区"},
1516: {1516, "静海县"},
1517: {1517, "宁河县"},
1518: {1518, "蓟县"},
2000: {2000, "重庆市"},
2001: {2001, "渝中区"},
2002: {2002, "大渡口区"},
2003: {2003, "江北区"},
2004: {2004, "沙坪坝区"},
2005: {2005, "九龙坡区"},
2006: {2006, "南岸区"},
2007: {2007, "北碚区"},
2008: {2008, "万盛区"},
2009: {2009, "双桥区"},
2010: {2010, "渝北区"},
2011: {2011, "巴南区"},
2012: {2012, "万州区"},
2013: {2013, "涪陵区"},
2014: {2014, "黔江区"},
2015: {2015, "永川市"},
2016: {2016, "合川市"},
2017: {2017, "江津市"},
2018: {2018, "南川市"},
2019: {2019, "长寿县"},
2020: {2020, "綦江县"},
2021: {2021, "潼南县"},
2022: {2022, "荣昌县"},
2023: {2023, "璧山县"},
2024: {2024, "大足县"},
2025: {2025, "铜梁县"},
2026: {2026, "梁平县"},
2027: {2027, "城口县"},
2028: {2028, "垫江县"},
2029: {2029, "武隆县"},
2030: {2030, "丰都县"},
2031: {2031, "奉节县"},
2032: {2032, "开县"},
2033: {2033, "云阳县"},
2034: {2034, "忠县"},
2035: {2035, "巫溪县"},
2036: {2036, "巫山县"},
2037: {2037, "石柱县"},
2038: {2038, "秀山县"},
2039: {2039, "酉阳县"},
2040: {2040, "彭水县"},
2500: {2500, "广东省"},
2501: {2501, "广州市"},
2502: {2502, "深圳市"},
2503: {2503, "珠海市"},
2504: {2504, "汕头市"},
2505: {2505, "韶关市"},
2506: {2506, "河源市"},
2507: {2507, "梅州市"},
2508: {2508, "惠州市"},
2509: {2509, "汕尾市"},
2510: {2510, "东莞市"},
2511: {2511, "中山市"},
2512: {2512, "江门市"},
2513: {2513, "佛山市"},
2514: {2514, "阳江市"},
2515: {2515, "湛江市"},
2516: {2516, "茂名市"},
2517: {2517, "肇庆市"},
2518: {2518, "清远市"},
2519: {2519, "潮州市"},
2520: {2520, "揭阳市"},
2521: {2521, "云浮市"},
3000: {3000, "福建省"},
3001: {3001, "福州市"},
3002: {3002, "厦门市"},
3003: {3003, "三明市"},
3004: {3004, "莆田市"},
3005: {3005, "泉州市"},
3006: {3006, "漳州市"},
3007: {3007, "南平市"},
3008: {3008, "龙岩市"},
3009: {3009, "宁德市"},
3500: {3500, "浙江省"},
3501: {3501, "杭州市"},
3502: {3502, "宁波市"},
3503: {3503, "温州市"},
3504: {3504, "嘉兴市"},
3505: {3505, "湖州市"},
3506: {3506, "绍兴市"},
3507: {3507, "金华市"},
3508: {3508, "衢州市"},
3509: {3509, "舟山市"},
3510: {3510, "台州市"},
3511: {3511, "丽水市"},
4000: {4000, "江苏省"},
4001: {4001, "南京市"},
4002: {4002, "徐州市"},
4003: {4003, "连云港市"},
4004: {4004, "淮安市"},
4005: {4005, "宿迁市"},
4006: {4006, "盐城市"},
4007: {4007, "扬州市"},
4008: {4008, "泰州市"},
4009: {4009, "南通市"},
4010: {4010, "镇江市"},
4011: {4011, "常州市"},
4012: {4012, "无锡市"},
4013: {4013, "苏州市"},
4500: {4500, "山东省"},
4501: {4501, "济南市"},
4502: {4502, "青岛市"},
4503: {4503, "淄博市"},
4504: {4504, "枣庄市"},
4505: {4505, "东营市"},
4506: {4506, "潍坊市"},
4507: {4507, "烟台市"},
4508: {4508, "威海市"},
4509: {4509, "济宁市"},
4510: {4510, "泰安市"},
4511: {4511, "日照市"},
4512: {4512, "莱芜市"},
4513: {4513, "德州市"},
4514: {4514, "临沂市"},
4515: {4515, "聊城市"},
4516: {4516, "滨州市"},
4517: {4517, "菏泽市"},
5000: {5000, "辽宁省"},
5001: {5001, "沈阳市"},
5002: {5002, "大连市"},
5003: {5003, "鞍山市"},
5004: {5004, "抚顺市"},
5005: {5005, "本溪市"},
5006: {5006, "丹东市"},
5007: {5007, "锦州市"},
5008: {5008, "葫芦岛市"},
5009: {5009, "营口市"},
5010: {5010, "盘锦市"},
5011: {5011, "阜新市"},
5012: {5012, "辽阳市"},
5013: {5013, "铁岭市"},
5014: {5014, "朝阳市"},
5500: {5500, "江西省"},
5501: {5501, "南昌市"},
5502: {5502, "景德镇市"},
5503: {5503, "萍乡市"},
5504: {5504, "新余市"},
5505: {5505, "九江市"},
5506: {5506, "鹰潭市"},
5507: {5507, "赣州市"},
5508: {5508, "吉安市"},
5509: {5509, "宜春市"},
5510: {5510, "抚州市"},
5511: {5511, "上饶市"},
6000: {6000, "四川省"},
6001: {6001, "成都市"},
6002: {6002, "自贡市"},
6003: {6003, "攀枝花市"},
6004: {6004, "泸州市"},
6005: {6005, "德阳市"},
6006: {6006, "绵阳市"},
6007: {6007, "广元市"},
6008: {6008, "遂宁市"},
6009: {6009, "内江市"},
6010: {6010, "乐山市"},
6011: {6011, "南充市"},
6012: {6012, "宜宾市"},
6013: {6013, "广安市"},
6014: {6014, "达州市"},
6015: {6015, "巴中市"},
6016: {6016, "雅安市"},
6017: {6017, "眉山市"},
6018: {6018, "资阳市"},
6019: {6019, "阿坝州"},
6020: {6020, "甘孜州"},
6021: {6021, "凉山州"},
6500: {6500, "陕西省"},
6501: {6501, "西安市"},
6502: {6502, "铜川市"},
6503: {6503, "宝鸡市"},
6504: {6504, "咸阳市"},
6505: {6505, "渭南市"},
6506: {6506, "延安市"},
6507: {6507, "汉中市"},
6508: {6508, "榆林市"},
6509: {6509, "安康市"},
6510: {6510, "商洛地区"},
7000: {7000, "湖北省"},
7001: {7001, "武汉市"},
7002: {7002, "黄石市"},
7003: {7003, "襄樊市"},
7004: {7004, "十堰市"},
7005: {7005, "荆州市"},
7006: {7006, "宜昌市"},
7007: {7007, "荆门市"},
7008: {7008, "鄂州市"},
7009: {7009, "孝感市"},
7010: {7010, "黄冈市"},
7011: {7011, "咸宁市"},
7012: {7012, "随州市"},
7013: {7013, "仙桃市"},
7014: {7014, "天门市"},
7015: {7015, "潜江市"},
7016: {7016, "神农架"},
7017: {7017, "恩施州"},
7500: {7500, "河南省"},
7501: {7501, "郑州市"},
7502: {7502, "开封市"},
7503: {7503, "洛阳市"},
7504: {7504, "平顶山市"},
7505: {7505, "焦作市"},
7506: {7506, "鹤壁市"},
7507: {7507, "新乡市"},
7508: {7508, "安阳市"},
7509: {7509, "濮阳市"},
7510: {7510, "许昌市"},
7511: {7511, "漯河市"},
7512: {7512, "三门峡市"},
7513: {7513, "南阳市"},
7514: {7514, "商丘市"},
7515: {7515, "信阳市"},
7516: {7516, "周口市"},
7517: {7517, "驻马店市"},
7518: {7518, "济源市"},
8000: {8000, "河北省"},
8001: {8001, "石家庄市"},
8002: {8002, "唐山市"},
8003: {8003, "秦皇岛市"},
8004: {8004, "邯郸市"},
8005: {8005, "邢台市"},
8006: {8006, "保定市"},
8007: {8007, "张家口市"},
8008: {8008, "承德市"},
8009: {8009, "沧州市"},
8010: {8010, "廊坊市"},
8011: {8011, "衡水市"},
8500: {8500, "山西省"},
8501: {8501, "太原市"},
8502: {8502, "大同市"},
8503: {8503, "阳泉市"},
8504: {8504, "长治市"},
8505: {8505, "晋城市"},
8506: {8506, "朔州市"},
8507: {8507, "晋中市"},
8508: {8508, "忻州市"},
8509: {8509, "临汾市"},
8510: {8510, "运城市"},
8511: {8511, "吕梁地区"},
9000: {9000, "内蒙古"},
9001: {9001, "呼和浩特"},
9002: {9002, "包头市"},
9003: {9003, "乌海市"},
9004: {9004, "赤峰市"},
9005: {9005, "通辽市"},
9006: {9006, "鄂尔多斯"},
9007: {9007, "乌兰察布"},
9008: {9008, "锡林郭勒"},
9009: {9009, "呼伦贝尔"},
9010: {9010, "巴彦淖尔"},
9011: {9011, "阿拉善盟"},
9012: {9012, "兴安盟"},
9500: {9500, "吉林省"},
9501: {9501, "长春市"},
9502: {9502, "吉林市"},
9503: {9503, "四平市"},
9504: {9504, "辽源市"},
9505: {9505, "通化市"},
9506: {9506, "白山市"},
9507: {9507, "松原市"},
9508: {9508, "白城市"},
9509: {9509, "延边州"},
10000: {10000, "黑龙江"},
10001: {10001, "哈尔滨市"},
10002: {10002, "齐齐哈尔"},
10003: {10003, "鹤岗市"},
10004: {10004, "双鸭山市"},
10005: {10005, "鸡西市"},
10006: {10006, "大庆市"},
10007: {10007, "伊春市"},
10008: {10008, "牡丹江市"},
10009: {10009, "佳木斯市"},
10010: {10010, "七台河市"},
10011: {10011, "黑河市"},
10012: {10012, "绥化市"},
10013: {10013, "大兴安岭"},
10500: {10500, "安徽省"},
10501: {10501, "合肥市"},
10502: {10502, "芜湖市"},
10503: {10503, "蚌埠市"},
10504: {10504, "淮南市"},
10505: {10505, "马鞍山市"},
10506: {10506, "淮北市"},
10507: {10507, "铜陵市"},
10508: {10508, "安庆市"},
10509: {10509, "黄山市"},
10510: {10510, "滁州市"},
10511: {10511, "阜阳市"},
10512: {10512, "宿州市"},
10513: {10513, "巢湖市"},
10514: {10514, "六安市"},
10515: {10515, "亳州市"},
10516: {10516, "宣城市"},
10517: {10517, "池州市"},
11000: {11000, "湖南省"},
11001: {11001, "长沙市"},
11002: {11002, "株州市"},
11003: {11003, "湘潭市"},
11004: {11004, "衡阳市"},
11005: {11005, "邵阳市"},
11006: {11006, "岳阳市"},
11007: {11007, "常德市"},
11008: {11008, "张家界市"},
11009: {11009, "益阳市"},
11010: {11010, "郴州市"},
11011: {11011, "永州市"},
11012: {11012, "怀化市"},
11013: {11013, "娄底市"},
11014: {11014, "湘西州"},
11500: {11500, "广西区"},
11501: {11501, "南宁市"},
11502: {11502, "柳州市"},
11503: {11503, "桂林市"},
11504: {11504, "梧州市"},
11505: {11505, "北海市"},
11506: {11506, "防城港市"},
11507: {11507, "钦州市"},
11508: {11508, "贵港市"},
11509: {11509, "玉林市"},
11510: {11510, "南宁地区"},
11511: {11511, "柳州地区"},
11512: {11512, "贺州地区"},
11513: {11513, "百色地区"},
11514: {11514, "河池地区"},
12000: {12000, "海南省"},
12001: {12001, "海口市"},
12002: {12002, "三亚市"},
12003: {12003, "五指山市"},
12004: {12004, "琼海市"},
12005: {12005, "儋州市"},
12006: {12006, "琼山市"},
12007: {12007, "文昌市"},
12008: {12008, "万宁市"},
12009: {12009, "东方市"},
12010: {12010, "澄迈县"},
12011: {12011, "定安县"},
12012: {12012, "屯昌县"},
12013: {12013, "临高县"},
12014: {12014, "白沙县"},
12015: {12015, "昌江县"},
12016: {12016, "乐东县"},
12017: {12017, "陵水县"},
12018: {12018, "保亭县"},
12019: {12019, "琼中县"},
12500: {12500, "云南省"},
12501: {12501, "昆明市"},
12502: {12502, "曲靖市"},
12503: {12503, "玉溪市"},
12504: {12504, "保山市"},
12505: {12505, "昭通市"},
12506: {12506, "思茅地区"},
12507: {12507, "临沧地区"},
12508: {12508, "丽江地区"},
12509: {12509, "文山州"},
12510: {12510, "红河州"},
12511: {12511, "西双版纳"},
12512: {12512, "楚雄州"},
12513: {12513, "大理州"},
12514: {12514, "德宏州"},
12515: {12515, "怒江州"},
12516: {12516, "迪庆州"},
13000: {13000, "贵州省"},
13001: {13001, "贵阳市"},
13002: {13002, "六盘水市"},
13003: {13003, "遵义市"},
13004: {13004, "安顺市"},
13005: {13005, "铜仁地区"},
13006: {13006, "毕节地区"},
13007: {13007, "黔西南州"},
13008: {13008, "黔东南州"},
13009: {13009, "黔南州"},
13500: {13500, "西藏区"},
13501: {13501, "拉萨市"},
13502: {13502, "那曲地区"},
13503: {13503, "昌都地区"},
13504: {13504, "山南地区"},
13505: {13505, "日喀则"},
13506: {13506, "阿里地区"},
13507: {13507, "林芝地区"},
14000: {14000, "甘肃省"},
14001: {14001, "兰州市"},
14002: {14002, "金昌市"},
14003: {14003, "白银市"},
14004: {14004, "天水市"},
14005: {14005, "嘉峪关市"},
14006: {14006, "武威市"},
14007: {14007, "定西地区"},
14008: {14008, "平凉地区"},
14009: {14009, "庆阳地区"},
14010: {14010, "陇南地区"},
14011: {14011, "张掖地区"},
14012: {14012, "酒泉地区"},
14013: {14013, "甘南州"},
14014: {14014, "临夏州"},
14500: {14500, "宁夏区"},
14501: {14501, "银川市"},
14502: {14502, "石嘴山市"},
14503: {14503, "吴忠市"},
14504: {14504, "固原市"},
15000: {15000, "青海省"},
15001: {15001, "西宁市"},
15002: {15002, "海东地区"},
15003: {15003, "海北州"},
15004: {15004, "黄南州"},
15005: {15005, "海南州"},
15006: {15006, "果洛州"},
15007: {15007, "玉树州"},
15008: {15008, "海西州"},
15500: {15500, "新疆区"},
15501: {15501, "乌鲁木齐"},
15502: {15502, "克拉玛依"},
15503: {15503, "石河子市"},
15504: {15504, "吐鲁番"},
15505: {15505, "哈密地区"},
15506: {15506, "和田地区"},
15507: {15507, "阿克苏"},
15508: {15508, "喀什地区"},
15509: {15509, "克孜勒苏"},
15510: {15510, "巴音郭楞"},
15511: {15511, "昌吉州"},
15512: {15512, "博尔塔拉"},
15513: {15513, "伊犁州"},
16000: {16000, "香港区"},
16500: {16500, "澳门区"},
17500: {17500, "台湾省"},
15514: {15514, "阿勒泰地区"},
}
)

View File

@@ -0,0 +1,45 @@
package model
const (
// MobileUserAgentFlag is
MobileUserAgentFlag = "Mobile"
// PlatH5 is
PlatH5 = "h5"
// PlatPC is
PlatPC = "pc"
)
// ProcessRes 请求获取极验验证响应参数
type ProcessRes struct {
Success int64 `json:"success"`
CaptchaID string `json:"gt"`
Challenge string `json:"challenge"`
NewCaptcha int `json:"new_captcha"`
}
//ValidateRes 验证返回值
type ValidateRes struct {
Seccode string `json:"seccode"`
}
// GeeCaptchaRequest 获取极验验证请求参数
type GeeCaptchaRequest struct {
MID int64 `json:"mid" form:"mid"`
IP string `json:"ip" form:"ip"`
// h5 web native
ClientType string `json:"client_type" form:"client_type" default:"web"`
}
// GeeCheckRequest 校验极验验证码请求参数
type GeeCheckRequest struct {
MID int64
Challenge string `json:"challenge" form:"challenge" validate:"required"`
Validate string `json:"validate" form:"validate" validate:"required"`
Seccode string `json:"seccode" form:"seccode" validate:"required"`
ClientType string `json:"client_type" form:"client_type" default:"web"`
}
// GeeCheckResponse 校验极验验证码响应参数
type GeeCheckResponse struct {
NewVoucher string `json:"new_voucher"`
}

View File

@@ -0,0 +1,50 @@
package model
// TokenResq .
type TokenResq struct {
CommonResq
Data *Token `json:"data"`
}
// Token .
type Token struct {
Token string `json:"token"`
URL string `json:"url"`
}
// CommonResq .
type CommonResq struct {
Code int64 `json:"code"`
TS int64 `json:"ts"`
Message string `json:"message"`
}
// ResourceCodeResq .
type ResourceCodeResq struct {
CommonResq
Data *ResourceCode `json:"data"`
}
// ResourceCode .
type ResourceCode struct {
Code string `json:"code"`
Status int8 `json:"status"`
Days int32 `json:"days"`
BatchCodeID int64 `json:"batch_code_id"`
}
// CMAccountInfo is
type CMAccountInfo struct {
Nickname string `json:"nickname"`
CertificationTitle string `json:"certification_title"`
CreditCode string `json:"credit_code"`
CompanyName string `json:"company_name"`
Organization string `json:"organization"`
OrganizationType string `json:"organization_type"`
}
// OfficialPermissionResponse is
type OfficialPermissionResponse struct {
DeniedRoles []int8 `json:"denied_roles"`
Metadata map[string]interface{} `json:"metadata"`
}

View File

@@ -0,0 +1,69 @@
package model
import (
"strconv"
accmdl "go-common/app/service/main/account/model"
usmdl "go-common/app/service/main/usersuit/model"
xtime "go-common/library/time"
)
// RichInviteStat rich invite stat.
type RichInviteStat struct {
Mid int64 `json:"mid"`
CurrentLimit int64 `json:"current_limit"`
CurrentBought int64 `json:"current_bought"`
TotalBought int64 `json:"total_bought"`
TotalUsed int64 `json:"total_used"`
InviteCodes []*RichInvite `json:"invite_codes"`
}
// RichInvite rich invite.
type RichInvite struct {
Status int64 `json:"status"`
Mid int64 `json:"mid"`
Code string `json:"invite_code"`
Ctime xtime.Time `json:"buy_time"`
Expires int64 `json:"expires"`
Invitee *Invitee `json:"invitee,omitempty"`
UsedAt int64 `json:"used_at,omitempty"`
}
// NewRichInvite new a rich invite.
func NewRichInvite(inv *usmdl.Invite, info *accmdl.Info) *RichInvite {
if inv == nil {
return nil
}
var invt *Invitee
if inv.Used() {
if info != nil {
invt = &Invitee{
Mid: inv.Imid,
Uname: info.Name,
Face: info.Face,
}
} else {
invt = &Invitee{
Mid: inv.Imid,
Uname: "用户" + strconv.FormatInt(inv.Imid, 10),
Face: "http://static.hdslb.com/images/member/noface.gif",
}
}
}
return &RichInvite{
Status: inv.Status,
Mid: inv.Mid,
Code: inv.Code,
Ctime: inv.Ctime,
Expires: inv.Expires,
Invitee: invt,
UsedAt: inv.UsedAt,
}
}
// Invitee invitee.
type Invitee struct {
Mid int64 `json:"mid"`
Uname string `json:"uname"`
Face string `json:"face"`
}

View File

@@ -0,0 +1,31 @@
package model
// IdentifyStatus .
type IdentifyStatus int8
// IdentifyStatus enum
const (
IdentifyNotOK IdentifyStatus = iota
IdentifyOK
// ApiIdentifyOk identify ok
APIIdentifyOk = 0
// ApiIdentifyNoInfo no identify info
APIIdentifyNoInfo = 1
)
// Identification .
type Identification struct {
Identification IdentifyStatus `json:"identification"`
}
// IdentifyInfo identify info.
type IdentifyInfo struct {
Identify int8 `json:"'identify'"`
Phone int8 `json:"phone"`
}
// IdentifyApply identify apply info.
type IdentifyApply struct {
Identify int8 `json:"'identify'"`
Applied bool `json:"applied"`
}

View File

@@ -0,0 +1,36 @@
package model
import (
"go-common/library/time"
)
const (
// NoticeStatusNotify notify
NoticeStatusNotify = 1
// NoticeStatusNotNotify not notify
NoticeStatusNotNotify = 0
// NoticeTypeSecurity security
NoticeTypeSecurity = "security"
)
// Notice2 v2.
type Notice2 struct {
Status int8 `json:"status"`
Type string `json:"type,omitempty"`
Realname *Realname `json:"realname,omitempty"`
Security *Security `json:"security,omitempty"`
}
// Realname struct.
type Realname struct {
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
}
// Security struct.
type Security struct {
Location string `json:"location,omitempty"`
Time time.Time `json:"time,omitempty"`
IP string `json:"ip,omitempty"`
Mid int64 `json:"mid,omitempty"`
}

View File

@@ -0,0 +1,83 @@
package model
import (
"strconv"
usmdl "go-common/app/service/main/usersuit/model"
)
// EquipPHP struct.
type EquipPHP struct {
Pid int64 `json:"pid"`
Coins float64 `json:"coins"`
Image string `json:"image"`
ImageModel string `json:"image_model"`
FaceURL string `json:"face_url"`
}
// GroupPHP php group result
type GroupPHP struct {
Name string `json:"group_name"`
Count int64 `json:"group_count"`
Pendant []*usmdl.Pendant `json:"pendant_info"`
}
// PendantPHP php pendant result
type PendantPHP struct {
Pid int64 `json:"pid"`
Name string `json:"name"`
Image string `json:"image"`
ImageModel string `json:"image_model"`
}
// GroupEntryPHP php vip pendant result
type GroupEntryPHP struct {
Pid int64 `json:"pid"`
Money int64 `json:"money"`
Name string `json:"name"`
Image string `json:"image"`
ImageModel string `json:"image_model"`
}
// GroupVipPHP php vip pendant result
type GroupVipPHP struct {
Pid int64 `json:"pid"`
Money int64 `json:"money"`
MoneyType int8 `json:"money_type"`
Expire int64 `json:"display_expire"`
Name string `json:"name"`
Image string `json:"image"`
ImageModel string `json:"image_model"`
}
// MyPHP struct.
type MyPHP struct {
Pid int64 `json:"pid"`
Name string `json:"name"`
MoneyType int8 `json:"money_type"`
Image string `json:"image"`
ImageModel string `json:"image_model"`
Expire int64 `json:"expire"`
IsActivated int8 `json:"is_activated"`
IsOnline int8 `json:"is_online"`
IsVip int8 `json:"is_vip"`
}
// MyHistoryPHP struct.
type MyHistoryPHP struct {
Pid int64 `json:"pid"`
Image string `json:"image"`
Name string `json:"name"`
BuyTime int64 `json:"buy_time"`
PayID string `json:"pay_id"`
Cost string `json:"cost"`
TimeLength int64 `json:"time_length"`
}
// FormatImgURL format images url
func FormatImgURL(mid int64, img string) (url string) {
if len(img) > 0 {
return "http://i" + strconv.FormatInt(mid%3, 10) + ".hdslb.com" + img
}
return
}

View File

@@ -0,0 +1,73 @@
package model
// RealnameBool is.
type RealnameBool uint8
// RealnameBool enum
const (
RealnameFalse RealnameBool = iota
RealnameTrue
)
// RealnameCountry .
type RealnameCountry struct {
ID int `json:"id"`
CName string `json:"cname"`
}
// RealnameCardType .
type RealnameCardType struct {
ID int `json:"id"`
Name string `json:"name"`
}
// RealnameChannel .
type RealnameChannel struct {
Name string
Flag RealnameBool
}
// ParamRealnameAlipayApply .
type ParamRealnameAlipayApply struct {
Realname string `form:"real_name"`
CardNum string `form:"card_num"`
Capture int `form:"capture"`
ImgToken string `form:"img_token"`
}
// RealnameAlipayApply .
type RealnameAlipayApply struct {
URL string `json:"url"`
// Bizno string `json:"biz_no"`
}
// RealnameAlipayConfirm .
type RealnameAlipayConfirm struct {
Passed RealnameBool `json:"passed"`
Reason string `json:"reason"`
}
// ParamRealnameCaptchaGTCheck .
type ParamRealnameCaptchaGTCheck struct {
Remote RealnameBool `form:"remote"`
Challenge string `form:"challenge"`
Validate string `form:"validate"`
Seccode string `form:"seccode"`
}
// ParamRealnameCaptchaGTRefresh .
type ParamRealnameCaptchaGTRefresh struct {
Hash string `form:"hash"`
}
// RealnameCaptchaGTRegister .
type RealnameCaptchaGTRegister struct {
Remote RealnameBool `json:"remote"`
ID string `json:"gt_id"`
Challenge string `json:"gt_challenge"`
}
// RealnameCaptchaGTValidate .
type RealnameCaptchaGTValidate struct {
State RealnameBool `json:"state"`
}

View File

@@ -0,0 +1,26 @@
package model
import (
"bytes"
"regexp"
)
// var .
var (
EmojiPattern = regexp.MustCompile(`[\x{1F600}-\x{1F6FF}|[\x{2600}-\x{26FF}]`)
NamePattern = regexp.MustCompile("^[A-Za-z0-9\uAC00-\uD788\u3041-\u309E\u30A1-\u30FE\u3131-\u3163\u4E00-\u9FA5\uF92C-\uFA29_\\-]+$")
)
// HasEmoji is used to check string is contain emoji
func HasEmoji(s string) bool {
return EmojiPattern.MatchString(s)
}
// ValidName check string is contain special characters.
func ValidName(s string) bool {
h := []byte(s)
if bytes.Contains(h, []byte("\xF0\x9F")) || bytes.Contains(h, []byte("\xC2\xA0")) {
return false
}
return NamePattern.MatchString(s) && !EmojiPattern.MatchString(s)
}

View File

@@ -0,0 +1,20 @@
package model
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestValidName(t *testing.T) {
Convey("ValidName", t, func() {
So(ValidName("FasdA0asd"+string(1)+"asdas"), ShouldBeFalse)
So(ValidName("FasdA0asd,asdas"), ShouldBeFalse)
So(ValidName("Fasd啊三0a😀asdas"), ShouldBeFalse)
So(ValidName("Fasd啊asdas"), ShouldBeFalse)
So(ValidName("Fasd啊\asdas"), ShouldBeFalse)
So(ValidName("Fasd啊-asdas_"), ShouldBeTrue)
So(ValidName("Fasd啊\xF0\x9Fasdas_"), ShouldBeFalse)
So(ValidName("Fasd啊xC2\xA0Fasdas_"), ShouldBeFalse)
})
}

View File

@@ -0,0 +1,223 @@
package model
import (
"strconv"
accountv1 "go-common/app/service/main/account/api"
relation "go-common/app/service/main/relation/model"
bm "go-common/library/net/http/blademaster"
)
// Vip .
type 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"`
}
// Following is user followinng info.
type Following struct {
*relation.Following
Uname string `json:"uname"`
Face string `json:"face"`
Sign string `json:"sign"`
// OfficialVerify member.OfficialInfo `json:"official_verify"`
OfficialVerify struct {
Type int8 `json:"type"`
Desc string `json:"desc"`
} `json:"official_verify"`
Vip Vip `json:"vip"`
}
// Tag is user info.
type Tag struct {
Mid int64 `json:"mid"`
Uname string `json:"uname"`
Face string `json:"face"`
Sign string `json:"sign"`
// OfficialVerify member.OfficialInfo `json:"official_verify"`
OfficialVerify struct {
Type int8 `json:"type"`
Desc string `json:"desc"`
} `json:"official_verify"`
Vip Vip `json:"vip"`
}
// 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 accountv1.PendantInfo `json:"pendant"`
Nameplate accountv1.NameplateInfo `json:"nameplate"`
OfficialVerify accountv1.OfficialInfo `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"`
}
// RecommendInfo is
type RecommendInfo struct {
Info
RecommendContent
Fans int64 `json:"fans"`
TypeName string `json:"type_name"`
SecondTypeName string `json:"second_type_name"`
TrackID string `json:"track_id"`
Relation *relation.Following `json:"relation"`
}
// TagSuggestRecommendInfo is
type TagSuggestRecommendInfo struct {
TagName string `json:"tagname"`
UpList []*RecommendInfo `json:"up_list"`
MatchCnt int64 `json:"match_cnt"`
}
/*
{
"code": 0,
"trackid": "123",
"msg": "success",
"data": [
{
"up_id": 123,
"rec_reason": "游戏区热门up主",
"rec_type": 1,
"tid": 4,
"second_tid": 173
}
]
}
*/
// RecommendContent is
type RecommendContent struct {
UpID int64 `json:"up_id"`
RecReason string `json:"rec_reason"`
RecType int64 `json:"rec_type"`
Tid int16 `json:"tid"`
SecondTid int16 `json:"second_tid"`
}
// RecommendResponse is
type RecommendResponse struct {
Code int64 `json:"code"`
TrackID string `json:"trackid"`
Msg string `json:"msg"`
Data []*RecommendContent `json:"data"`
}
// TagSuggestRecommendContent is
type TagSuggestRecommendContent struct {
TagName string `json:"tagname"`
UpList []*RecommendContent `json:"up_list"`
MatchCnt int64 `json:"match_cnt"`
}
// UpIDs is
func (tsrc *TagSuggestRecommendContent) UpIDs() []int64 {
upIDs := make([]int64, 0, len(tsrc.UpList))
for _, up := range tsrc.UpList {
upIDs = append(upIDs, up.UpID)
}
return upIDs
}
// TagSuggestRecommendResponse is
type TagSuggestRecommendResponse struct {
Code int64 `json:"code"`
TrackID string `json:"trackid"`
Msg string `json:"msg"`
Data []*TagSuggestRecommendContent `json:"data"`
}
// FromCard from card.
func (i *Info) FromCard(c *accountv1.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
i.OfficialVerify = c.Official
i.Vip.Type = int(c.Vip.Type)
i.Vip.VipStatus = int(c.Vip.Status)
i.Vip.DueDate = c.Vip.DueDate
}
// BatchModifyResult is
type BatchModifyResult struct {
FailedFids []int64 `json:"failed_fids"`
}
// ArgRecommend is
type ArgRecommend struct {
Mid int64
Device *bm.Device
RemoteIP string
MainTids string `form:"main_tids"`
SubTids string `form:"sub_tids"`
PageSize int64 `form:"pagesize" default:"10"`
}
// ArgTagSuggestRecommend is
type ArgTagSuggestRecommend struct {
Mid int64
Device *bm.Device
RemoteIP string
TagName string `form:"tagname"`
ContextID string `form:"context_id" validate:"required"`
PageSize int64 `form:"pagesize" default:"10"`
}
// ArgAchieveGet is
type ArgAchieveGet struct {
Mid int64
Award string `form:"award" validate:"required"`
}
// ArgAchieve is
type ArgAchieve struct {
AwardToken string `form:"award_token" validate:"required"`
}
// AchieveReply is
type AchieveReply struct {
relation.Achieve
Metadata map[string]interface{} `json:"metadata"`
}
// ArgSameFollowing is
type ArgSameFollowing struct {
Mid int64 `form:"mid"`
VMid int64 `form:"vmid" validate:"required"`
Order string `form:"order"`
PS int64 `form:"ps"`
PN int64 `form:"pn"`
ReVersion uint64 `form:"re_version"`
}

View File

@@ -0,0 +1,40 @@
package model
// ReplyHistory reply history
type ReplyHistory struct {
Page struct {
Num int `json:"num"`
Size int `json:"size"`
Total int `json:"total"`
} `json:"page"`
Records []*Record `json:"records"`
}
// Record record
type Record struct {
ID int `json:"id"`
Oid int64 `json:"oid"`
OidStr string `json:"oid_str"` // oid 前端会溢出改用 string
Type int64 `json:"type"`
Floor int `json:"floor"`
Like int `json:"like"`
Rcount int `json:"rcount"`
Mid int64 `json:"mid"`
State int `json:"state"`
Message string `json:"message"`
Ctime string `json:"ctime"`
Members []*Member `json:"members"`
RecordAppend
}
// RecordAppend record append
type RecordAppend struct {
Title string `json:"title"`
URL string `json:"url"`
}
// Member member
type Member struct {
Mid int64 `json:"mid"`
Uname string `json:"uname"`
}

View File

@@ -0,0 +1,19 @@
package model
// PendantInfo is.
type PendantInfo struct {
Pid int `json:"pid"`
Name string `json:"name"`
Image string `json:"image"`
Expire int `json:"expire"`
}
// NameplateInfo is.
type NameplateInfo struct {
Nid int `json:"nid"`
Name string `json:"name"`
Image string `json:"image"`
ImageSmall string `json:"image_small"`
Level string `json:"level"`
Condition string `json:"condition"`
}

View File

@@ -0,0 +1,310 @@
package model
import (
col "go-common/app/service/main/coupon/model"
vipv1 "go-common/app/service/main/vip/api"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/time"
)
// vip tips.
const (
PanelPosition int8 = iota + 1
PgcPosition
)
const (
// PlatAndroid is int8 for android.
PlatAndroid = int8(0)
// PlatIPhone is int8 for iphone.
PlatIPhone = int8(1)
// PlatIPad is int8 for ipad.
PlatIPad = int8(2)
// PlatWPhone is int8 for wphone.
PlatWPhone = int8(3)
// PlatAndroidG is int8 for Android Googleplay.
PlatAndroidG = int8(4)
// PlatIPhoneI is int8 for Iphone Global.
PlatIPhoneI = int8(5)
// PlatIPadI is int8 for IPAD Global.
PlatIPadI = int8(6)
// PlatAndroidTV is int8 for AndroidTV Global.
PlatAndroidTV = int8(7)
// PlatAndroidI is int8 for Android Global.
PlatAndroidI = int8(8)
// PlatIpadHD is int8 for IpadHD
PlatIpadHD = int8(9)
// PlatAndroidB is int8 for Android Blue.
PlatAndroidB = int8(10)
// PlatIPhoneB is int8 for Android Blue.
PlatIPhoneB = int8(11)
)
// resource id .
const (
ResourceBannerIPhone = "2850"
ResourceBannerAndroid = "2857"
ResourceBannerIPad = "2864"
ResourceBuyIPhone = "2898"
ResourceBuyAndroid = "2903"
ResourceBuyIPad = "2908"
)
// IsAndroid check plat is android or ipad.
func IsAndroid(plat int8) bool {
return plat == PlatAndroid || plat == PlatAndroidG || plat == PlatAndroidI || plat == PlatAndroidB
}
// IsIOS check plat is iphone or ipad.
func IsIOS(plat int8) bool {
return plat == PlatIPad || plat == PlatIPhone || plat == PlatIPadI || plat == PlatIPhoneI
}
// IsIPhone check plat is iphone.
func IsIPhone(plat int8) bool {
return plat == PlatIPhone || plat == PlatIPhoneI
}
// IsIPad check plat is pad.
func IsIPad(plat int8) bool {
return plat == PlatIPad || plat == PlatIPadI || plat == PlatIpadHD
}
// IsIPhoneB check plat is iphone_b.
func IsIPhoneB(plat int8) bool {
return plat == PlatIPhoneB
}
// Plat .
func Plat(mobiApp, device string) int8 {
switch mobiApp {
case "iphone":
if device == "pad" {
return PlatIPad
}
return PlatIPhone
case "white":
return PlatIPhone
case "ipad":
return PlatIpadHD
case "android":
return PlatAndroid
case "win", "winphone":
return PlatWPhone
case "android_G":
return PlatAndroidG
case "android_i":
return PlatAndroidI
case "iphone_i":
if device == "pad" {
return PlatIPadI
}
return PlatIPhoneI
case "ipad_i":
return PlatIPadI
case "android_tv":
return PlatAndroidTV
case "android_b":
return PlatAndroidB
case "iphone_b":
return PlatIPhoneB
}
return PlatIPhone
}
// VIPInfo vip info.
type VIPInfo struct {
Mid int64 `json:"mid"`
Type int8 `json:"vipType"`
DueDate int64 `json:"vipDueDate"`
DueMsec int64 `json:"vipSurplusMsec"`
DueRemark string `json:"dueRemark"`
Status int8 `json:"accessStatus"`
VipStatus int8 `json:"vipStatus"`
}
// TipsReq tips request.
type TipsReq struct {
Version int64 `form:"build"`
Platform string `form:"platform" validate:"required"`
Position int8 `form:"position" default:"1"`
}
//CodeInfoReq code info request
type CodeInfoReq struct {
Appkey string `form:"appkey" validate:"required"`
Sign string `form:"sign"`
Ts time.Time `form:"ts"`
StartTime time.Time `form:"start_time" validate:"required"`
EndTime time.Time `form:"end_time" validate:"required"`
Cursor int64 `form:"cursor"`
}
// VipPanelRes .
type VipPanelRes struct {
Device string `form:"device"`
MobiApp string `form:"mobi_app"`
Platform string `form:"platform" default:"pc"`
SortTP int8 `form:"sort_type"`
PanelType string `form:"panel_type" default:"normal"`
Month int32 `form:"month"`
SubType int32 `form:"order_type"`
Build int64 `form:"build"`
}
// ArgVipCoupon req.
type ArgVipCoupon struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
}
// ArgVipCancelPay req.
type ArgVipCancelPay struct {
CouponToken string `form:"coupon_token" validate:"required"`
}
// coupon cancel explain
const (
CouponCancelExplain = "解锁成功,请重新选择劵信息"
)
// const for vip
const (
MobiAppIphone = iota + 1
MobiAppIpad
MobiAppPC
MobiAppANDROID
)
//MobiAppByName .
var MobiAppByName = map[string]int{
"iphone": MobiAppIphone,
"ipad": MobiAppIpad,
"pc": MobiAppPC,
"android": MobiAppANDROID,
}
// MobiAppPlat .
func MobiAppPlat(mobiApp string) (p int) {
p = MobiAppByName[mobiApp]
if p == 0 {
// def pc.
p = MobiAppPC
}
return
}
// ArgVipPanel arg panel.
type ArgVipPanel struct {
Device string `form:"device"`
Build int64 `form:"build"`
MobiApp string `form:"mobi_app"`
Platform string `form:"platform" default:"pc"`
SortTP int8 `form:"sort_type"`
PanelType string `form:"panel_type" default:"normal"`
Mid int64
IP string
}
// VipPanelResp vip panel resp.
type VipPanelResp struct {
Vps []*vipmol.VipPanelInfo `json:"price_list"`
CodeSwitch int8 `json:"code_switch"`
GiveSwitch int8 `json:"give_switch"`
Privileges map[int8]*vipmol.PrivilegesResp `json:"privileges,omitempty"`
TipInfo *vipmol.TipsResp `json:"tip_info,omitempty"`
UserInfo *vipmol.VipPanelExplain `json:"user_info,omitempty"`
}
// VipPanelV8Resp vip panel v8 resp.
type VipPanelV8Resp struct {
Vps []*vipmol.VipPanelInfo `json:"price_list"`
CouponInfo *col.CouponAllowancePanelInfo `json:"coupon_info,omitempty"`
CouponSwith int8 `json:"coupon_switch,omitempty"`
CodeSwitch int8 `json:"code_switch"`
GiveSwitch int8 `json:"give_switch"`
Privileges map[int8]*vipmol.PrivilegesResp `json:"privileges,omitempty"`
TipInfo *vipmol.TipsResp `json:"tip_info,omitempty"`
UserInfo *vipmol.VipPanelExplain `json:"user_info,omitempty"`
AssociateVips []*vipmol.AssociateVipResp `json:"associate_vips,omitempty"`
}
// VipPanelRespV9 vip panel resp v9.
type VipPanelRespV9 struct {
Vps []*vipv1.ModelVipPanelInfo `json:"price_list,omitempty"`
Coupon *vipv1.CouponBySuitIDReply `json:"coupon,omitempty"`
CouponSwith int32 `json:"coupon_switch"`
CodeSwitch int32 `json:"code_switch"`
GiveSwitch int32 `json:"give_switch"`
Privileges map[int32]*vipv1.ModelPrivilegeResp `json:"privileges,omitempty"`
TipInfo *vipmol.TipsResp `json:"tip_info,omitempty"`
UserInfo *vipmol.VipPanelExplain `json:"user_info,omitempty"`
AssociateVips []*vipmol.AssociateVipResp `json:"associate_vips,omitempty"`
}
// ManagerResp manager resp.
type ManagerResp struct {
JointlyInfo []*vipmol.JointlyResp `json:"jointly_info"`
}
//ArgCreateOrder2 .
type ArgCreateOrder2 struct {
Month int32 `form:"months" validate:"required,min=1,gte=1"`
Platform string `form:"platform"`
MobiApp string `form:"mobi_app"`
Device string `form:"device"`
AppID int64 `form:"appId"`
AppSubID string `form:"appSubId"`
OrderType int8 `form:"orderType"`
Dtype int8 `form:"dtype"`
ReturnURL string `form:"returnUrl"`
CouponToken string `form:"coupon_token"`
Bmid int64 `form:"bmid"`
PanelType string `form:"panel_type" default:"normal"`
Build int64 `form:"build"`
IP string
Mid int64
}
//ArgCreateAssociateOrder create asoociate order .
type ArgCreateAssociateOrder struct {
Month int32 `form:"months" validate:"required,min=1,gte=1"`
Platform string `form:"platform" default:"pc"`
MobiApp string `form:"mobi_app"`
Device string `form:"device"`
AppID int64 `form:"appId"`
AppSubID string `form:"appSubId"`
OrderType int8 `form:"orderType"`
Dtype int8 `form:"dtype"`
ReturnURL string `form:"returnUrl"`
CouponToken string `form:"coupon_token"`
Bmid int64 `form:"bmid"`
PanelType string `form:"panel_type" default:"normal"`
Build int64 `form:"build"`
IP string
Mid int64
}
// ArgResource struct .
type ArgResource struct {
MID int64
ResIDs string
Plat int8 `form:"plat"`
Build int `form:"build" validate:"required"`
MobiApp string `form:"mobi_app" validate:"required"`
Device string `form:"device"`
Buvid string
IP string
Network string `form:"network"`
Channel string
}
// ArgCouponBySuitID coupon by suit id.
type ArgCouponBySuitID struct {
Mid int64
Sid int64 `form:"id" validate:"required,min=1,gte=1"`
Platform string `form:"platform" default:"pc"`
MobiApp string `form:"mobi_app"`
Device string `form:"device"`
PanelType string `form:"panel_type" default:"normal"`
Build int64 `form:"build"`
}

View File

@@ -0,0 +1,64 @@
package model
// ArgAuthCode get open_id args.
type ArgAuthCode struct {
Code string `form:"auth_code" validate:"required"`
APPID int64
IP string
}
// OpenIDResp open_id resp.
type OpenIDResp struct {
OpenID string `json:"open_id"`
}
// OAuth2InfoResp oauth2 resp.
type OAuth2InfoResp struct {
Mid int64 `json:"mid"`
Uname string `json:"uname"`
}
// ArgBind bind args.
type ArgBind struct {
OpenID string `form:"open_id" validate:"required"`
OutOpenID string `form:"out_open_id" validate:"required"`
AppID int64
}
// ArgUserInfoByOpenID args.
type ArgUserInfoByOpenID struct {
OpenID string `form:"open_id" validate:"required"`
AppID int64
IP string
}
// ArgBindInfo bind info args.
type ArgBindInfo struct {
Mid int64
AppID int64
}
// ArgBilibiliPrizeGrant args.
type ArgBilibiliPrizeGrant struct {
PrizeKey string `form:"prize_key" validate:"required"`
UniqueNo string `form:"unique_no" validate:"required"`
OpenID string `form:"open_id" validate:"required"`
AppID int64
}
// ArgBilibiliVipGrant bilibili vip grant args.
type ArgBilibiliVipGrant struct {
OpenID string `form:"open_id" validate:"required"`
OutOpenID string `form:"out_open_id" validate:"required"`
OutOrderNO string `form:"out_order_no" validate:"required"`
Duration int32 `form:"duration" validate:"required"`
AppID int64
}
// ArgOpenAuthCallBack args.
type ArgOpenAuthCallBack struct {
ThirdCode string `form:"auth_code" validate:"required"`
State string `form:"state" validate:"required"`
Mid int64
AppID int64
}

View File

@@ -0,0 +1,26 @@
package model
import "go-common/library/time"
// WelfareRes welfare list info
type WelfareRes struct {
ID int `json:"id"`
Name string `json:"name"`
HomepageUri string `json:"homepage_uri"`
BackdropUri string `json:"backdrop_uri"`
Tid int `json:"tid"`
Rank int `json:"rank"`
}
// WelfareInfo welfare info
type WelfareInfo struct {
ID int `json:"id"`
Name string `json:"name"`
Desc string `json:"desc"`
HomepageUri string `json:"homepage_uri"`
BackdropUri string `json:"backdrop_uri"`
SurplusCount int `json:"surplus_count"`
Received bool `json:"received"`
Stime time.Time `json:"stime"`
Etime time.Time `json:"etime"`
}

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