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,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 = [
"dao_test.go",
"livewallet_test.go",
"paycenter_test.go",
"userext_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/live/app-room/conf:go_default_library",
"//app/interface/live/app-room/model:go_default_library",
"//library/log:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
"livewallet.go",
"paycenter.go",
"userext.go",
],
importpath = "go-common/app/interface/live/app-room/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/live/app-room/conf:go_default_library",
"//app/interface/live/app-room/model:go_default_library",
"//app/service/live/userext/api/liverpc:go_default_library",
"//app/service/live/userext/api/liverpc/v0:go_default_library",
"//app/service/live/xuserex/api/grpc/v1:go_default_library",
"//library/cache:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/rpc/liverpc: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",
"//app/interface/live/app-room/dao/av:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,20 @@
package dao
import (
"go-common/app/interface/live/app-room/conf"
userextApi "go-common/app/service/live/userext/api/liverpc"
"go-common/library/net/rpc/liverpc"
)
// InitAPI init all service APIs
func InitAPI(dao *Dao) {
dao.UserExtAPI = userextApi.New(getConf("userext"))
}
func getConf(appName string) *liverpc.ClientConfig {
c := conf.Conf.LiveRpc
if c != nil {
return c[appName]
}
return nil
}

View File

@@ -0,0 +1,20 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"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"],
)

View File

@@ -0,0 +1,60 @@
package dao
import (
"context"
"go-common/app/interface/live/app-room/conf"
userextApi "go-common/app/service/live/userext/api/liverpc"
xUserEx "go-common/app/service/live/xuserex/api/grpc/v1"
"go-common/library/cache"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
_payCenterWalletURL = "/wallet-int/wallet/getUserWalletInfo"
_liveWalletURL = "/x/internal/livewallet/wallet/getAll"
)
// Dao dao
type Dao struct {
c *conf.Config
payCenterWalletURL string
payCenterClient *bm.Client
liveWalletURL string
liveWalletClient *bm.Client
UserExtAPI *userextApi.Client
giftCache *cache.Cache
XuserexAPI *xUserEx.Client
}
// New init mysql db
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
c: c,
payCenterWalletURL: c.Host.PayCenter + _payCenterWalletURL,
payCenterClient: bm.NewClient(c.HTTPClient.PayCenter),
liveWalletURL: c.Host.LiveRpc + _liveWalletURL,
liveWalletClient: bm.NewClient(c.HTTPClient.LiveRpc),
giftCache: cache.New(1, 1024),
}
xUserexApi, err := xUserEx.NewClient(c.Warden)
if err != nil {
log.Error("init xuserex error(%v)", err)
}
dao.XuserexAPI = xUserexApi
InitAPI(dao)
return
}
// Close close the resource.
func (d *Dao) Close() {
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) error {
// TODO: if you need use mc,redis, please add
// check
return nil
}

View File

@@ -0,0 +1,21 @@
package dao
import (
"go-common/app/interface/live/app-room/conf"
"go-common/library/log"
"os"
"testing"
)
var testDao *Dao
func TestMain(m *testing.M) {
conf.ConfPath = "../cmd/test.toml"
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Log)
defer log.Close()
testDao = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,55 @@
package dao
import (
"context"
"crypto/md5"
"encoding/hex"
"github.com/pkg/errors"
"go-common/app/interface/live/app-room/model"
"go-common/library/ecode"
"net/http"
"net/url"
"strconv"
"time"
)
//LiveWallet 获取用户直播钱包数据
func (d *Dao) LiveWallet(c context.Context, mid int64, platform string) (wallet *model.LiveWallet, err error) {
params := url.Values{}
params.Set("uid", strconv.FormatInt(mid, 10))
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("appkey", d.c.HTTPClient.LiveRpc.Key)
tmp := params.Encode() + d.c.HTTPClient.LiveRpc.Secret
mh := md5.Sum([]byte(tmp))
sign := hex.EncodeToString(mh[:])
params.Set("sign", sign)
req, _ := http.NewRequest("GET", d.liveWalletURL+"?"+params.Encode(), nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("platform", platform)
var wr struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
Gold string `json:"gold"`
Silver string `json:"silver"`
GoldRechargeCnt string `json:"gold_recharge_cnt"`
GoldPayCnt string `json:"gold_pay_cnt"`
SilverPayCnt string `json:"silver_pay_cnt"`
} `json:"data"`
}
if err = d.liveWalletClient.Do(c, req, &wr); err != nil {
return
}
if wr.Code != 0 {
err = errors.Wrap(ecode.Int(wr.Code), d.liveWalletURL+"?"+params.Encode())
return
}
wallet = &model.LiveWallet{}
wallet.Gold, _ = strconv.ParseInt(wr.Data.Gold, 10, 64)
wallet.Silver, _ = strconv.ParseInt(wr.Data.Silver, 10, 64)
wallet.GoldRechargeCnt, _ = strconv.ParseInt(wr.Data.GoldRechargeCnt, 10, 64)
wallet.GoldPayCnt, _ = strconv.ParseInt(wr.Data.GoldPayCnt, 10, 64)
wallet.SilverPayCnt, _ = strconv.ParseInt(wr.Data.SilverPayCnt, 10, 64)
return
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestDao_LiveWallet(t *testing.T) {
Convey("normal", t, func() {
mid := int64(1)
w, e := testDao.LiveWallet(context.Background(), mid, "android")
So(e, ShouldBeNil)
t.Logf("%+v", w)
})
}

