Create & Init Project...

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

View File

@@ -0,0 +1,67 @@
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",
"mc_limit_test.go",
"rpc_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/relation/model:go_default_library",
"//app/service/main/relation/rpc/client:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/bouk/monkey:go_default_library",
"//vendor/github.com/golang/mock/gomock:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"mc_limit.go",
"rpc.go",
],
importpath = "go-common/app/interface/main/videoup/dao/account",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/relation/model:go_default_library",
"//app/service/main/relation/rpc/client: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",
],
)
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,122 @@
package account
import (
"context"
"net/url"
"strconv"
"time"
"go-common/app/interface/main/videoup/conf"
accapi "go-common/app/service/main/account/api"
relation "go-common/app/service/main/relation/rpc/client"
"go-common/library/cache/memcache"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
_addFollowingURI = "/x/internal/relation/following/add"
)
// Dao dao is account dao.
type Dao struct {
// config
c *conf.Config
// rpc
rela *relation.Service
acc accapi.AccountClient
// memcache
mc *memcache.Pool
mcSubExp, mcLimitAddBasicExp int32
client *bm.Client
addFollowingURL string
}
// New new a account dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// rpc
rela: relation.New(c.RelationRPC),
// access memcache
mc: memcache.NewPool(c.Memcache.Account.Config),
mcSubExp: int32(time.Duration(c.Memcache.Account.SubmitExpire) / time.Second),
mcLimitAddBasicExp: int32(time.Duration(c.Limit.AddBasicExp) / time.Second),
client: bm.NewClient(c.HTTPClient.Write),
addFollowingURL: c.Host.APICo + _addFollowingURI,
}
var err error
if d.acc, err = accapi.NewClient(c.AccClient); err != nil {
panic(err)
}
return
}
// Close close resource.
func (d *Dao) Close() {
if d.mc != nil {
d.mc.Close()
}
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingMemcache(c); err != nil {
return
}
return
}
// IdentifyInfo 获取用户实名认证状态
func (d *Dao) IdentifyInfo(c context.Context, ip string, mid int64) (err error) {
var mf *accapi.Profile
if mf, err = d.Profile(c, mid, ip); err != nil {
log.Error("d.Profile mid(%d),ip(%s),error(%v)", mid, ip, err)
err = ecode.CreativeAccServiceErr
return
}
if mf.Identification == 1 {
return
}
//switch for FrontEnd return json format, return OldPhone, and newError
if err = d.switchIDInfoRet(mf.TelStatus); err != nil {
log.Error("switchIDInfoRet res(%v)", mf.TelStatus)
return
}
return
}
func (d *Dao) switchIDInfoRet(phoneRet int32) (err error) {
switch phoneRet {
case 0:
err = ecode.UserCheckNoPhone
case 1:
err = nil
case 2:
err = ecode.UserCheckInvalidPhone
}
return
}
// AddFollowing 添加关注
func (d *Dao) AddFollowing(c context.Context, mid, fid int64, src int, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("fid", strconv.FormatInt(fid, 10))
params.Set("src", strconv.Itoa(src))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.addFollowingURL, ip, params, &res); err != nil {
log.Error("d.client.Do uri(%s) mid(%d) fid(%d) res(%+v) error(%v)", d.addFollowingURL+"?"+params.Encode(), mid, fid, res, err)
return
}
log.Info("acc AddFollowing url(%s)", d.addFollowingURL+"?"+params.Encode())
if res.Code != 0 {
log.Error("acc AddFollowing (%+s)|(%+d)|(%+d)|(%+d)|(%s) (%+v)", d.addFollowingURL, mid, fid, src, ip, res)
err = ecode.CreativeAccServiceErr
return
}
return
}

View File

@@ -0,0 +1,66 @@
package account
import (
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.client.SetTransport(gock.DefaultTransport)
return r
}
func TestAddFollowing(t *testing.T) {
convey.Convey("AddFollowing", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
fid = int64(2089810)
src = 173
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.addFollowingURL).Reply(200).JSON(`{"code":0,"data":""}`)
err := d.AddFollowing(c, mid, fid, src, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,132 @@
package account
import (
"context"
"crypto/md5"
"encoding/binary"
"encoding/hex"
"strconv"
"time"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_addMidAndTitlePrefix = "add_midtitle_"
_addMidHalfMinPrefix = "add_midhafmin_"
)
func limitMidHafMin(mid int64) string {
return _addMidHalfMinPrefix + strconv.FormatInt(mid, 10)
}
func limitMidSameTitle(mid int64, title string) string {
ms := md5.Sum([]byte(title))
return _addMidAndTitlePrefix + strconv.FormatInt(mid, 10) + "_" + hex.EncodeToString(ms[:])
}
// HalfMin fn
func (d *Dao) HalfMin(c context.Context, mid int64) (exist bool, ts uint64, err error) {
var (
conn = d.mc.Get(c)
rp *memcache.Item
)
defer conn.Close()
key := limitMidHafMin(mid)
rp, err = conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
} else {
log.Error("conn.Get error(%v) | key(%s) mid(%d)", err, key, mid)
}
return
}
if err = conn.Scan(rp, &ts); err != nil {
log.Error("conn.Scan(%s) error(%v)", rp.Value, err)
return
}
log.Info("HalfMin key(%s) ts(%d)", key, ts)
if ts != 0 {
exist = true
}
return
}
// AddHalfMin fn
func (d *Dao) AddHalfMin(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := limitMidHafMin(mid)
ts := time.Now().Unix()
if err = conn.Set(&memcache.Item{Key: key, Object: ts, Flags: memcache.FlagJSON, Expiration: d.mcLimitAddBasicExp}); err != nil {
log.Error("memcache.set error(%v) | key(%s) mid(%d)", err, key, mid)
}
return
}
// DelHalfMin func
func (d *Dao) DelHalfMin(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(limitMidHafMin(mid)); err == memcache.ErrNotFound {
err = nil
}
return
}
// SubmitCache get user submit cache.
func (d *Dao) SubmitCache(c context.Context, mid int64, title string) (exist int8, err error) {
var (
conn = d.mc.Get(c)
rp *memcache.Item
)
defer conn.Close()
key := limitMidSameTitle(mid, title)
rp, err = conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
} else {
log.Error("conn.Get error(%v) | key(%s) mid(%d) title(%s)", err, key, mid, title)
}
}
if rp != nil {
exist = int8(binary.BigEndian.Uint64(rp.Value))
}
return
}
// AddSubmitCache add submit cache into mc.
func (d *Dao) AddSubmitCache(c context.Context, mid int64, title string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := limitMidSameTitle(mid, title)
bs := make([]byte, 8)
binary.BigEndian.PutUint64(bs, 1)
if err = conn.Set(&memcache.Item{Key: key, Object: bs, Flags: memcache.FlagJSON, Expiration: d.mcSubExp}); err != nil {
log.Error("memcache.set error(%v) | key(%s) mid(%d) title(%s)", err, key, mid, title)
}
return
}
// DelSubmitCache func
func (d *Dao) DelSubmitCache(c context.Context, mid int64, title string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(limitMidSameTitle(mid, title)); err == memcache.ErrNotFound {
err = nil
}
return
}
func (d *Dao) pingMemcache(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
log.Error("mc.ping.Store error(%v)", err)
return
}
return
}

View File