View File

@@ -0,0 +1,130 @@
package dao
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"github.com/pkg/errors"
"go-common/app/interface/live/app-room/model"
"go-common/library/ecode"
"go-common/library/log"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
const (
customID = "10005"
)
//PayCenterWallet Wallet get user bcoin doc:http://info.bilibili.co/pages/viewpage.action?pageId=7559096
func (d *Dao) PayCenterWallet(c context.Context, mid int64, platform string) (wallet *model.Wallet, err error) {
var plat int
if platform == "ios" {
plat = 1
} else if platform == "android" {
plat = 2
} else if platform == "pc" {
plat = 3
} else {
err = ecode.ParamInvalid
return
}
platStr := strconv.Itoa(plat)
params := url.Values{}
params.Set("customerId", customID)
params.Set("platformType", platStr)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("traceId", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("timestamp", strconv.FormatInt(time.Now().UnixNano()/1e6, 10))
params.Set("signType", "MD5")
params.Set("token", d.c.HTTPClient.PayCenter.Secret)
type pJSON struct {
CustomerID string `json:"customerId"`
PlatformType int `json:"platformType"`
Mid int64 `json:"mid"`
TraceID string `json:"traceId"`
Timestamp string `json:"timestamp"`
SignType string `json:"signType"`
Sign string `json:"sign"`
}
tmp := encode(params)
mh := md5.Sum([]byte(tmp))
sign := hex.EncodeToString(mh[:])
p := &pJSON{
CustomerID: customID,
PlatformType: plat,
Mid: mid,
TraceID: params.Get("traceId"),
Timestamp: params.Get("timestamp"),
SignType: params.Get("signType"),
Sign: sign,
}
bs, _ := json.Marshal(p)
req, _ := http.NewRequest("POST", d.payCenterWalletURL, strings.NewReader(string(bs)))
req.Header.Set("Content-Type", "application/json")
var res struct {
Code int `json:"errno"`
Msg string `json:"msg"`
Data struct {
// DefaultBp float32 `json:"defaultBp"`
CouponBalance float32 `json:"couponBalance"`
AvailableBp float32 `json:"availableBp"`
DefaultBp float32 `json:"defaultBp"`
IosBp float32 `json:"iosBp"`
} `json:"data"`
}
if err = d.payCenterClient.Do(c, req, &res); err != nil {
return
}
if res.Code != 0 {
err = errors.Wrap(ecode.Int(res.Code), d.payCenterWalletURL+"?"+string(bs))
log.Error("account pay url(%s) error(%v) %s", d.payCenterWalletURL+"?"+string(bs), res.Code, res.Msg)
return
}
wallet = &model.Wallet{
Mid: mid,
BcoinBalance: res.Data.AvailableBp,
CouponBalance: res.Data.CouponBalance,
DefaultBp: res.Data.DefaultBp,
IosBp: res.Data.IosBp,
}
return
}
func encode(v url.Values) string {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
ht := false
for k := range v {
if k == "token" {
ht = true
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
if ht { // 需要把token放在最后 支付中心的规则
keys = append(keys, "token")
}
for _, k := range keys {
vs := v[k]
prefix := k + "="
for _, v := range vs {
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(v)
}
}
return buf.String()
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestDao_PayCenterWallet(t *testing.T) {
Convey("normal", t, func() {
mid := int64(1)
w, e := testDao.PayCenterWallet(context.Background(), mid, "android")
So(e, ShouldBeNil)
t.Logf("%+v", w)
})
}

View File

@@ -0,0 +1,105 @@
package dao
import (
"context"
"go-common/app/interface/live/app-room/model"
"go-common/app/service/live/userext/api/liverpc/v0"
"go-common/library/ecode"
"go-common/library/log"
"strconv"
)
//GetUserConf 获取用户配置
func (d *Dao) GetUserConf(c context.Context, mid int64, targetId int64, keys []int64) (values model.ConfValues, err error) {
req := &v0.ConfGetReq{
Uid: mid,
TargetId: targetId,
Type: keys,
}
resp, err := d.UserExtAPI.V0Conf.Get(c, req)
if err != nil {
log.Error("call getUserConf sys error %v", err.Error())
return
}
if resp.Code != 0 {
log.Error("call getUserConf failed %d %v", resp.Code, resp.Msg)
err = ecode.ParamInvalid
return
}
o := resp.Data
values = make(map[int64]string, len(o))
for i, v := range o {
s, e := strconv.ParseInt(i, 10, 64)
if e != nil {
log.Error("call getUserConf string2int64 failed %v", e.Error())
err = e
return
}
values[s] = v
}
return
}
//AsyncSetUserConf 异步设置用户一个配置 "存在"
func (d *Dao) AsyncSetUserConf(c context.Context, mid int64, targetId int64, key int64) (err error) {
value := model.Set
vs := make(map[int64]string, 1)
vs[key] = value
err = d.giftCache.Save(func() {
d.SetMoreUserConf(context.Background(), mid, targetId, vs)
})
if err != nil {
err = d.SetMoreUserConf(c, mid, targetId, vs)
}
return
}
//SetUserConf 设置用户一个配置 "存在"
func (d *Dao) SetUserConf(c context.Context, mid int64, targetId int64, key int64) (err error) {
value := model.Set
vs := make(map[int64]string, 1)
vs[key] = value
err = d.SetMoreUserConf(c, mid, targetId, vs)
return
}
//DelUserConf 删除用户一个配置 "不存在"
func (d *Dao) DelUserConf(c context.Context, mid int64, targetId int64, key int64) (err error) {
value := model.Empty
vs := make(map[int64]string, 1)
vs[key] = value
err = d.SetMoreUserConf(c, mid, targetId, vs)
return
}
//SetMoreUserConf 设置用户多个配置
func (d *Dao) SetMoreUserConf(c context.Context, mid int64, targetId int64, values map[int64]string) (err error) {
varList := make([]*v0.ConfSetReq_Var, len(values))
ic := 0
for k, v := range values {
rv := &v0.ConfSetReq_Var{
Uid: mid,
TargetId: targetId,
Type: k,
Content: v,
}
varList[ic] = rv
ic++
}
req := &v0.ConfSetReq{
VarList: varList,
}
r, err := d.UserExtAPI.V0Conf.Set(c, req)
if err != nil {
log.Error("call setUserConf sys error %v", err.Error())
return
}
if r.Code != 0 {
log.Error("call setUserConf failed %d %v", r.Code, r.Msg)
err = ecode.ParamInvalid
return
}
return
}

View File

@@ -0,0 +1,48 @@
package dao
import (
"context"
. "github.com/smartystreets/goconvey/convey"
"go-common/app/interface/live/app-room/model"
"math/rand"
"testing"
"time"
)
func getTestRandUid() int64 {
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
return r.Int63n(10000000)
}
func TestDao_UserConf(t *testing.T) {
Convey("normal", t, func() {
Convey("conf", func() {
So(7, ShouldEqual, testDao.c.Gift.RechargeTip.SilverTipDays[0])
So(1, ShouldEqual, len(testDao.c.Gift.RechargeTip.SilverTipDays))
t.Logf("%v", testDao.c.Gift.RechargeTip.SilverTipDays)
})
Convey("set and get", func() {
uid := getTestRandUid()
err := testDao.SetUserConf(context.Background(), uid, model.GoldTarget, 1)
So(err, ShouldBeNil)
m, err := testDao.GetUserConf(context.Background(), uid, model.GoldTarget, []int64{1})
So(err, ShouldBeNil)
v, ok := m[1]
t.Logf("v: %v", v)
So(ok, ShouldBeTrue)
So(v, ShouldEqual, "1")
So(m.IsSet(1), ShouldBeTrue)
testDao.DelUserConf(context.Background(), uid, model.GoldTarget, 1)
m, err = testDao.GetUserConf(context.Background(), uid, model.GoldTarget, []int64{1})
So(err, ShouldBeNil)
v, ok = m[1]
t.Logf("v: %v", v)
So(ok, ShouldBeTrue)
So(v, ShouldEqual, "")
So(m.IsSet(1), ShouldBeFalse)
})
})
}