@@ -0,0 +1,179 @@
package account
import (
"context"
"go-common/library/cache/memcache"
"reflect"
"testing"
"github.com/bouk/monkey"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountlimitMidHafMin(t *testing.T) {
convey.Convey("limitMidHafMin", t, func(ctx convey.C) {
var (
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := limitMidHafMin(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountlimitMidSameTitle(t *testing.T) {
convey.Convey("limitMidSameTitle", t, func(ctx convey.C) {
var (
mid = int64(2089809)
title = "iamtitle"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := limitMidSameTitle(mid, title)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountHalfMin(t *testing.T) {
convey.Convey("HalfMin", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
exist, ts, err := d.HalfMin(c, mid)
ctx.Convey("Then err should be nil.exist,ts should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ts, convey.ShouldNotBeNil)
ctx.So(exist, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountAddHalfMin(t *testing.T) {
convey.Convey("AddHalfMin", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
err := d.AddHalfMin(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountDelHalfMin(t *testing.T) {
convey.Convey("DelHalfMin", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
err := d.DelHalfMin(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestAccountSubmitCache(t *testing.T) {
convey.Convey("SubmitCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
title = "iamtitle"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
exist, err := d.SubmitCache(c, mid, title)
ctx.Convey("Then err should be nil.exist should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(exist, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountAddSubmitCache(t *testing.T) {
convey.Convey("AddSubmitCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
title = "iamtitle"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
err := d.AddSubmitCache(c, mid, title)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestAccountDelSubmitCache(t *testing.T) {
convey.Convey("DelSubmitCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
title = "iamtitle"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
err := d.DelSubmitCache(c, mid, title)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestAccountpingMemcache(t *testing.T) {
convey.Convey("pingMemcache", t, func(ctx convey.C) {
var (
c = context.Background()
err error
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
connGuard := monkey.PatchInstanceMethod(reflect.TypeOf(d.mc), "Get", func(_ *memcache.Pool, _ context.Context) memcache.Conn {
return memcache.MockWith(memcache.ErrNotFound)
})
defer connGuard.Unpatch()
err = d.pingMemcache(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,82 @@
package account
import (
"context"
accapi "go-common/app/service/main/account/api"
relaMdl "go-common/app/service/main/relation/model"
"go-common/library/ecode"
"go-common/library/log"
)
// Profile get profile from rpc
func (d *Dao) Profile(c context.Context, mid int64, ip string) (p *accapi.Profile, err error) {
arg := &accapi.MidReq{
Mid: mid,
}
var rpcRes *accapi.ProfileReply
if rpcRes, err = d.acc.Profile3(c, arg); err != nil {
log.Error("d.acc.Profile3 error(%v) | mid(%d) ip(%s) arg(%v)", err, mid, ip, arg)
err = ecode.CreativeAccServiceErr
}
if rpcRes != nil {
p = rpcRes.Profile
}
return
}
// Cards get cards from rpc
func (d *Dao) Cards(c context.Context, mids []int64, ip string) (cards map[int64]*accapi.Card, err error) {
var res *accapi.CardsReply
if len(mids) == 0 {
return
}
arg := &accapi.MidsReq{
Mids: mids,
}
if res, err = d.acc.Cards3(c, arg); err != nil {
log.Error("d.acc.Cards3 error(%v) | mids(%v) ip(%s) arg(%v)", err, mids, ip, arg)
err = ecode.CreativeAccServiceErr
}
if res != nil {
cards = res.Cards
}
return
}
// Infos get infos from rpc
func (d *Dao) Infos(c context.Context, mids []int64, ip string) (infos map[int64]*accapi.Info, err error) {
var res *accapi.InfosReply
arg := &accapi.MidsReq{
Mids: mids,
}
infos = make(map[int64]*accapi.Info)
if res, err = d.acc.Infos3(c, arg); err != nil {
log.Error("d.acc.Infos3 error(%v) | mids(%v) ip(%s) arg(%v)", err, mids, ip, arg)
err = ecode.CreativeAccServiceErr
}
if res != nil {
infos = res.Infos
}
return
}
// Relations get all relation state.
func (d *Dao) Relations(c context.Context, mid int64, fids []int64, ip string) (res map[int64]int, err error) {
var rls map[int64]*relaMdl.Following
if rls, err = d.rela.Relations(c, &relaMdl.ArgRelations{Mid: mid, Fids: fids, RealIP: ip}); err != nil {
log.Error("d.rela.Relations mid(%d)|ip(%s)|error(%v)", mid, ip, err)
err = ecode.CreativeAccServiceErr
return
}
if len(rls) == 0 {
log.Info("d.rela.Relations mid(%d)|ip(%s)", mid, ip)
return
}
res = make(map[int64]int, len(rls))
for _, v := range rls {
res[v.Mid] = int(v.Attribute)
}
log.Info("d.rela.Relations mid(%d)|res(%+v)|rls(%+v)|ip(%s)", mid, res, rls, ip)
return
}

View File

@@ -0,0 +1,107 @@
package account
import (
"context"
"reflect"
"testing"
relaMdl "go-common/app/service/main/relation/model"
"go-common/app/service/main/relation/rpc/client"
"github.com/bouk/monkey"
. "github.com/smartystreets/goconvey/convey"
accapi "go-common/app/service/main/account/api"
"go-common/library/ecode"
"github.com/golang/mock/gomock"
)
func WithMock(t *testing.T, f func(mock *gomock.Controller)) func() {
return func() {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
f(mockCtrl)
}
}
func TestAccountProfile(t *testing.T) {
Convey("1", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
p *accapi.Profile
)
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidReq{
Mid: mid,
}
mock.EXPECT().Profile3(gomock.Any(), mockReq).Return(nil, ecode.CreativeAccServiceErr)
p, err = d.Profile(c, mid, ip)
So(err, ShouldNotBeNil)
So(p, ShouldBeNil)
}))
}
func TestDao_Cards(t *testing.T) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
)
Convey("Cards", t, WithMock(t, func(mockCtrl *gomock.Controller) {
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidsReq{
Mids: []int64{mid},
}
res := &accapi.CardsReply{}
mock.EXPECT().Cards3(gomock.Any(), mockReq).Return(res, nil)
_, err = d.Cards(c, []int64{mid}, ip)
So(err, ShouldBeNil)
}))
}
func TestDao_Infos(t *testing.T) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
)
Convey("Infos", t, WithMock(t, func(mockCtrl *gomock.Controller) {
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidsReq{
Mids: []int64{mid},
}
res := &accapi.InfosReply{}
mock.EXPECT().Infos3(gomock.Any(), mockReq).Return(res, nil)
_, err = d.Infos(c, []int64{mid}, ip)
So(err, ShouldBeNil)
}))
}
func TestDao_Relations(t *testing.T) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
)
Convey("Relations", t, func(ctx C) {
mock := monkey.PatchInstanceMethod(reflect.TypeOf(d.rela), "Relations",
func(_ *relation.Service, _ context.Context, _ *relaMdl.ArgRelations) (res map[int64]*relaMdl.Following, err error) {
res = make(map[int64]*relaMdl.Following)
res[2089809] = &relaMdl.Following{}
return res, nil
})
defer mock.Unpatch()
_, err = d.Relations(c, mid, []int64{mid}, ip)
So(err, ShouldBeNil)
})
}

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 = [
"api_test.go",
"dao_test.go",
"redis_test.go",
"type_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive:go_default_library",
"//app/service/main/up/api/v1:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/golang/mock/gomock:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
"redis.go",
"type.go",
],
importpath = "go-common/app/interface/main/videoup/dao/archive",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/creative/dao/tool:go_default_library",
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive:go_default_library",
"//app/interface/main/videoup/model/porder:go_default_library",
"//app/service/main/up/api/v1: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/sync/errgroup: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,365 @@
package archive
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"go-common/app/interface/main/creative/dao/tool"
"go-common/app/interface/main/videoup/conf"
"go-common/app/interface/main/videoup/model/archive"
pordermdl "go-common/app/interface/main/videoup/model/porder"
upapi "go-common/app/service/main/up/api/v1"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/sync/errgroup"
"net/http"
"net/url"
"strconv"
"sync"
"time"
)
const (
_viewURL = "/videoup/view"
_addURL = "/videoup/add"
_editURL = "/videoup/edit"
_tagUpURL = "/videoup/tag/up"
_applyStaffs = "/videoup/staff/archive/applys"
// StaffWhiteGroupID const
StaffWhiteGroupID = int64(24)
)
// View get archive and videos.
func (d *Dao) View(c context.Context, aid int64, ip string) (a *archive.Archive, vs []*archive.Video, err error) {
params := url.Values{}
params.Set("aid", strconv.FormatInt(aid, 10))
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
Archive *archive.Archive `json:"archive"`
Videos []*archive.Video `json:"videos"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.viewURI, ip, params, &res); err != nil {
log.Error("videoup view archive error(%v) | viewUri(%s) aid(%d) ip(%s) params(%v)", err, d.viewURI+"?"+params.Encode(), aid, ip, params)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
err = ecode.Error(ecode.Int(res.Code), res.Message)
log.Error("videoup view archive res code nq zero, res.Code(%d) | viewUri(%s) aid(%d) ip(%s) params(%v) res(%v)", res.Code, d.viewURI+"?"+params.Encode(), aid, ip, params, res)
return
}
a = res.Data.Archive
vs = res.Data.Videos
return
}
// ApplyStaffs fn
func (d *Dao) ApplyStaffs(c context.Context, aid int64, ip string) (staffs []*archive.Staff, err error) {
params := url.Values{}
params.Set("aid", strconv.FormatInt(aid, 10))
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data []*archive.StaffView `json:"data"`
}
if err = d.httpR.Get(c, d.applyStaffs, ip, params, &res); err != nil {
log.Error("videoup view archive error(%v) | viewUri(%s) aid(%d) ip(%s) params(%v)", err, d.viewURI+"?"+params.Encode(), aid, ip, params)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
log.Error("videoup view archive res code nq zero, res.Code(%d) | viewUri(%s) aid(%d) ip(%s) params(%v) res(%v)", res.Code, d.viewURI+"?"+params.Encode(), aid, ip, params, res)
err = ecode.CreativeArchiveAPIErr
return
}
for _, v := range res.Data {
staff := &archive.Staff{
Mid: v.ApMID,
Title: v.ApTitle,
}
staffs = append(staffs, staff)
}
return
}
// Add add archive and videos.
func (d *Dao) Add(c context.Context, ap *archive.ArcParam, ip string) (aid int64, err error) {
params := url.Values{}
params.Set("appkey", d.c.App.Key)
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
mh := md5.Sum([]byte(params.Encode() + d.c.App.Secret))
params.Set("sign", hex.EncodeToString(mh[:]))
var (
uri = d.addURI + "?" + params.Encode()
)
bs, err := json.Marshal(ap)
if err != nil {
log.Error("json.Marshal error(%v) | ap(%v) ap.Mid(%d) ap.videos(%v)", err, ap, ap.Mid, ap.Videos)
return
}
req, err := http.NewRequest("POST", uri, bytes.NewReader(bs))
if err != nil {
log.Error("http.NewRequest error(%v) | uri(%s) ap.Mid(%d)", err, uri, ap.Mid)
return
}
req.Header.Set("X-BACKEND-BILI-REAL-IP", ip)
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data struct {
Aid int64 `json:"aid"`
} `json:"data"`
}
if err = d.httpW.Do(c, req, &res); err != nil {
log.Error("d.Add error(%v) | uri(%s) ap(%+v)", err, uri, ap)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
err = ecode.Error(ecode.Int(res.Code), res.Message)
log.Error("d.Add nq zero (%v)|(%v)|(%v)|(%v)|uri(%s),ap(%+v)", res.Code, res.Message, res.Data, err, uri, ap)
return
}
log.Info("d.Add (%s)|res.Data.Aid(%d) ip(%s) ", string(bs), res.Data.Aid, ip)
aid = res.Data.Aid
return
}
// Edit edit archive and videos.
func (d *Dao) Edit(c context.Context, ap *archive.ArcParam, ip string) (err error) {
params := url.Values{}
params.Set("appkey", conf.Conf.App.Key)
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
mh := md5.Sum([]byte(params.Encode() + d.c.App.Secret))
params.Set("sign", hex.EncodeToString(mh[:]))
// uri
var (
uri = d.editURI + "?" + params.Encode()
)
// new request
bs, err := json.Marshal(ap)
if err != nil {
log.Error("json.Marshal ap error (%v) | ap(%v)", err, ap)
return
}
req, err := http.NewRequest("POST", uri, bytes.NewReader(bs))
if err != nil {
log.Error("http.NewRequest error(%v) | uri(%s) ap(%v)", err, uri, ap)
return
}
req.Header.Set("X-BACKEND-BILI-REAL-IP", ip)
var res struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err = d.httpW.Do(c, req, &res); err != nil {
log.Error("d.Edit error(%v) | uri(%s) ap(%+v)", err, uri, ap)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
err = ecode.Error(ecode.Int(res.Code), res.Message)
log.Error("d.Add nq zero (%v)|(%v)|(%v)|uri(%s),ap(%+v)", res.Code, res.Message, err, uri, ap)
return
}
log.Info("d.Edit(%s) | ip(%s)", string(bs), ip)
return
}
// DescFormat fn
func (d *Dao) DescFormat(c context.Context) (descFormats map[int]*archive.DescFormat, err error) {
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data []*archive.DescFormat `json:"data"`
}
descFormats = make(map[int]*archive.DescFormat)
if err = d.httpR.Get(c, d.descFormatURI, "", nil, &res); err != nil {
log.Error("videoup descFormat error(%v) | descFormatURI(%s) err(%v)", err, d.descFormatURI, err)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
err = ecode.Error(ecode.Int(res.Code), res.Message)
log.Error("videoup descFormat res.Code(%d) | descFormatURI(%s) res(%v) err(%v)", res.Code, d.descFormatURI, res, err)
return
}
for _, v := range res.Data {
descFormats[v.ID] = v
}
return
}
// TagUp fn
func (d *Dao) TagUp(c context.Context, aid int64, tag, ip string) (err error) {
params := url.Values{}
params.Set("aid", strconv.Itoa(int(aid)))
params.Set("tag", tag)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.tagUpURI, ip, params, &res); err != nil {
log.Error("Post(%s,%s,%s) err(%v)", d.tagUpURI, ip, params.Encode(), err)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
log.Error("Code(%s,%s,%s) err(%v), code(%d)", d.tagUpURI, ip, params.Encode(), err, res.Code)
err = ecode.CreativeArchiveAPIErr
return
}
return
}
// PorderCfgList fn
func (d *Dao) PorderCfgList(c context.Context) (cfgs map[int64]*pordermdl.Config, err error) {
cfgs = make(map[int64]*pordermdl.Config)
var res struct {
Code int `json:"code"`
Data []*pordermdl.Config `json:"data"`
}
if err = d.httpR.Get(c, d.porderConfigURL, "", nil, &res); err != nil {
log.Error("archive.porderConfigURL url(%s) error(%v)", d.porderConfigURL, err)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
log.Error("archive.porderConfigURL url(%s) res(%v)", d.porderConfigURL, res)
err = ecode.CreativeArchiveAPIErr
return
}
for _, cfg := range res.Data {
cfgs[cfg.ID] = cfg
}
return
}
// GameList fn
func (d *Dao) GameList(c context.Context) (gameMap map[int64]*pordermdl.Game, err error) {
gameMap = make(map[int64]*pordermdl.Game)
params := url.Values{}
params.Set("appkey", conf.Conf.Game.App.Key)
params.Set("appsecret", conf.Conf.Game.App.Secret)
params.Set("ts", strconv.FormatInt(time.Now().UnixNano()/1000000, 10))
var res struct {
Code int `json:"code"`
Data []*pordermdl.Game `json:"data"`
}
var (
query, _ = tool.Sign(params)
url string
)
url = d.gameListURL + "?" + query
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Error("http.NewRequest(%s) error(%v), ", url, err)
err = ecode.CreativeGameOpenAPIErr
return
}
if err = d.httpR.Do(c, req, &res); err != nil {
log.Error("d.httpR.Do(%s) error(%v);", url, err)
err = ecode.CreativeGameOpenAPIErr
return
}
log.Info("GameList url(%+v)|gameLen(%+v)", url, len(res.Data))
if res.Code != 0 {
log.Error("GameList api url(%s) res(%v);, code(%d)", url, res, res.Code)
err = ecode.CreativeGameOpenAPIErr
return
}
for _, data := range res.Data {
gameMap[data.GameBaseID] = data
}
return
}
//StaffUps 联合投稿白名单
func (d *Dao) StaffUps(c context.Context) (ups map[int64]int64, err error) {
return d.UpSpecial(c, StaffWhiteGroupID)
}
// StaffTypeConfig 获取联合投稿分区配置
func (d *Dao) StaffTypeConfig(c context.Context) (isGary bool, typeConf map[int16]*archive.StaffTypeConf, err error) {
typeConf = make(map[int16]*archive.StaffTypeConf)
params := url.Values{}
var res struct {
Code int `json:"code"`
Data struct {
IsGary bool `json:"is_gary"`
TypeList []*archive.StaffTypeConf `json:"typelist"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.staffConfigURI, "", params, &res); err != nil {
log.Error("StaffTypeConfig error(%v) | staffConfigURI(%s)", err, d.staffConfigURI)
err = ecode.CreativeArchiveAPIErr
return
}
log.Info("StaffTypeConfig url(%+v)|res(%+v)", d.staffConfigURI, res)
if res.Code != 0 || res.Data.TypeList == nil {
log.Error("StaffTypeConfig api url(%s) res(%+v);, code(%d)", d.staffConfigURI, res, res.Code)
err = ecode.CreativeArchiveAPIErr
return
}
isGary = res.Data.IsGary
for _, v := range res.Data.TypeList {
typeConf[v.TypeID] = v
}
return
}
// UpSpecial 获取UP主的特殊用户组
func (d *Dao) UpSpecial(c context.Context, gpid int64) (ups map[int64]int64, err error) {
var (
res *upapi.UpGroupMidsReply
page int
g errgroup.Group
l sync.RWMutex
)
if res, err = d.UpClient.UpGroupMids(c, &upapi.UpGroupMidsReq{
GroupID: gpid,
Pn: 1,
Ps: 1,
}); err != nil {
log.Error("UpSpecial d.UpSpecial gpid(%d)|error(%v)", gpid, err)
return
}
log.Warn("UpSpecial get total: gpid(%d)|total(%d)", gpid, res.Total)
if res.Total <= 0 {
return
}
ups = make(map[int64]int64, res.Total)
ps := int(10000)
pageNum := res.Total / ps
if res.Total%ps != 0 {
pageNum++
}
for page = 1; page <= pageNum; page++ {
tmpPage := page
g.Go(func() (err error) {
resgg, err := d.UpClient.UpGroupMids(c, &upapi.UpGroupMidsReq{
GroupID: gpid,
Pn: tmpPage,
Ps: ps,
})
if err != nil {
log.Error("d.UpGroupMids gg (%d,%d,%d) error(%v) ", gpid, tmpPage, ps, err)
err = nil
return
}
for _, mid := range resgg.Mids {
l.Lock()
ups[mid] = mid
l.Unlock()
}
return
})
}
g.Wait()
log.Warn("UpSpecial get result: gpid,total,midslen,upslens (%d)|(%d)|(%d)", gpid, res.Total, len(ups))
return
}

View File

@@ -0,0 +1,216 @@
package archive
import (
"context"
"go-common/app/interface/main/videoup/model/archive"
upapi "go-common/app/service/main/up/api/v1"
"go-common/library/ecode"
"testing"
"github.com/golang/mock/gomock"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestPing(t *testing.T) {
Convey("Ping", t, func(ctx C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx C) {
err := d.Ping(c)
ctx.Convey("Then err should be nil.a,vs should not be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
})
})
})
}
func TestArchiveView(t *testing.T) {
Convey("View", t, func(ctx C) {
var (
c = context.Background()
aid = int64(10110826)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("GET", d.viewURI).Reply(200).JSON(`{"code":20001,"data":""}`)
a, vs, err := d.View(c, aid, ip)
ctx.Convey("Then err should be nil.a,vs should not be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
ctx.So(vs, ShouldBeNil)
ctx.So(a, ShouldBeNil)
})
})
})
}
func TestArchiveAdd(t *testing.T) {
Convey("Add", t, func(ctx C) {
var (
c = context.Background()
ap = &archive.ArcParam{}
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("Post", d.addURI).Reply(200).JSON(`{"code":20001,"data":""}`)
aid, err := d.Add(c, ap, ip)
ctx.Convey("Then err should be nil.aid should not be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
ctx.So(aid, ShouldNotBeNil)
})
})
})
}
func TestArchiveEdit(t *testing.T) {
Convey("Edit", t, func(ctx C) {
var (
c = context.Background()
ap = &archive.ArcParam{}
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("Post", d.editURI).Reply(200).JSON(`{"code":20001,"data":""}`)
err := d.Edit(c, ap, ip)
ctx.Convey("Then err should be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
})
})
})
}
func TestArchiveDescFormat(t *testing.T) {
Convey("DescFormat", t, func(ctx C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx C) {
descFormats, err := d.DescFormat(c)
ctx.Convey("Then err should be nil.descFormats should not be nil.", func(ctx C) {
ctx.So(err, ShouldBeNil)
ctx.So(descFormats, ShouldNotBeNil)
})
})
})
}
func TestArchiveTagUp(t *testing.T) {
Convey("TagUp", t, func(ctx C) {
var (
c = context.Background()
aid = int64(10110826)
tag = "iamatag"
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx C) {
err := d.TagUp(c, aid, tag, ip)
ctx.Convey("Then err should be nil.", func(ctx C) {
ctx.So(err, ShouldBeNil)
})
})
})
}
func TestArchivePorderCfgList(t *testing.T) {
Convey("PorderCfgList", t, func(ctx C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx C) {
cfgs, err := d.PorderCfgList(c)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx C) {
ctx.So(err, ShouldBeNil)
ctx.So(cfgs, ShouldNotBeNil)
})
})
})
}
func TestArchiveGameList(t *testing.T) {
Convey("GameList", t, func(ctx C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("GET", d.viewURI).Reply(200).JSON(`{"code":20051,"data":""}`)
gameMap, err := d.GameList(c)
ctx.Convey("Then err should be nil.gameMap should not be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
ctx.So(gameMap, ShouldNotBeNil)
})
})
})
}
func TestUpSpecial(t *testing.T) {
var (
c = context.Background()
res map[int64]int64
err error
)
Convey("UpSpecial", t, func(ctx C) {
res, err = d.UpSpecial(c, 17)
So(res, ShouldNotBeNil)
So(err, ShouldBeNil)
})
}
func TestDao_ApplyStaffs(t *testing.T) {
var (
c = context.Background()
aid = int64(10110826)
ip = "127.0.0.1"
err error
)
Convey("ApplyStaffs", t, func(ctx C) {
httpMock("GET", d.applyStaffs).Reply(200).JSON(`{"code":0}`)
_, err = d.ApplyStaffs(c, aid, ip)
So(err, ShouldBeNil)
})
}
func WithMock(t *testing.T, f func(mock *gomock.Controller)) func() {
return func() {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
f(mockCtrl)
}
}
func TestDao_StaffUps(t *testing.T) {
Convey("StaffUps", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
err error
ups map[int64]int64
)
mock := upapi.NewMockUpClient(mockCtrl)
d.UpClient = mock
mockReq := &upapi.UpGroupMidsReq{
GroupID: 1,
Pn: 1,
Ps: 1,
}
mock.EXPECT().UpGroupMids(gomock.Any(), mockReq).Return(nil, ecode.CreativeAccServiceErr)
ups, err = d.StaffUps(c)
So(err, ShouldNotBeNil)
So(ups, ShouldBeNil)
}))
}
func TestDao_StaffTypeConfig(t *testing.T) {
var (
c = context.Background()
err error
)
Convey("StaffTypeConfig", t, func(ctx C) {
httpMock("GET", d.staffConfigURI).Reply(200).JSON(`{"code":0,"data":{"is_gray":true,"typelist":[{"typeid":22,"max_staff":6}]}}`)
_, _, err = d.StaffTypeConfig(c)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,87 @@
package archive
import (
"context"
"go-common/app/interface/main/videoup/conf"
upapi "go-common/app/service/main/up/api/v1"
"go-common/library/cache/redis"
bm "go-common/library/net/http/blademaster"
"time"
)
// Dao is archive dao.
type Dao struct {
c *conf.Config
// http
httpR *bm.Client
httpW *bm.Client
UpClient upapi.UpClient
// redis
redis *redis.Pool
redisExpire int32
// uri
viewURI string
addURI string
editURI string
typesURI string
descFormatURI string
tagUpURI string
staffConfigURI string
applyStaffs string
// ad check
porderConfigURL string
gameListURL string
}
const (
_descFormatURL = "/videoup/desc/format"
_porderConfig = "/videoup/porder/config/list"
_gameList = "/game/list"
_staffConfURI = "/x/internal/creative/staff/config"
)
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
//filename redis
redis: redis.NewPool(c.Redis.Videoup.Config),
redisExpire: int32(time.Duration(c.Redis.Videoup.Expire) / time.Second),
// http client
httpR: bm.NewClient(c.HTTPClient.Read),
httpW: bm.NewClient(c.HTTPClient.Write),
// uri
viewURI: c.Host.Archive + _viewURL,
addURI: c.Host.Archive + _addURL,
editURI: c.Host.Archive + _editURL,
typesURI: c.Host.Archive + _typesURL,
descFormatURI: c.Host.Archive + _descFormatURL,
tagUpURI: c.Host.Archive + _tagUpURL,
staffConfigURI: c.Host.APICo + _staffConfURI,
applyStaffs: c.Host.Archive + _applyStaffs,
// ad
porderConfigURL: c.Host.Archive + _porderConfig,
gameListURL: c.Game.OpenHost + _gameList,
}
var err error
if d.UpClient, err = upapi.NewClient(c.UpClient); err != nil {
panic(err)
}
return d
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingRedis(c); err != nil {
return
}
return
}
// Close close resource.
func (d *Dao) Close() {
if d.redis != nil {
d.redis.Close()
}
}

View File

@@ -0,0 +1,45 @@
package archive
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.httpR.SetTransport(gock.DefaultTransport)
return r
}

View File

@@ -0,0 +1,73 @@
package archive
import (
"context"
"strconv"
"time"
"go-common/app/interface/main/videoup/model/archive"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_upFavTpsPrefix = "up_fav_tps_"
)
func keyUpFavTpsPrefix(mid int64) string {
return _upFavTpsPrefix + strconv.FormatInt(mid, 10)
}
// FilenameExpires get filename expire time.
func (d *Dao) FilenameExpires(c context.Context, vs []*archive.VideoParam) (ves []*archive.VideoExpire, err error) {
var conn = d.redis.Get(c)
defer conn.Close()
for _, v := range vs {
conn.Send("GET", v.Filename)
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v) | vs(%#v)", err, vs)
return
}
for _, v := range vs {
var exp int64
if exp, err = redis.Int64(conn.Receive()); err != nil && err != redis.ErrNil {
log.Error("conn.Receive error(%+v) | filename(%s)", err, v.Filename)
return
}
err = nil // NOTE: maybe err==redis.ErrNil
ves = append(ves, &archive.VideoExpire{
Filename: v.Filename,
Expire: exp,
})
}
return
}
// FreshFavTypes fn
func (d *Dao) FreshFavTypes(c context.Context, mid int64, tp int) (err error) {
var (
conn = d.redis.Get(c)
score = time.Now().Unix()
)
defer conn.Close()
if err = conn.Send("ZADD", keyUpFavTpsPrefix(mid), score, strconv.Itoa(tp)); err != nil {
log.Error("conn.Send(ZADD, %s, %d) error(%v)", _upFavTpsPrefix, tp, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
}
return
}
func (d *Dao) pingRedis(c context.Context) (err error) {
conn := d.redis.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}

View File

@@ -0,0 +1,69 @@
package archive
import (
"context"
"go-common/app/interface/main/videoup/model/archive"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestArchivekeyUpFavTpsPrefix(t *testing.T) {
convey.Convey("keyUpFavTpsPrefix", t, func(ctx convey.C) {
var (
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyUpFavTpsPrefix(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestArchiveFilenameExpires(t *testing.T) {
convey.Convey("FilenameExpires", t, func(ctx convey.C) {
var (
c = context.Background()
vs = []*archive.VideoParam{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ves, err := d.FilenameExpires(c, vs)
ctx.Convey("Then err should be nil.ves should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(ves, convey.ShouldBeNil)
})
})
})
}
func TestArchiveFreshFavTypes(t *testing.T) {
convey.Convey("FreshFavTypes", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
tp = int(162)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.FreshFavTypes(c, mid, tp)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestArchivepingRedis(t *testing.T) {
convey.Convey("pingRedis", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.pingRedis(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,39 @@
package archive
import (
"context"
"go-common/app/interface/main/videoup/model/archive"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_typesURL = "/videoup/types"
)
// TypeMapping is second types opposite first types.
func (d *Dao) TypeMapping(c context.Context) (rmap map[int16]*archive.Type, err error) {
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[int16]*archive.Type `json:"data"`
}
if err = d.httpR.Get(c, d.typesURI, "", nil, &res); err != nil {
log.Error("videoup view archive error(%v) | typesURI(%s)", err, d.typesURI)
err = ecode.CreativeArchiveAPIErr
return
}
if res.Code != 0 {
err = ecode.CreativeArchiveAPIErr
log.Error("get archive type failed res.Code(%d) | typesURI(%s) res(%v)", res.Code, d.typesURI, res)
return
}
rmap = make(map[int16]*archive.Type, len(res.Data))
for _, v := range res.Data {
if v.PID != 0 {
rmap[v.ID] = v
}
}
return
}

View File

@@ -0,0 +1,28 @@
package archive
import (
"context"
"testing"
"gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestArchiveTypeMapping(t *testing.T) {
convey.Convey("TypeMapping", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.typesURI).Reply(200).JSON(`{"code":20001}`)
rmap, err := d.TypeMapping(c)
ctx.Convey("Then err should be nil.rmap should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(rmap, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,45 @@
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"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/videoup/dao/bfs",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//library/ecode:go_default_library",
"//library/log: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,98 @@
package bfs
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"go-common/app/interface/main/videoup/conf"
"go-common/library/ecode"
"go-common/library/log"
"hash"
"io"
"net/http"
"strconv"
"time"
)
const (
_bucket = "archive"
_url = "http://bfs.bilibili.co/bfs/archive/"
_template = "%s\n%s\n\n%d\n"
_method = "PUT"
_key = "8d4e593ba7555502"
_secret = "0bdbd4c7caeeddf587c3c4daec0475"
)
// Dao is bfs dao.
type Dao struct {
c *conf.Config
client *http.Client
}
// New new a bfs dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: &http.Client{
Timeout: time.Duration(c.Bfs.Timeout),
},
}
return d
}
// Upload upload bfs.
func (d *Dao) Upload(c context.Context, fileType string, body io.Reader) (location string, err error) {
req, err := http.NewRequest(_method, _url, body)
if err != nil {
log.Error("http.NewRequest error (%v) | fileType(%s) body(%v)", err, fileType, body)
return
}
expire := time.Now().Unix()
authorization := authorize(_key, _secret, _method, _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
c, cancel := context.WithTimeout(c, time.Duration(d.c.Bfs.Timeout))
req = req.WithContext(c)
defer cancel()
resp, err := d.client.Do(req)
if err != nil {
log.Error("d.Client.Do error(%v) | _url(%s) req(%v)", err, _url, req)
err = ecode.BfsUploadServiceUnavailable
return
}
if resp.StatusCode != http.StatusOK {
log.Error("Upload http.StatusCode nq http.StatusOK (%d) | url(%s)", resp.StatusCode, _url)
err = ecode.BfsUploadStatusErr
return
}
header := resp.Header
code := header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
log.Error("strconv.Itoa err, code(%s) | url(%s)", code, _url)
err = ecode.BfsUploadCodeErr
return
}
location = header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}

View File

@@ -0,0 +1,54 @@
package bfs
import (
"bytes"
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"testing"
"github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func Test_Upload(t *testing.T) {
var (
c = context.TODO()
err error
loc string
body = []byte{}
)
convey.Convey("Upload", t, func(ctx convey.C) {
loc, err = d.Upload(c, "jpeg", bytes.NewReader(body))
ctx.Convey("Then err should be nil should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(loc, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,55 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"creative_test.go",
"dao_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"creative.go",
"dao.go",
],
importpath = "go-common/app/interface/main/videoup/dao/creative",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive: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,80 @@
package creative
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"go-common/app/interface/main/videoup/conf"
"go-common/app/interface/main/videoup/model/archive"
"go-common/library/log"
"net/http"
"net/url"
"strconv"
"time"
)
const (
_setWatermark = "/x/internal/creative/watermark/set"
_uploadMaterial = "/x/internal/creative/upload/material"
)
// SetWatermark fn
func (d *Dao) SetWatermark(c context.Context, mid int64, state, ty, pos int8, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("state", strconv.Itoa(int(state)))
params.Set("type", strconv.Itoa(int(ty)))
params.Set("position", strconv.Itoa(int(pos)))
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.setWatermarkURL, ip, params, &res); err != nil {
log.Error("d.httpW.Post(%s) error(%v)", d.setWatermarkURL+"?"+params.Encode(), err)
return
}
log.Info("SetWatermark url(%s) code(%d)", d.setWatermarkURL+"?"+params.Encode(), res.Code)
if res.Code != 0 {
log.Error("url(%s) code(%d)", d.setWatermarkURL+"?"+params.Encode(), res.Code)
}
return
}
// UploadMaterial fn
func (d *Dao) UploadMaterial(c context.Context, editors []*archive.Editor, aid, mid int64, ip string) (err error) {
params := url.Values{}
params.Set("appkey", conf.Conf.App.Key)
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("aid", strconv.FormatInt(aid, 10))
mh := md5.Sum([]byte(params.Encode() + d.c.App.Secret))
params.Set("sign", hex.EncodeToString(mh[:]))
var (
uri = d.uploadMaterialURL + "?" + params.Encode()
)
bs, err := json.Marshal(editors)
if err != nil {
log.Error("UploadMaterial json.Marshal error(%+v)|editor(%+v)", err, editors)
return
}
req, err := http.NewRequest("POST", uri, bytes.NewReader(bs))
if err != nil {
log.Error("UploadMaterial http.NewRequest error(%v) | uri(%s) bs(%+v)", err, uri, bs)
return
}
req.Header.Set("X-BACKEND-BILI-REAL-IP", ip)
var res struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err = d.httpW.Do(c, req, &res); err != nil {
log.Error("UploadMaterial do error(%v)|uri(%s)", err, uri)
return
}
log.Info("UploadMaterial url(%s) code(%d)", uri, res.Code)
if res.Code != 0 {
log.Error("url(%s) code(%d)", uri, res.Code)
}
return
}

View File

@@ -0,0 +1,51 @@
package creative
import (
"context"
"go-common/app/interface/main/videoup/model/archive"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestCreativeSetWatermark(t *testing.T) {
convey.Convey("SetWatermark", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
state = int8(1)
ty = int8(3)
pos = int8(1)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.setWatermarkURL).Reply(200).JSON(`{"code":0,"data":{"id":53,"mid":27515310,"uname":"1qs314567","state":2,"type":2,"position":4,"url":"http://i0.hdslb.com/bfs/article/578a61e7caf47b5deaa80940b2806f1d9ce53dde.png","md5":"79d02f08c2b7b0d2b30a6b6a4f61c97e","info":"{\"width\":325,\"height\":50}","ctime":1499764110,"mtime":1499828335},"message":"","ttl":1}`)
err := d.SetWatermark(c, mid, state, ty, pos, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestCreativeUploadMaterial(t *testing.T) {
convey.Convey("UploadMaterial", t, func(ctx convey.C) {
var (
c = context.Background()
editors = []*archive.Editor{}
aid = int64(10110826)
mid = int64(2089809)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.uploadMaterialURL).Reply(200).JSON(`{"code":0,"data":""}`)
err := d.UploadMaterial(c, editors, aid, mid, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,32 @@
package creative
import (
"context"
"go-common/app/interface/main/videoup/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao is elec dao.
type Dao struct {
c *conf.Config
httpW *bm.Client
setWatermarkURL string
uploadMaterialURL string
}
// New new a elec dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
httpW: bm.NewClient(c.HTTPClient.Write),
setWatermarkURL: c.Host.APICo + _setWatermark,
uploadMaterialURL: c.Host.APICo + _uploadMaterial,
}
return d
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
return
}

View File

@@ -0,0 +1,45 @@
package creative
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.httpW.SetTransport(gock.DefaultTransport)
return r
}

View File

@@ -0,0 +1,48 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/videoup/dao/dynamic",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf: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 = ["dao_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf: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,86 @@
package dynamic
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/videoup/conf"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
_userCheckURI = "/lottery_svr/v0/lottery_svr/user_check"
_lotteryBindURI = "/lottery_svr/v0/lottery_svr/bind"
)
// Dao define
type Dao struct {
c *conf.Config
client *bm.Client
LotteryBindURL string
UserCheckURL string
}
// New init dao
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Write),
LotteryBindURL: c.Host.Dynamic + _lotteryBindURI,
UserCheckURL: c.Host.Dynamic + _userCheckURI,
}
return
}
// LotteryBind fn
func (d *Dao) LotteryBind(c context.Context, lotteryID, aid, mid int64, ip string) (err error) {
params := url.Values{}
params.Set("lottery_id", strconv.FormatInt(lotteryID, 10))
params.Set("business_type", "8")
params.Set("business_id", strconv.FormatInt(aid, 10))
params.Set("sender_uid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.LotteryBindURL, ip, params, &res); err != nil {
log.Error("LotteryBind url(%s) response(%s) error(%v)", d.LotteryBindURL+"?"+params.Encode(), res, err)
err = ecode.CreativeLotteryAPIErr
return
}
log.Info("LotteryBind d.LotteryBindURL url(%s)", d.LotteryBindURL+"?"+params.Encode(), res.Code)
if res.Code != 0 {
log.Error("LotteryBind url(%s) res(%v)", d.LotteryBindURL, res)
err = ecode.CreativeLotteryAPIErr
return
}
return
}
// UserCheck fn
func (d *Dao) UserCheck(c context.Context, mid int64, ip string) (ret int, err error) {
params := url.Values{}
params.Set("sender_uid", strconv.FormatInt(mid, 10))
params.Set("business_type", "8")
var res struct {
Code int `json:"code"`
Data struct {
Result int `json:"result"`
} `json:"data"`
}
if err = d.client.Get(c, d.UserCheckURL, ip, params, &res); err != nil {
log.Error("UserCheck url(%s) response(%s) error(%v)", d.UserCheckURL+"?"+params.Encode(), res, err)
err = ecode.CreativeLotteryAPIErr
return
}
log.Info("UserCheck d.UserCheckURL url(%s)", d.UserCheckURL+"?"+params.Encode(), res.Code)
if res.Code != 0 {
log.Error("UserCheck url(%s) res(%v)", d.UserCheckURL, res)
err = ecode.CreativeLotteryAPIErr
return
}
ret = res.Data.Result
return
}

View File

@@ -0,0 +1,87 @@
package dynamic
import (
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.client.SetTransport(gock.DefaultTransport)
return r
}
func Test_LotteryBind(t *testing.T) {
convey.Convey("LotteryBind", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(10110826)
mid = int64(2089809)
lid = int64(111)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.LotteryBindURL).Reply(200).JSON(`{"code":0,"data":""}`)
err := d.LotteryBind(c, lid, aid, mid, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func Test_UserCheck(t *testing.T) {
convey.Convey("UserCheck", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
ret int
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.UserCheckURL).Reply(200).JSON(`{"code":0,"data":{"result":1}}`)
ret, err = d.UserCheck(c, mid, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ret, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"api_test.go",
"dao_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
],
importpath = "go-common/app/interface/main/videoup/dao/elec",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf: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,71 @@
package elec
import (
"context"
"net/url"
"strconv"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_showURL = "/internal/member/show"
_arcOpenURI = "/internal/archice/partin"
_arcCloseURI = "/internal/archice/exit"
)
// ArcShow return archive elec show, contains rank.
func (d *Dao) ArcShow(c context.Context, mid, aid int64, ip string) (show bool, err error) {
params := url.Values{}
params.Set("upmid", strconv.FormatInt(mid, 10))
params.Set("aid", strconv.FormatInt(aid, 10))
params.Set("nolist", "0")
var res struct {
Code int `json:"code"`
Data struct {
Show bool `json:"show"`
} `json:"data"`
}
if err = d.client.Get(c, d.showURI, ip, params, &res); err != nil {
log.Error("elec url(%s) error(%v)", d.showURI+"?"+params.Encode(), err)
err = ecode.CreativeElecErr
return
}
log.Info("ArcShow d.showURI url(%s)|res(%+v)", d.showURI+"?"+params.Encode(), res)
if res.Code != 0 {
log.Error("d.client.Get(%s) code(%d) error(%v)", d.showURI+"?"+params.Encode(), res.Code, err)
err = ecode.Int(res.Code)
return
}
show = res.Data.Show
return
}
// ArcUpdate arc open or close elec.
func (d *Dao) ArcUpdate(c context.Context, mid, aid int64, openElec int8, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("aid", strconv.FormatInt(aid, 10))
var url string
if openElec == 1 {
url = d.arcOpenURL
} else if openElec == 0 {
url = d.arcCloseURL
}
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, url, ip, params, &res); err != nil {
log.Error("d.client.Do uri(%s) aid(%d) mid(%d) orderID(%d) code(%d) error(%v)", url+"?"+params.Encode(), mid, aid, openElec, res.Code, err)
err = ecode.CreativeElecErr
return
}
log.Info("dealElec ArcUpdate url(%s)", url+"?"+params.Encode())
if res.Code != 0 {
log.Error("arc elec update state url(%s) res(%v); mid(%d), aid(%d), ip(%s), code(%d), error(%v)", url, res, mid, aid, ip, res.Code, err)
err = ecode.Int(res.Code)
return
}
return
}

View File

@@ -0,0 +1,52 @@
package elec
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestElecArcShow(t *testing.T) {
convey.Convey("ArcShow", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
aid = int64(10110826)
ip = "127.0.0.1"
err error
show bool
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.showURI).Reply(200).JSON(`{"code":20004,"data":""}`)
show, err = d.ArcShow(c, mid, aid, ip)
ctx.Convey("Then err should be nil.show should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(show, convey.ShouldNotBeNil)
})
})
})
}
func TestElecArcUpdate(t *testing.T) {
convey.Convey("ArcUpdate", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
aid = int64(10110826)
openElec = int8(1)
ip = "127.0.0.1"
err error
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.arcOpenURL).Reply(200).JSON(`{"code":20004,"data":""}`)
err = d.ArcUpdate(c, mid, aid, openElec, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,38 @@
package elec
import (
"context"
"go-common/app/interface/main/videoup/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao is elec dao.
type Dao struct {
c *conf.Config
// http
client *bm.Client
// uri
showURI string
arcOpenURL string
arcCloseURL string
}
// New new a elec dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// http client
client: bm.NewClient(c.HTTPClient.Write),
// uri
showURI: c.Host.Elec + _showURL,
arcOpenURL: c.Host.Elec + _arcOpenURI,
arcCloseURL: c.Host.Elec + _arcCloseURI,
}
return d
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
return
}

View File

@@ -0,0 +1,45 @@
package elec
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.client.SetTransport(gock.DefaultTransport)
return r
}

View File

@@ -0,0 +1,50 @@
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"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/videoup/dao/filter",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive: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,97 @@
package filter
import (
"context"
"net/url"
"go-common/app/interface/main/videoup/conf"
"go-common/app/interface/main/videoup/model/archive"
"go-common/library/ecode"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
)
const (
_postFilter = "/x/internal/filter/post"
_postMFilter = "/x/internal/filter/mpost"
)
// Dao define
type Dao struct {
c *conf.Config
client *httpx.Client
postFilterURI string
postMFilterURI string
}
// New init dao
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: httpx.NewClient(c.HTTPClient.FastRead),
postFilterURI: c.Host.APICo + _postFilter,
postMFilterURI: c.Host.APICo + _postMFilter,
}
return
}
// VideoFilter fn
func (d *Dao) VideoFilter(c context.Context, msg, ip string) (resData *archive.FilterData, hit []string, err error) {
params := url.Values{}
params.Set("area", "video_submit")
params.Set("msg", msg)
var res struct {
Code int `json:"code"`
Data *archive.FilterData `json:"data"`
Message string `json:"message"`
}
if err = d.client.Post(c, d.postFilterURI, ip, params, &res); err != nil {
log.Error("d.client.Post uri(%s) msg(%s) ip(%s)", d.postFilterURI+"?"+params.Encode(), msg, ip, err)
err = ecode.VideoupFilterServiceErr
return
}
log.Info("VideoupFilterService url(%s)", d.postFilterURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("d.client.Post uri(%s) msg(%s) ip(%s)", d.postFilterURI+"?"+params.Encode(), msg, ip, err)
err = ecode.VideoupFilterServiceErr
return
}
hit = res.Data.Hit
resData = res.Data
return
}
// VideoMultiFilter 批量过滤
func (d *Dao) VideoMultiFilter(c context.Context, msgs []string, ip string) (resDatas []*archive.FilterData, hit []string, err error) {
if len(msgs) == 0 {
return
}
params := url.Values{}
params.Set("area", "video_submit")
for _, v := range msgs {
params.Add("msg", v)
}
var res struct {
Code int `json:"code"`
Data []*archive.FilterData `json:"data"`
Message string `json:"message"`
}
if err = d.client.Post(c, d.postMFilterURI, ip, params, &res); err != nil {
log.Error("d.client.Post uri(%s) msg(%v) ip(%s)", d.postMFilterURI+"?"+params.Encode(), msgs, ip, err)
err = ecode.VideoupFilterServiceErr
return
}
log.Info("VideoupFilterService url(%s)", d.postMFilterURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("d.client.Post uri(%s) msg(%v) ip(%s)", d.postMFilterURI+"?"+params.Encode(), msgs, ip, err)
err = ecode.VideoupFilterServiceErr
return
}
resDatas = res.Data
for _, v := range resDatas {
if len(v.Hit) != 0 {
hit = append(hit, v.Hit...)
}
}
return
}

View File

@@ -0,0 +1,93 @@
package filter
import (
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"go-common/app/interface/main/videoup/model/archive"
"os"
"strings"
"testing"
. "github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.client.SetTransport(gock.DefaultTransport)
return r
}
func Test_VideoFilter(t *testing.T) {
Convey("VideoFilter", t, func(ctx C) {
var (
err error
c = context.Background()
ip = "127.0.0.1"
msg = "iamamsg"
resData *archive.FilterData
hit []string
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("Post", d.postFilterURI).Reply(200).JSON(`{"code":21064,"data":""}`)
resData, hit, err = d.VideoFilter(c, msg, ip)
ctx.Convey("Then err should be nil.", func(ctx C) {
ctx.So(err, ShouldNotBeNil)
ctx.So(resData, ShouldBeNil)
ctx.So(hit, ShouldBeNil)
})
})
})
}
func TestDao_VideoMultiFilter(t *testing.T) {
Convey("VideoFilter", t, func(ctx C) {
var (
err error
c = context.Background()
ip = "127.0.0.1"
msgs = []string{"李可强"}
resData []*archive.FilterData
hit []string
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("Post", d.postMFilterURI).Reply(200).JSON(`{"code":0,"message":"0","ttl":1,"data":[{"msg":"李可强","level":0,"typeid":[],"hit":[],"limit":0,"ai":{"scores":null,"threshold":0,"note":""}}]}`)
resData, hit, err = d.VideoMultiFilter(c, msgs, ip)
ctx.Convey("Then err should be nil.", func(ctx C) {
ctx.So(err, ShouldBeNil)
ctx.So(resData, ShouldNotBeNil)
ctx.So(hit, ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,50 @@
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"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/videoup/dao/geetest",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/geetest: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",
],
)
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,67 @@
package geetest
import (
"context"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"go-common/app/interface/main/videoup/conf"
"go-common/app/interface/main/videoup/model/geetest"
"go-common/library/ecode"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
const (
_validate = "/validate.php"
)
// Dao is account dao.
type Dao struct {
c *conf.Config
// url
validateURI string
// http client
clientX *httpx.Client
}
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
validateURI: c.Host.Geetest + _validate,
clientX: httpx.NewClient(c.HTTPClient.Read),
}
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 *geetest.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())
err = ecode.CreativeGeetestAPIErr
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err = d.clientX.Do(c, req, &res); err != nil {
log.Error("d.client.Do error(%v)", err)
err = ecode.CreativeGeetestAPIErr
return
}
return
}

View File

@@ -0,0 +1,69 @@
package geetest
import (
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.clientX.SetTransport(gock.DefaultTransport)
return r
}
func Test_Validate(t *testing.T) {
convey.Convey("Validate", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
challenge = "iamchallenge"
seccode = "iamseccode"
clientType = "iamclientType"
captchaID = "iamcaptchaID"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.validateURI).Reply(200).JSON(`{"code":20054,"data":""}`)
_, err = d.Validate(c, challenge, seccode, clientType, captchaID, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
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",
"mission_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"mission.go",
],
importpath = "go-common/app/interface/main/videoup/dao/mission",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/mission: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,34 @@
package mission
import (
"context"
"go-common/app/interface/main/videoup/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao is mission dao.
type Dao struct {
c *conf.Config
httpR *bm.Client
missAllURL string
actOnlineByTypeURL string
}
// New new a mission dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// client
httpR: bm.NewClient(c.HTTPClient.Read),
// uri
missAllURL: c.Host.WWW + _msAllURL,
actOnlineByTypeURL: c.Host.WWW + _actOnlineByTypeURI,
}
return d
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
return
}

View File

@@ -0,0 +1,35 @@
package mission
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.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,85 @@
package mission
import (
"context"
"net/url"
"strconv"
"time"
"go-common/app/interface/main/videoup/model/mission"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_msAllURL = "/activity/list/videoall"
_actOnlineByTypeURI = "/activity/online/by/type"
)
// Missions get missions.
func (d *Dao) Missions(c context.Context) (mm map[int]*mission.Mission, err error) {
var res struct {
Code int `json:"code"`
Data []*struct {
ID int `json:"id"`
Name string `json:"name"`
ETime string `json:"etime"`
Tags string `json:"tags"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.missAllURL, "", nil, &res); err != nil {
log.Error("videoup mission list error(%v) | missAllURL(%s)", err, d.missAllURL)
return
}
if res.Code != 0 {
log.Error("videoup mission list res.Code nq zero error(%v) | missAllURL(%s) res(%v)", res.Code, d.missAllURL, res)
err = ecode.CreativeActivityErr
return
}
mm = make(map[int]*mission.Mission, len(res.Data))
for _, m := range res.Data {
miss := &mission.Mission{}
miss.ID = m.ID
miss.Name = m.Name
miss.ETime, _ = time.Parse("2006-01-02 15:04:05", m.ETime)
miss.Tags = m.Tags
mm[miss.ID] = miss
}
return
}
// MissionOnlineByTid fn, 这里默认会返回所有无投稿分区限制要求的通用活动,在做校验的时候允许此类活动投稿到任意分区
func (d *Dao) MissionOnlineByTid(c context.Context, tid int16) (mm map[int]*mission.Mission, err error) {
var res struct {
Code int `json:"code"`
Data []*struct {
ID int `json:"id"`
Name string `json:"name"`
ETime string `json:"etime"`
Tags string `json:"tags"`
} `json:"data"`
}
mm = make(map[int]*mission.Mission)
params := url.Values{}
params.Set("type", strconv.Itoa(int(tid)))
params.Set("plat", "1")
if err = d.httpR.Get(c, d.actOnlineByTypeURL, "", params, &res); err != nil {
log.Error("videoup actOnlineByTypeURL error(%v) | actOnlineByTypeURL(%s)", err, d.actOnlineByTypeURL+"?"+params.Encode())
err = ecode.CreativeActivityErr
return
}
if res.Code != 0 {
log.Error("videoup actOnlineByTypeURL res.Code nq zero error(%v) | actOnlineByTypeURL(%s) res(%v)", res.Code, d.actOnlineByTypeURL+"?"+params.Encode(), res)
err = ecode.CreativeActivityErr
return
}
for _, m := range res.Data {
miss := &mission.Mission{}
miss.ID = m.ID
miss.Name = m.Name
miss.ETime, _ = time.Parse("2006-01-02 15:04:05", m.ETime)
miss.Tags = m.Tags
mm[miss.ID] = miss
}
return
}

View File

@@ -0,0 +1,39 @@
package mission
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestMissionMissions(t *testing.T) {
convey.Convey("Missions", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
mm, err := d.Missions(c)
ctx.Convey("Then err should be nil.mm should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mm, convey.ShouldNotBeNil)
})
})
})
}
func TestMissionMissionOnlineByTid(t *testing.T) {
convey.Convey("MissionOnlineByTid", t, func(ctx convey.C) {
var (
c = context.Background()
tid = int16(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
mm, err := d.MissionOnlineByTid(c, tid)
ctx.Convey("Then err should be nil.mm should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mm, 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 = ["dao_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/interface/main/videoup/dao/order",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//library/ecode:go_default_library",
"//library/log: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,146 @@
package order
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/videoup/conf"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
xtime "go-common/library/time"
)
const (
_executeOrders = "/api/open_api/v2/execute_orders"
_ups = "/api/open_api/v2/ups"
_launchtime = "/api/open_api/v2/execute_orders/launch_time"
_useExeOrder = "/api/open_api/v2/execute_orders/use"
)
// Dao define
type Dao struct {
c *conf.Config
// http
client *bm.Client
// uri
executeOrdersURI string
upsURI string
launchTimeURI string
useExeOrderURI string
}
// New init dao
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Chaodian),
executeOrdersURI: c.Host.Chaodian + _executeOrders,
upsURI: c.Host.Chaodian + _ups,
launchTimeURI: c.Host.Chaodian + _launchtime,
useExeOrderURI: c.Host.Chaodian + _useExeOrder,
}
return
}
// ExecuteOrders execute order ids.
func (d *Dao) ExecuteOrders(c context.Context, mid int64, ip string) (orderIds map[int64]int64, err error) {
params := url.Values{}
params.Set("up_mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Orders []*struct {
ExeOdID int64 `json:"execute_order_id"`
} `json:"data"`
}
if err = d.client.Get(c, d.executeOrdersURI, ip, params, &res); err != nil {
log.Error("chaodian url(%s) response(%+v) error(%v)", d.executeOrdersURI+"?"+params.Encode(), res, err)
err = ecode.VideoupOrderAPIErr
return
}
log.Info("chaodian url(%s)", d.executeOrdersURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("chaodian url(%s) res(%v)", d.executeOrdersURI, res)
err = ecode.VideoupOrderAPIErr
return
}
orderIds = make(map[int64]int64)
for _, v := range res.Orders {
orderIds[v.ExeOdID] = v.ExeOdID
}
return
}
// Ups order ups.
func (d *Dao) Ups(c context.Context) (ups map[int64]int64, err error) {
params := url.Values{}
var res struct {
Code int `json:"code"`
Ups []int64 `json:"data"`
}
if err = d.client.Get(c, d.upsURI, "", params, &res); err != nil {
log.Error("chaodian url(%s) response(%+v) error(%v)", d.upsURI+"?"+params.Encode(), res, err)
err = ecode.VideoupOrderAPIErr
return
}
log.Info("chaodian url(%s)", d.upsURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("chaodian url(%s) res(%v)", d.upsURI, res)
err = ecode.VideoupOrderAPIErr
return
}
ups = make(map[int64]int64)
for _, v := range res.Ups {
ups[v] = v
}
return
}
// BindOrder bind order with up.
func (d *Dao) BindOrder(c context.Context, mid, aid, orderID int64, ip string) (err error) {
params := url.Values{}
params.Set("execute_order_id", strconv.FormatInt(orderID, 10))
params.Set("av_id", strconv.FormatInt(aid, 10))
var res struct {
Code int `json:"code"`
Message string `json:"message"`
}
if err = d.client.Post(c, d.useExeOrderURI, ip, params, &res); err != nil {
log.Error("d.client.Do uri(%s) aid(%d) mid(%d) orderID(%d) error(%v)", d.useExeOrderURI+"?"+params.Encode(), mid, aid, orderID, err)
err = ecode.VideoupOrderAPIErr
return
}
log.Info("chaodian url(%s)", d.useExeOrderURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("d.client.Do uri(%s) aid(%d) mid(%d) orderID(%d) res.code(%d) error(%v)", d.useExeOrderURI+"?"+params.Encode(), mid, aid, orderID, res.Code, err)
err = ecode.VideoupOrderAPIErr
return
}
return
}
// PubTime publish time from order id.
func (d *Dao) PubTime(c context.Context, mid, orderID int64, ip string) (ptime xtime.Time, err error) {
params := url.Values{}
params.Set("execute_order_id", strconv.FormatInt(orderID, 10))
var res struct {
Code int `json:"code"`
Data struct {
BeginDate xtime.Time `json:"begin_date"`
} `json:"data"`
}
if err = d.client.Get(c, d.launchTimeURI, "", params, &res); err != nil {
log.Error("chaodian url(%s) response(%+v) error(%v)", d.launchTimeURI+"?"+params.Encode(), res, err)
err = ecode.VideoupOrderAPIErr
return
}
log.Info("chaodian url(%s)", d.launchTimeURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("chaodian url(%s) res(%v)", d.launchTimeURI, res)
err = ecode.VideoupOrderAPIErr
return
}
ptime = res.Data.BeginDate
return
}

View File

@@ -0,0 +1,124 @@
package order
import (
"context"
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.client.SetTransport(gock.DefaultTransport)
return r
}
func Test_PubTime(t *testing.T) {
convey.Convey("PubTime", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
orderID = int64(111)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.launchTimeURI).Reply(200).JSON(`{"code":21022,"data":""}`)
_, err = d.PubTime(c, mid, orderID, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func Test_BindOrder(t *testing.T) {
convey.Convey("BindOrder", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
aid = int64(10110826)
orderID = int64(111)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Post", d.useExeOrderURI).Reply(200).JSON(`{"code":21022,"data":""}`)
err = d.BindOrder(c, mid, aid, orderID, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func Test_Ups(t *testing.T) {
convey.Convey("Ups", t, func(ctx convey.C) {
var (
err error
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.upsURI).Reply(200).JSON(`{"code":21022,"data":""}`)
_, err = d.Ups(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func Test_ExecuteOrders(t *testing.T) {
convey.Convey("ExecuteOrders", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.executeOrdersURI).Reply(200).JSON(`{"code":21022,"data":""}`)
_, err = d.ExecuteOrders(c, mid, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,56 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"api_test.go",
"dao_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"api.go",
"dao.go",
],
importpath = "go-common/app/interface/main/videoup/dao/pay",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//app/interface/main/videoup/model/archive:go_default_library",
"//library/database/elastic:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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,104 @@
package pay
import (
"context"
"go-common/app/interface/main/videoup/model/archive"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/queue/databus/report"
"net/url"
"strconv"
)
const (
_assRegURI = "/x/internal/ugcpay/asset/register"
_assURI = "/x/internal/ugcpay/asset"
)
// AssReg 注册付费内容
func (d *Dao) AssReg(c context.Context, mid, aid int64, bp int, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("oid", strconv.FormatInt(aid, 10))
params.Set("price", strconv.Itoa(bp*100))
params.Set("otype", "archive")
params.Set("platform", "web")
params.Set("currency", "bp")
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.assRegURI, ip, params, &res); err != nil {
log.Error("d.client.Do uri(%s) aid(%d) mid(%d) bp(%d) code(%d) error(%v)", d.assRegURI+"?"+params.Encode(), mid, aid, bp, res.Code, err)
err = ecode.VideoupPayAPIErr
return
}
log.Info("UgcPay AssReg url(%s)", d.assRegURI+"?"+params.Encode())
if res.Code != 0 {
log.Error("UgcPay asset register url(%s) res(%+v); mid(%d),aid(%d),bp(%d),ip(%s),code(%d),error(%v)", d.assRegURI, res, mid, aid, bp, ip, res.Code, err)
err = ecode.VideoupPayAPIErr
return
}
return
}
// Ass 查看付费信息
// UGCPayAssetInvalid = New(88001) // ugcpay 内容无效
func (d *Dao) Ass(c context.Context, aid int64, ip string) (assert *archive.PayAsset, registed bool, err error) {
params := url.Values{}
params.Set("oid", strconv.FormatInt(aid, 10))
params.Set("otype", "archive")
params.Set("currency", "bp")
var res struct {
Code int `json:"code"`
Data *archive.PayAsset `json:"data"`
}
if err = d.client.Get(c, d.assURI, ip, params, &res); err != nil {
log.Error("d.client.Do uri(%s) aid(%d) code(%d) error(%v)", d.assURI+"?"+params.Encode(), aid, res.Code, err)
err = ecode.VideoupPayAPIErr
return
}
log.Info("UgcPay AssView url(%s)", d.assURI+"?"+params.Encode())
if res.Code != 0 {
if res.Code == ecode.UGCPayAssetInvalid.Code() {
log.Warn("UgcPay asset UGCPayAssetInvalid url(%s) res(%+v); aid(%d),ip(%s),error(%v)", d.assURI, res, aid, ip, err)
return nil, false, nil
}
err = ecode.VideoupPayAPIErr
log.Error("VideoupPayAPIErr AssView url(%s) res(%+v); aid(%d),ip(%s),code(%d),error(%v)", d.assURI, res, aid, ip, res.Code, err)
return
}
if res.Data != nil {
assert = res.Data
assert.Price = res.Data.Price / 100
registed = true
}
return
}
// UserAcceptProtocol fn: 判断当前的协议是否已经同意过,前端必须传递当前的投稿协议ID
func (d *Dao) UserAcceptProtocol(c context.Context, protocolID string, mid int64) (accept bool, err error) {
type Res struct {
Page *struct {
Num int `json:"num"`
Size int `json:"size"`
Total int `json:"total"`
} `json:"page"`
Result []*report.UserActionLog `json:"result"`
}
res := &Res{}
r := d.es.NewRequest("log_user_action")
r.Index("log_user_action_83_all").Pn(1).Ps(2000).OrderScoreFirst(true)
r.WhereEq("str_0", protocolID).WhereEq("mid", mid)
r.Order("ctime", "desc")
log.Info("UserAcceptProtocol params(%s)", r.Params())
if err = r.Scan(c, res); err != nil {
log.Error("UserAcceptProtocol r.Scan params(%s)|error(%v)", r.Params(), err)
return
}
if res.Page.Total == 0 {
accept = false
} else {
accept = true
}
return
}

View File

@@ -0,0 +1,61 @@
package pay
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestPayAssReg(t *testing.T) {
convey.Convey("AssReg", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
aid = int64(10110826)
bp = int(5)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AssReg(c, mid, aid, bp, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestPayAss(t *testing.T) {
convey.Convey("Ass", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(10110826)
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
assert, registed, err := d.Ass(c, aid, ip)
ctx.Convey("Then err should be nil.assert,registed should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(registed, convey.ShouldNotBeNil)
ctx.So(assert, convey.ShouldNotBeNil)
})
})
})
}
func TestPayUserAcceptProtocol(t *testing.T) {
convey.Convey("UserAcceptProtocol", t, func(ctx convey.C) {
var (
c = context.Background()
protocolID = "iamhashstring"
mid = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
accept, err := d.UserAcceptProtocol(c, protocolID, mid)
ctx.Convey("Then err should be nil.accept should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(accept, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,38 @@
package pay
import (
"context"
"go-common/app/interface/main/videoup/conf"
"go-common/library/database/elastic"
bm "go-common/library/net/http/blademaster"
)
// Dao str
type Dao struct {
c *conf.Config
client *bm.Client
assRegURI string
assURI string
es *elastic.Elastic
}
// New fn
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Write),
assRegURI: c.Host.APICo + _assRegURI,
assURI: c.Host.APICo + _assURI,
es: elastic.NewElastic(&elastic.Config{
Host: c.Host.MainSearch,
HTTPClient: c.HTTPClient.Read,
}),
}
return d
}
// Ping fn
func (d *Dao) Ping(c context.Context) (err error) {
return
}

View File

@@ -0,0 +1,35 @@
package pay
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.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,53 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"subtitle.go",
],
importpath = "go-common/app/interface/main/videoup/dao/subtitle",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/dm2/model:go_default_library",
"//app/interface/main/dm2/rpc/client:go_default_library",
"//app/interface/main/videoup/conf:go_default_library",
"//library/ecode:go_default_library",
"//library/log: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 = [
"dao_test.go",
"subtitle_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,21 @@
package subtitle
import (
"go-common/app/interface/main/dm2/rpc/client"
"go-common/app/interface/main/videoup/conf"
)
// Dao fn
type Dao struct {
c *conf.Config
sub *client.Service
}
// New fn
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
sub: client.New(c.SubRPC),
}
return
}

View File

@@ -0,0 +1,35 @@
package subtitle
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.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,22 @@
package subtitle
import (
"context"
"go-common/app/interface/main/dm2/model"
"go-common/library/ecode"
"go-common/library/log"
)
// Update fn
func (d *Dao) Update(c context.Context, aid int64, open bool, lan string) (err error) {
var arg = &model.ArgSubtitleAllowSubmit{
Aid: aid,
AllowSubmit: open,
Lan: lan,
}
if err = d.sub.SubtitleSujectSubmit(c, arg); err != nil {
log.Error("d.sub.SubtitleSujectSubmit (%+v) error(%v)", arg, err)
err = ecode.CreativeSubtitleAPIErr
}
return
}

View File

@@ -0,0 +1,25 @@
package subtitle
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestSubtitleUpdate(t *testing.T) {
convey.Convey("Update", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(10110826)
open bool
lan = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.Update(c, aid, open, lan)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,55 @@
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",
"tag_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/videoup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"tag.go",
],
importpath = "go-common/app/interface/main/videoup/dao/tag",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/creative/model/tag:go_default_library",
"//app/interface/main/videoup/conf: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,36 @@
package tag
import (
"context"
"go-common/app/interface/main/videoup/conf"
bm "go-common/library/net/http/blademaster"
)
// Dao is elec dao.
type Dao struct {
c *conf.Config
// http
httpW *bm.Client
// uri
upBindURL string
TagCheckURL string
}
// New new a elec dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// http client
httpW: bm.NewClient(c.HTTPClient.Write),
// uri
upBindURL: c.Host.Tag + _upBindURI,
TagCheckURL: c.Host.Tag + _tagCheck,
}
return d
}
// Ping ping success.
func (d *Dao) Ping(c context.Context) (err error) {
return
}

View File

@@ -0,0 +1,45 @@
package tag
import (
"flag"
"go-common/app/interface/main/videoup/conf"
"os"
"strings"
"testing"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.videoup")
flag.Set("conf_token", "9772c9629b00ac09af29a23004795051")
flag.Set("tree_id", "2306")
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/videoup.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
d.httpW.SetTransport(gock.DefaultTransport)
return r
}

View File

@@ -0,0 +1,62 @@
package tag
import (
"context"
"go-common/app/interface/main/creative/model/tag"
"go-common/library/ecode"
"go-common/library/log"
"net/url"
"strconv"
)
const (
_upBindURI = "/x/internal/tag/archive/upbind"
_tagCheck = "/x/internal/tag/check"
)
// UpBind update bind tag.
func (d *Dao) UpBind(c context.Context, mid, aid int64, tags, regionName, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("aid", strconv.FormatInt(aid, 10))
params.Set("tnames", tags)
params.Set("region_name", regionName)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.upBindURL, ip, params, &res); err != nil {
log.Error("d.httpW.Post(%s) error(%v)", d.upBindURL+"?"+params.Encode(), err)
err = ecode.CreativeTagErr
return
}
log.Info("url(%s) code(%d)", d.upBindURL+"?"+params.Encode(), res.Code)
if res.Code != 0 {
log.Error("url(%s) code(%d)", d.upBindURL+"?"+params.Encode(), res.Code)
err = ecode.CreativeTagErr
}
return
}
// TagCheck tag check
func (d *Dao) TagCheck(c context.Context, mid int64, tagName string) (t *tag.Tag, err error) {
var res struct {
Code int `json:"code"`
Data *tag.Tag `json:"data"`
}
params := url.Values{}
params.Set("tag_name", tagName)
params.Set("mid", strconv.FormatInt(mid, 10))
if err = d.httpW.Get(c, d.TagCheckURL, "", params, &res); err != nil {
log.Error("TagCheck url(%s) p(%+v) response(%s) error(%v)", d.TagCheckURL, params.Encode(), res, err)
err = ecode.CreativeTagErr
return
}
log.Info("TagCheck mid(%d) url(%s) res(%v)", mid, d.TagCheckURL, res)
if res.Code != 0 {
log.Error("TagCheck url(%s) res(%v)", d.TagCheckURL, res)
err = ecode.Int(res.Code)
return
}
t = res.Data
return
}

View File

@@ -0,0 +1,50 @@
package tag
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestTagUpBind(t *testing.T) {
convey.Convey("UpBind", t, func(ctx convey.C) {
var (
err error
c = context.Background()
mid = int64(2089809)
aid = int64(10110826)
tags = "LOL"
regionName = "游戏"
ip = "127.0.0.1"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.upBindURL).Reply(200).JSON(`{"code":20042,"data":""}`)
err = d.UpBind(c, mid, aid, tags, regionName, ip)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestTagCheck(t *testing.T) {
convey.Convey("TagCheck", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
tagName = "LOL"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("Get", d.TagCheckURL).Reply(200).JSON(`{"code":20042,"data":""}`)
no, err := d.TagCheck(c, mid, tagName)
ctx.Convey("Then err should be nil.no should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(no, convey.ShouldBeNil)
})
})
})
}