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,80 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"auto_case_test.go",
"blocked_test.go",
"case_mc_test.go",
"case_test.go",
"dao_test.go",
"depend_test.go",
"jury_test.go",
"memcache_test.go",
"mysql_test.go",
"redis_test.go",
"reply_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/job/main/credit/conf:go_default_library",
"//app/job/main/credit/model:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"auto_case.go",
"blocked.go",
"case.go",
"case_mc.go",
"dao.go",
"depend.go",
"jury.go",
"memcache.go",
"mysql.go",
"redis.go",
"reply.go",
],
importpath = "go-common/app/job/main/credit/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/credit/conf:go_default_library",
"//app/job/main/credit/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/sql: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",
"//library/xstr:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,40 @@
package dao
import (
"context"
"database/sql"
"go-common/app/job/main/credit/model"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_autoCaseConfigSQL = "SELECT reasons,report_score,likes FROM blocked_auto_case WHERE platform = ?"
)
// AutoCaseConf get auto case config.
func (d *Dao) AutoCaseConf(c context.Context, otype int8) (ac *model.AutoCaseConf, err error) {
ac = &model.AutoCaseConf{}
row := d.db.QueryRow(c, _autoCaseConfigSQL, otype)
if err = row.Scan(&ac.ReasonStr, &ac.ReportScore, &ac.Likes); err != nil {
if err != sql.ErrNoRows {
log.Error("d.AutoCaseConf err(%v)", err)
return
}
ac = nil
err = nil
}
if ac != nil && ac.ReasonStr != "" {
var reasonSlice []int64
if reasonSlice, err = xstr.SplitInts(ac.ReasonStr); err != nil {
log.Error("xstr.SplitInts(%s) err(%v)", ac.ReasonStr, err)
return
}
ac.Reasons = make(map[int8]struct{}, len(reasonSlice))
for _, v := range reasonSlice {
ac.Reasons[int8(v)] = struct{}{}
}
}
return
}

View File

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

View File

@@ -0,0 +1,31 @@
package dao
import (
"context"
"time"
"go-common/library/log"
)
const (
_countBlockedSQL = "SELECT COUNT(*) FROM blocked_info WHERE uid=? AND ctime > ? AND status = 0"
_blockedInfoID = "SELECT id FROM blocked_info WHERE uid=? ORDER BY id DESC"
)
// CountBlocked get user block count ofter ts.
func (d *Dao) CountBlocked(c context.Context, uid int64, ts time.Time) (count int64, err error) {
row := d.db.QueryRow(c, _countBlockedSQL, uid, ts)
if err = row.Scan(&count); err != nil {
log.Error("d.CountBlocked err(%v)", err)
}
return
}
// BlockedInfoID get user blocked new info.
func (d *Dao) BlockedInfoID(c context.Context, uid int64) (id int64, err error) {
row := d.db.QueryRow(c, _blockedInfoID, uid)
if err = row.Scan(&id); err != nil {
log.Error("d.BlockedInfoID err(%v)", err)
}
return
}

View File

@@ -0,0 +1,25 @@
package dao
import (
"context"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestDaoCountBlocked(t *testing.T) {
Convey("should return err be nil and num>=0", t, func() {
num, err := d.CountBlocked(context.TODO(), 27515415, time.Now())
So(err, ShouldBeNil)
So(num, ShouldBeGreaterThanOrEqualTo, 0)
})
}
func TestDaoBlockedInfoID(t *testing.T) {
Convey("should return err be nil and num>=0", t, func() {
id, err := d.BlockedInfoID(context.TODO(), 27515415)
So(err, ShouldBeNil)
So(id, ShouldBeGreaterThanOrEqualTo, 0)
})
}

View File

@@ -0,0 +1,206 @@
package dao
import (
"context"
"database/sql"
"fmt"
"time"
"go-common/app/job/main/credit/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
xtime "go-common/library/time"
"go-common/library/xstr"
)
const (
_inBlockedCasesSQL = "INSERT INTO blocked_case(mid,status,origin_content,punish_result,origin_title,origin_type,origin_url,blocked_days,reason_type,relation_id,oper_id,business_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
_inBlockedCaseModifyLogSQL = "INSERT INTO blocked_case_modify_log(case_id,modify_type,origin_reason,modify_reason) VALUES (?,?,?,?)"
_upBlockedCaseReasonSQL = "UPDATE blocked_case SET reason_type = ? WHERE id = ?"
_upBlockedCaseStatusSQL = "UPDATE blocked_case SET status = ? WHERE id = ?"
_upGrantCaseSQL = "UPDATE blocked_case SET status = 1, start_time = ?, end_time = ? WHERE id IN (%s)"
_grantCaseSQL = "SELECT id,mid,start_time,end_time,vote_rule,vote_break,vote_delete,case_type FROM blocked_case WHERE status = 8 ORDER BY mtime ASC limit ?"
_caseVoteSQL = "SELECT mid,vote,expired FROM blocked_case_vote WHERE id = ?"
_caseRelationIDCountSQL = "SELECT COUNT(*) FROM blocked_case WHERE origin_type=? AND relation_id =?"
_caseVotesCIDSQL = "SELECT mid,vote FROM blocked_case_vote WHERE cid = ?"
_countCaseMIDSQL = "SELECT COUNT(*) FROM blocked_case WHERE mid = ? AND origin_type = ? AND ctime >= ?"
_caseApplyReasonsSQL = "SELECT DISTINCT(apply_reason) FROM blocked_case_apply_log WHERE case_id = ? AND apply_type = 1"
_caseApplyReasonNumSQL = "SELECT COUNT(*) AS num, case_id, apply_type, apply_reason, origin_reason FROM `blocked_case_apply_log` WHERE case_id = ? AND apply_type = 1 AND apply_reason IN (%s) GROUP BY apply_reason ORDER BY mtime ASC"
_casesStatusSQL = "SELECT id,status FROM blocked_case WHERE id IN (%s)"
)
// AddBlockedCase add blocked case.
func (d *Dao) AddBlockedCase(c context.Context, ca *model.Case) (err error) {
if _, err = d.db.Exec(c, _inBlockedCasesSQL, ca.Mid, ca.Status, ca.OriginContent, ca.PunishResult, ca.OriginTitle, ca.OriginType, ca.OriginURL, ca.BlockedDay, ca.ReasonType, ca.RelationID, ca.OPID, ca.BCtime); err != nil {
log.Error("d.AddBlockedCase(%+v) err(%v)", ca, err)
}
return
}
// AddBlockedCaseModifyLog add blocked case modify log.
func (d *Dao) AddBlockedCaseModifyLog(c context.Context, cid int64, mType, oReason, mReason int8) (err error) {
if _, err = d.db.Exec(c, _inBlockedCaseModifyLogSQL, cid, mType, oReason, mReason); err != nil {
log.Error("d.AddBlockedCaseModifyLog(%d,%d,%d,%d) err(%v)", cid, mType, oReason, mReason, err)
}
return
}
// UpBlockedCaseReason update blocked case reason.
func (d *Dao) UpBlockedCaseReason(c context.Context, cid int64, reasonType int8) (affect int64, err error) {
var result sql.Result
if result, err = d.db.Exec(c, _upBlockedCaseReasonSQL, reasonType, cid); err != nil {
log.Error("d.UpBlockedCaseReason(%d,%d) err(%v)", cid, reasonType, err)
return
}
return result.RowsAffected()
}
// UpBlockedCaseStatus update blocked case status.
func (d *Dao) UpBlockedCaseStatus(c context.Context, cid int64, status int8) (err error) {
if _, err = d.db.Exec(c, _upBlockedCaseStatusSQL, status, cid); err != nil {
log.Error("d.UpBlockedCaseStatus(%d,%d) err(%v)", cid, status, err)
}
return
}
// UpGrantCase update blocked_case from que to granting.
func (d *Dao) UpGrantCase(c context.Context, ids []int64, stime xtime.Time, etime xtime.Time) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_upGrantCaseSQL, xstr.JoinInts(ids)), stime, etime); err != nil {
log.Error("d.UpGrantCase(%s,%v,%v) err(%v)", xstr.JoinInts(ids), stime, etime, err)
}
return
}
// Grantcase get case from state of CaseStatusQueueing.
func (d *Dao) Grantcase(c context.Context, limit int) (mcases map[int64]*model.SimCase, err error) {
mcases = make(map[int64]*model.SimCase)
rows, err := d.db.Query(c, _grantCaseSQL, limit)
if err != nil {
log.Error("d.Grantcase err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
ca := &model.SimCase{}
if err = rows.Scan(&ca.ID, &ca.Mid, &ca.Stime, &ca.Etime, &ca.VoteRule, &ca.VoteBreak, &ca.VoteDelete, &ca.CaseType); err != nil {
log.Error("rows.Scan err(%v)", err)
return
}
mcases[ca.ID] = ca
}
err = rows.Err()
return
}
// CaseVote get blocked case vote info.
func (d *Dao) CaseVote(c context.Context, id int64) (res *model.CaseVote, err error) {
res = &model.CaseVote{}
row := d.db.QueryRow(c, _caseVoteSQL, id)
if err = row.Scan(&res.MID, &res.Vote, &res.Expired); err != nil {
log.Error("d.CaseVote err(%v)", err)
}
return
}
// CaseRelationIDCount get case relation_id count.
func (d *Dao) CaseRelationIDCount(c context.Context, tp int8, relationID string) (count int64, err error) {
row := d.db.QueryRow(c, _caseRelationIDCountSQL, tp, relationID)
if err = row.Scan(&count); err != nil {
log.Error("d.caseRelationIDCount err(%v)", err)
}
return
}
// CaseVotesCID is blocked case vote list by cid.
func (d *Dao) CaseVotesCID(c context.Context, cid int64) (res []*model.CaseVote, err error) {
rows, err := d.db.Query(c, _caseVotesCIDSQL, cid)
if err != nil {
log.Error("d.CaseVoteCID(%d) err(%v)", cid, err)
return
}
defer rows.Close()
for rows.Next() {
ca := &model.CaseVote{}
if err = rows.Scan(&ca.MID, &ca.Vote); err != nil {
log.Error("rows.Scan err(%v)", err)
return
}
res = append(res, ca)
}
err = rows.Err()
return
}
// CountCaseMID get count case by mid.
func (d *Dao) CountCaseMID(c context.Context, mid int64, tp int8) (count int64, err error) {
row := d.db.QueryRow(c, _countCaseMIDSQL, mid, tp, time.Now().AddDate(0, 0, -2))
if err = row.Scan(&count); err != nil {
log.Error("d.CountCaseMID err(%v)", err)
}
return
}
// CaseApplyReasons case apply reasons.
func (d *Dao) CaseApplyReasons(c context.Context, cid int64) (aReasons []int64, err error) {
rows, err := d.db.Query(c, _caseApplyReasonsSQL, cid)
if err != nil {
log.Error("d.CaseApplyReasons(%d) err(%v)", cid, err)
return
}
defer rows.Close()
for rows.Next() {
var aReason int64
if err = rows.Scan(&aReason); err != nil {
log.Error("rows.Scan err(%v)", err)
return
}
aReasons = append(aReasons, aReason)
}
err = rows.Err()
return
}
// CaseApplyReasonNum case group apply reasons num.
func (d *Dao) CaseApplyReasonNum(c context.Context, cid int64, aReasons []int64) (cas []*model.CaseApplyModifyLog, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_caseApplyReasonNumSQL, xstr.JoinInts(aReasons)), cid)
if err != nil {
log.Error("d.CaseApplyReasonNum(%s) err(%v)", xstr.JoinInts(aReasons), err)
return
}
defer rows.Close()
for rows.Next() {
ca := &model.CaseApplyModifyLog{}
if err = rows.Scan(&ca.Num, &ca.CID, &ca.AType, &ca.AReason, &ca.OReason); err != nil {
log.Error("rows.Scan err(%v)", err)
return
}
cas = append(cas, ca)
}
err = rows.Err()
return
}
// CasesStatus get cases status.
func (d *Dao) CasesStatus(c context.Context, cids []int64) (map[int64]int8, error) {
rows, err := d.db.Query(c, fmt.Sprintf(_casesStatusSQL, xstr.JoinInts(cids)))
if err != nil {
return nil, err
}
defer rows.Close()
cs := make(map[int64]int8, len(cids))
for rows.Next() {
var (
cid int64
status int8
)
if err = rows.Scan(&cid, &status); err != nil {
if err == xsql.ErrNoRows {
err = nil
}
return nil, err
}
cs[cid] = status
}
err = rows.Err()
return cs, err
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
"fmt"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_prefixCaseInfo = "ca_in_%d"
_prefixVoteCaseInfo = "vc_in_%d_%d"
)
func caseInfoKey(cid int64) string {
return fmt.Sprintf(_prefixCaseInfo, cid)
}
func voteCaseInfoKey(mid int64, cid int64) string {
return fmt.Sprintf(_prefixVoteCaseInfo, mid, cid)
}
// DelCaseInfoCache del case info cache info.
func (d *Dao) DelCaseInfoCache(c context.Context, cid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(caseInfoKey(cid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d) error(%v)", cid, err)
}
return
}
// DelVoteCaseCache del vote case cache info.
func (d *Dao) DelVoteCaseCache(c context.Context, mid, cid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(voteCaseInfoKey(mid, cid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d,%d) error(%v)", mid, cid, err)
}
return
}

View File

@@ -0,0 +1,22 @@
package dao
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestDaoDelCaseInfoCache(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.DelCaseInfoCache(context.TODO(), 12)
So(err, ShouldBeNil)
})
}
func TestDaoDelVoteCaseCache(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.DelVoteCaseCache(context.TODO(), 12, 11)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,71 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/job/main/credit/model"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func Test_AddBlockedCase(t *testing.T) {
Convey("should return err be nil", t, func() {
ca := &model.Case{}
ca.Mid = 6660
ca.BlockedDay = 7
err := d.AddBlockedCase(context.TODO(), ca)
So(err, ShouldBeNil)
})
}
func Test_UpGrantCase(t *testing.T) {
Convey("should return err be nil", t, func() {
now := time.Now()
err := d.UpGrantCase(context.TODO(), []int64{1, 2}, xtime.Time(now.Unix()), xtime.Time(now.Unix()))
So(err, ShouldBeNil)
})
}
func Test_Grantcase(t *testing.T) {
Convey("should return err be nil", t, func() {
sc, err := d.Grantcase(context.TODO(), 3)
So(err, ShouldBeNil)
So(sc, ShouldNotBeNil)
So(sc, ShouldResemble, make(map[int64]*model.SimCase))
})
}
func Test_CaseVote(t *testing.T) {
Convey("should return err be nil", t, func() {
cv, err := d.CaseVote(context.TODO(), 1004)
So(err, ShouldBeNil)
So(cv, ShouldNotBeNil)
})
}
func Test_CaseRelationIDCount(t *testing.T) {
Convey("should return err be nil", t, func() {
count, err := d.CaseRelationIDCount(context.TODO(), 2, "2-8-113")
So(err, ShouldBeNil)
So(count, ShouldBeGreaterThanOrEqualTo, 0)
})
}
func Test_CaseVotesCID(t *testing.T) {
Convey("should return err be nil", t, func() {
cv, err := d.CaseVotesCID(context.TODO(), 2)
So(err, ShouldBeNil)
So(cv, ShouldNotBeNil)
})
}
func Test_CountCaseMID(t *testing.T) {
Convey("should return err be nil", t, func() {
count, err := d.CountCaseMID(context.TODO(), 1, 2)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,97 @@
package dao
import (
"context"
"time"
"go-common/app/job/main/credit/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
)
const (
_delReplyURI = "/x/internal/v2/reply/del"
_delTagURI = "/x/internal/tag/archive/del"
_regReplyURI = "/x/internal/v2/reply/subject/regist"
_blockAccountURI = "/x/internal/block/block"
_unBlockAccountURI = "/x/internal/block/remove"
_sendPendantURI = "/x/internal/pendant/multiGrantByPid"
_sendMsgURI = "/api/notify/send.user.notify.do"
_delDMURI = "/x/internal/dmadmin/report/judge/result"
_sendMedalURI = "/x/internal/medal/grant"
_addMoralURI = "/api/moral/add"
_upReplyStateURI = "/x/internal/v2/reply/report/state"
_modifyCoinsURI = "/x/internal/v1/coin/user/modify"
_filterURI = "/x/internal/filter"
_upAppealStateURI = "/x/internal/workflow/appeal/v3/public/referee"
)
// Dao struct info of Dao.
type Dao struct {
db *sql.DB
c *conf.Config
client *bm.Client
// del path
delReplyURL string
delTagURL string
delDMURL string
blockAccountURL string
unBlockAccountURL string
regReplyURL string
sendPendantURL string
sendMsgURL string
sendMedalURL string
addMoralURL string
upReplyStateURL string
modifyCoinsURL string
filterURL string
upAppealStateURL string
// redis // redis
redis *redis.Pool
redisExpire int64
// memcache
mc *memcache.Pool
}
// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: sql.NewMySQL(c.Mysql),
client: bm.NewClient(c.HTTPClient),
delReplyURL: c.Host.APICoURI + _delReplyURI,
delTagURL: c.Host.APICoURI + _delTagURI,
regReplyURL: c.Host.APICoURI + _regReplyURI,
blockAccountURL: c.Host.APICoURI + _blockAccountURI,
unBlockAccountURL: c.Host.APICoURI + _unBlockAccountURI,
sendPendantURL: c.Host.APICoURI + _sendPendantURI,
sendMsgURL: c.Host.MsgCoURI + _sendMsgURI,
delDMURL: c.Host.APICoURI + _delDMURI,
sendMedalURL: c.Host.APICoURI + _sendMedalURI,
addMoralURL: c.Host.AccountCoURI + _addMoralURI,
upReplyStateURL: c.Host.APICoURI + _upReplyStateURI,
modifyCoinsURL: c.Host.APICoURI + _modifyCoinsURI,
filterURL: c.Host.APICoURI + _filterURI,
upAppealStateURL: c.Host.APICoURI + _upAppealStateURI,
// redis
redis: redis.NewPool(c.Redis.Config),
redisExpire: int64(time.Duration(c.Redis.Expire) / time.Second),
// memcache
mc: memcache.NewPool(c.Memcache.Config),
}
return
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
}
// Ping ping health of db.
func (d *Dao) Ping(c context.Context) (err error) {
return d.db.Ping(c)
}

View File

@@ -0,0 +1,44 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/job/main/credit/conf"
"gopkg.in/h2non/gock.v1"
)
var d *Dao
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account-law.credit-job")
flag.Set("conf_token", "KCWd5XPfBUjexnogldviQxV0tEtiFcvy")
flag.Set("tree_id", "2937")
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")
}
if os.Getenv("UT_LOCAL_TEST") != "" {
flag.Set("conf", "../cmd/convey-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.client.SetTransport(gock.DefaultTransport)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}

View File

@@ -0,0 +1,306 @@
package dao
import (
"context"
"errors"
"fmt"
"net/url"
"strconv"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/xstr"
)
// SendPendant send pendant.
func (d *Dao) SendPendant(c context.Context, mid int64, pids []int64, day int64) (err error) {
params := url.Values{}
params.Set("pids", xstr.JoinInts(pids))
params.Set("mid", strconv.FormatInt(mid, 10))
var days []int64
for range pids {
days = append(days, day)
}
params.Set("expires", xstr.JoinInts(days))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.sendPendantURL, "", params, &res); err != nil {
log.Error("d.sendPendantURL url(%s) res(%d) error(%v)", d.sendPendantURL+"?"+params.Encode(), res.Code, err)
return
}
if res.Code != 0 {
log.Error("d.sendPendantURL url(%s) code(%d)", d.sendPendantURL+"?"+params.Encode(), res.Code)
err = errors.New("sendPendant failed")
}
return
}
// SendMedal send Medal.
func (d *Dao) SendMedal(c context.Context, mid int64, nid int64) (err error) {
params := url.Values{}
params.Set("nid", strconv.FormatInt(nid, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.sendMedalURL, "", params, &res); err != nil {
log.Error("d.sendMedalURL url(%s) res(%d) error(%v)", d.sendMedalURL+"?"+params.Encode(), res.Code, err)
return
}
if res.Code != 0 {
log.Error("d.sendMedalURL url(%s) code(%d)", d.sendMedalURL+"?"+params.Encode(), res.Code)
err = errors.New("sendMedalURL failed")
}
return
}
// DelTag del tag.
func (d *Dao) DelTag(c context.Context, tid, aid string) (err error) {
params := url.Values{}
params.Set("aid", aid)
params.Set("tag_id", tid)
params.Set("mid", "0")
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.delTagURL, "", params, &res); err != nil {
log.Info("d.delTagURL url(%s) res(%v) error(%v)", d.delTagURL+"?"+params.Encode(), res, err)
return
}
if res.Code != 0 {
log.Error("d.delTagURL url(%s) code(%d)", d.delTagURL+"?"+params.Encode(), res.Code)
}
log.Info("d.delTagURL url(%s) res(%d)", d.delTagURL+"?"+params.Encode(), res.Code)
return
}
// ReportDM report dm is delete.
func (d *Dao) ReportDM(c context.Context, cid string, dmid string, result int64) (err error) {
params := url.Values{}
params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
params.Set("cid", cid)
params.Set("dmid", dmid)
params.Set("result", strconv.FormatInt(result, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.delDMURL, "", params, &res); err != nil {
log.Error("d.delDMURL url(%s) error(%v)", d.delDMURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("d.delDMURL url(%s) code(%d)", d.delDMURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}
// BlockAccount block account.
func (d *Dao) BlockAccount(c context.Context, r *model.BlockedInfo) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(r.UID, 10))
params.Set("source", "1")
if int8(r.PunishType) == model.PunishTypeForever && r.BlockedForever == model.InBlockedForever {
params.Set("action", "2")
} else {
params.Set("action", "1")
}
if r.CaseID == 0 {
params.Set("notify", "1")
} else {
params.Set("notify", "0")
}
params.Set("duration", strconv.FormatInt(r.BlockedDays*86400, 10))
params.Set("start_time", fmt.Sprintf("%d", time.Now().Unix()))
params.Set("op_id", strconv.FormatInt(r.OPID, 10))
params.Set("operator", r.OperatorName)
params.Set("reason", model.ReasonTypeDesc(int8(r.ReasonType)))
params.Set("comment", r.BlockedRemark)
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.blockAccountURL, "", params, &res); err != nil {
log.Error("d.blockAccountURL res(%d) url(%s)", res.Code, d.blockAccountURL+"?"+params.Encode())
}
log.Info("d.blockAccountURL res(%d) url(%s)", res.Code, d.blockAccountURL+"?"+params.Encode())
return
}
// UnBlockAccount unblock account.
func (d *Dao) UnBlockAccount(c context.Context, r *model.BlockedInfo) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(r.UID, 10))
params.Set("source", "1")
params.Set("op_id", strconv.FormatInt(r.OPID, 10))
params.Set("operator", r.OperatorName)
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.unBlockAccountURL, "", params, &res); err != nil {
log.Error("d.unBlockAccountURL res(%d) url(%s)", res.Code, d.unBlockAccountURL+"?"+params.Encode())
}
log.Info("d.unBlockAccountURL res(%d) url(%s)", res.Code, d.unBlockAccountURL+"?"+params.Encode())
return
}
// SendMsg send message.
func (d *Dao) SendMsg(c context.Context, mid int64, title string, context string) (err error) {
params := url.Values{}
params.Set("mc", "2_1_13")
params.Set("title", title)
params.Set("data_type", "4")
params.Set("context", context)
params.Set("mid_list", fmt.Sprintf("%d", mid))
var res struct {
Code int `json:"code"`
Data *struct {
Status int8 `json:"status"`
Remark string `json:"remark"`
} `json:"data"`
}
if err = d.client.Post(c, d.sendMsgURL, "", params, &res); err != nil {
log.Error("sendMsgURL(%s) error(%v)", d.sendMsgURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("sendMsgURL(%s) res(%d)", d.sendMsgURL+"?"+params.Encode(), res.Code)
}
log.Info("d.sendMsgURL url(%s) res(%d)", d.sendMsgURL+"?"+params.Encode(), res.Code)
return
}
// Sms send monitor sms.
func (d *Dao) Sms(c context.Context, phone, token, msg string) (err error) {
var (
urlStr = "http://ops-mng.bilibili.co/api/sendsms"
res struct {
Result bool `json:"result"`
}
)
params := url.Values{}
params.Set("phone", phone)
params.Set("message", msg)
params.Set("token", token)
if err = d.client.Get(c, urlStr, "", params, &res); err != nil {
log.Error("d.Sms url(%s) res(%v) err(%v)", urlStr+"?"+params.Encode(), res, err)
return
}
if !res.Result {
log.Error("ops-mng sendsms url(%s) result(%v)", urlStr+"?"+params.Encode(), res.Result)
}
log.Info("d.Sms url(%s) res(%v)", urlStr+"?"+params.Encode(), res)
return
}
// AddMoral add or reduce moral to user
func (d *Dao) AddMoral(c context.Context, mid int64, moral float64, reasonType int8, oper, reason, remark, remoteIP string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("addMoral", strconv.FormatFloat(moral, 'f', -1, 64))
if moral > 0 {
params.Set("origin", "1")
} else {
params.Set("origin", "2")
}
if oper == "" {
params.Set("operater", "系统")
} else {
params.Set("operater", oper)
}
params.Set("reason", reason)
params.Set("reason_type", strconv.FormatInt(int64(reasonType), 10))
params.Set("remark", remark)
params.Set("is_notify", "1")
var res struct {
Code int `json:"code"`
}
err = d.client.Get(c, d.addMoralURL, remoteIP, params, &res)
if err != nil {
log.Error("d.addMoralURL url(%s) error(%v)", d.addMoralURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("d.addMoralURL url(%s) error(%v)", d.addMoralURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
log.Info("d.addMoralURL url(%s) res(%v)", d.addMoralURL+"?"+params.Encode(), res)
return
}
// AddMoney Modify user Coinsold.
func (d *Dao) AddMoney(c context.Context, mid int64, money float64, reason string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("count", strconv.FormatFloat(money, 'f', -1, 64))
params.Set("reason", reason)
var res struct {
Code int `json:"code"`
}
err = d.client.Post(c, d.modifyCoinsURL, "", params, &res)
log.Info("d.modifyCoinsURL url(%s) res(%v)", d.modifyCoinsURL+"?"+params.Encode(), res)
if err != nil {
log.Error("d.modifyCoinsURL url(%s) error(%v)", d.modifyCoinsURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("d.modifyCoinsURL url(%s) error(%v)", d.modifyCoinsURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}
// CheckFilter check content filter.
func (d *Dao) CheckFilter(c context.Context, area, msg, ip string) (need bool, err error) {
params := url.Values{}
params.Set("area", area)
params.Set("msg", msg)
var res struct {
Code int `json:"code"`
Data *struct {
Level int `json:"level"`
Limit int `json:"limit"`
Msg string `json:"msg"`
} `json:"data"`
}
err = d.client.Get(c, d.filterURL, ip, params, &res)
if err != nil {
log.Error("d.filterURL url(%s) error(%v)", d.filterURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("d.filterURL url(%s) error(%v)", d.filterURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
if res.Data == nil {
log.Warn("d.filterURL url(%s) res(%+v)", d.filterURL+"?"+params.Encode(), res.Data)
return
}
need = res.Data.Level >= 20
return
}
// UpAppealState .
func (d *Dao) UpAppealState(c context.Context, bid, oid, eid int64) (err error) {
params := url.Values{}
params.Set("business", strconv.FormatInt(bid, 10))
params.Set("oid", strconv.FormatInt(oid, 10))
params.Set("eid", strconv.FormatInt(eid, 10))
var res struct {
Code int `json:"code"`
}
err = d.client.Post(c, d.upAppealStateURL, "", params, &res)
log.Info("d.upAppealStateURL url(%s) res(%v)", d.upAppealStateURL+"?"+params.Encode(), res)
if err != nil {
log.Error("d.upAppealStateURL url(%s) error(%v)", d.upAppealStateURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("d.upAppealStateURL url(%s) error(%v)", d.upAppealStateURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
}
return
}

View File

@@ -0,0 +1,121 @@
package dao
import (
"context"
"testing"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func Test_SendPendant(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.SendPendant(context.TODO(), 27515305, []int64{83, 84}, 30)
So(err, ShouldBeNil)
})
}
func Test_SendMedal(t *testing.T) {
Convey("should return err be nil", t, func() {
defer gock.OffAll()
httpMock("POST", d.sendMedalURL).Reply(200).JSON(`{"code":0}`)
err := d.SendMedal(context.TODO(), 27515305, 4)
So(err, ShouldBeNil)
})
}
func Test_DelTag(t *testing.T) {
Convey("should return err be nil", t, func() {
defer gock.OffAll()
httpMock("POST", d.delTagURL).Reply(200).JSON(`{"code":0}`)
err := d.DelTag(context.TODO(), "1", "4")
So(err, ShouldBeNil)
})
}
func Test_ReportDM(t *testing.T) {
Convey("should return err be nil", t, func() {
defer gock.OffAll()
httpMock("POST", d.delDMURL).Reply(200).JSON(`{"code":0}`)
err := d.ReportDM(context.TODO(), "1", "4", 1)
So(err, ShouldBeNil)
})
}
func Test_BlockAccount(t *testing.T) {
var bi = &model.BlockedInfo{}
bi.UID = 27515305
Convey("should return err be nil", t, func() {
err := d.BlockAccount(context.TODO(), bi)
So(err, ShouldBeNil)
})
}
func TestDaoUnBlockAccount(t *testing.T) {
var bi = &model.BlockedInfo{}
bi.UID = 27515305
Convey("should return err be nil", t, func() {
err := d.UnBlockAccount(context.TODO(), bi)
So(err, ShouldBeNil)
})
}
func Test_SendMsg(t *testing.T) {
Convey("should return err be nil", t, func() {
defer gock.OffAll()
httpMock("POST", d.sendMsgURL).Reply(200).JSON(`{"code":0}`)
err := d.SendMsg(context.TODO(), 88889017, "风纪委员任期结束", "您的风纪委员资格已到期,任职期间的总结报告已生成。感谢您对社区工作的大力支持!#{点击查看}{"+"\"http://www.bilibili.com/judgement/\""+"}")
So(err, ShouldBeNil)
})
}
func TestDaoSms(t *testing.T) {
Convey("should return err be nil", t, func() {
defer gock.OffAll()
httpMock("GET", "http://ops-mng.bilibili.co/api/sendsms").Reply(200).JSON(`{"code":0}`)
err := d.Sms(context.TODO(), "13888888888", "1232131", "hahh1")
So(err, ShouldBeNil)
})
}
func Test_AddMoral(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.AddMoral(context.TODO(), 27515305, -10, 1, "credit", "reason", "风纪委处罚", "")
So(err, ShouldBeNil)
})
}
func Test_AddMoney(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.AddMoney(context.TODO(), 27956255, 10, "风纪委奖励")
So(err, ShouldBeNil)
})
}
func TestDaoCheckFilter(t *testing.T) {
Convey("should return err be nil", t, func() {
res, err := d.CheckFilter(context.TODO(), "credit", "lalsdal1", "127.0.0.1")
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestDaoUpAppealState(t *testing.T) {
Convey("UpAppealState", t, func(ctx C) {
var (
c = context.Background()
bid = model.AppealBusinessID
oid = int64(1)
eid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx C) {
defer gock.OffAll()
httpMock("POST", d.upAppealStateURL).Reply(200).JSON(`{"code":0}`)
err := d.UpAppealState(c, bid, oid, eid)
ctx.Convey("Then err should be nil.", func(ctx C) {
ctx.So(err, ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,150 @@
package dao
import (
"context"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
_addBlockInfoSQL = `INSERT INTO blocked_info (uid,origin_title,blocked_remark,origin_url,origin_content,origin_content_modify,origin_type,
punish_time,punish_type,moral_num,blocked_days,publish_status,reason_type,operator_name,blocked_forever,blocked_type,case_id,oper_id)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`
_updateKPISQL = "UPDATE blocked_kpi set rate=1,rank_per=1 where id=?"
_updateKPIPendentSQL = "UPDATE blocked_kpi set pendent_status=1 where id=?"
_updateKPIHandlerSQL = "UPDATE blocked_kpi set handler_status=1 where id=?"
_updateCaseSQL = "UPDATE blocked_case SET status=?,judge_type=? WHERE id=?"
_invalidJurySQL = "UPDATE blocked_jury SET status=2,invalid_reason=? where mid=?"
_updateVoteRightSQL = "UPDATE blocked_jury SET vote_total = vote_total + 1, vote_right = vote_right + 1 WHERE mid = ?"
_updateVoteTotalSQL = "UPDATE blocked_jury SET vote_total = vote_total + 1 WHERE mid = ?"
_updatePunishResultSQL = "UPDATE blocked_case SET punish_result=? WHERE id=?"
_selKPISQL = "SELECT id,mid,rate from blocked_kpi where rate in(1,2,3) and day=?"
_selKPIInfoSQL = "SELECT id,mid,handler_status from blocked_kpi where id=?"
_selCaseByIDSQL = "SELECT id,mid,status,judge_type,relation_id from blocked_case where id=?"
_countKPIRateSQL = "SELECT COUNT(*) AS num FROM blocked_kpi WHERE mid=? AND rate<=4"
)
// AddBlockInfo add user block info.
func (d *Dao) AddBlockInfo(c context.Context, b *model.BlockedInfo, ts time.Time) (id int64, err error) {
res, err := d.db.Exec(c, _addBlockInfoSQL, b.UID, b.OriginTitle, b.BlockedRemark, b.OriginURL, b.OriginContent, b.OriginContentModify, b.OriginType,
ts, b.PunishType, b.MoralNum, b.BlockedDays, b.PublishStatus, b.ReasonType, b.OperatorName, b.BlockedForever, b.BlockedType, b.CaseID, b.OPID)
if err != nil {
log.Error("d.AddBlockInfo err(%v)", err)
}
return res.LastInsertId()
}
// UpdateKPI update kpi status to st.
func (d *Dao) UpdateKPI(c context.Context, id int64) (err error) {
if _, err = d.db.Exec(c, _updateKPISQL, id); err != nil {
log.Error("d.UpdateKPI err(%v)", err)
}
return
}
// UpdateKPIPendentStatus update blocked_kpi status to st.
func (d *Dao) UpdateKPIPendentStatus(c context.Context, id int64) (err error) {
if _, err = d.db.Exec(c, _updateKPIPendentSQL, id); err != nil {
log.Error("d.UpdatePendentStatus err(%v)", err)
}
return
}
// UpdateKPIHandlerStatus update blocked_kpi handler status.
func (d *Dao) UpdateKPIHandlerStatus(c context.Context, id int64) (err error) {
if _, err = d.db.Exec(c, _updateKPIHandlerSQL, id); err != nil {
log.Error("d.UpdatePendentStatus err(%v)", err)
}
return
}
// UpdateCase update case status to st.
func (d *Dao) UpdateCase(c context.Context, st, jt, id int64) (err error) {
if _, err = d.db.Exec(c, _updateCaseSQL, st, jt, id); err != nil {
log.Error("d.UpdateCase err(%v)", err)
}
return
}
// InvalidJury set jury invalid.
func (d *Dao) InvalidJury(c context.Context, reason, mid int64) (err error) {
if _, err = d.db.Exec(c, _invalidJurySQL, reason, mid); err != nil {
log.Error("d.InvalidJury err(%v)", err)
}
return
}
// UpdateVoteRight update vote total and vote right.
func (d *Dao) UpdateVoteRight(c context.Context, mid int64) (err error) {
if _, err = d.db.Exec(c, _updateVoteRightSQL, mid); err != nil {
log.Error("d.UpdateVoteRight err(%v)", err)
}
return
}
// UpdateVoteTotal update vote total.
func (d *Dao) UpdateVoteTotal(c context.Context, mid int64) (err error) {
if _, err = d.db.Exec(c, _updateVoteTotalSQL, mid); err != nil {
log.Error("d.UpdateVoteTotal err(%v)", err)
}
return
}
// UpdatePunishResult update table blocked_case punish_result field =0
func (d *Dao) UpdatePunishResult(c context.Context, id int64, punishResult int8) (err error) {
if _, err = d.db.Exec(c, _updatePunishResultSQL, punishResult, id); err != nil {
log.Error("d.UpdatePunishResult err(%v)", err)
}
return
}
// KPIList get kpi list.
func (d *Dao) KPIList(c context.Context, day string) (res []model.Kpi, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _selKPISQL, day); err != nil {
log.Error("dao.KPIList error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := model.Kpi{}
if err = rows.Scan(&r.ID, &r.Mid, &r.Rate); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// KPIInfo get KPI info.
func (d *Dao) KPIInfo(c context.Context, id int64) (res model.Kpi, err error) {
row := d.db.QueryRow(c, _selKPIInfoSQL, id)
if err = row.Scan(&res.ID, &res.Mid, &res.HandlerStatus); err != nil {
log.Error("d.KPIInfo err(%v)", err)
}
return
}
// CaseByID get case info by id.
func (d *Dao) CaseByID(c context.Context, id int64) (res model.Case, err error) {
row := d.db.QueryRow(c, _selCaseByIDSQL, id)
if err = row.Scan(&res.ID, &res.Mid, &res.Status, &res.JudgeType, &res.RelationID); err != nil {
log.Error("d.BlockCount err(%v)", err)
}
return
}
// CountKPIRate count KPI rate<=4(C).
func (d *Dao) CountKPIRate(c context.Context, mid int64) (count int, err error) {
row := d.db.QueryRow(c, _countKPIRateSQL, mid)
if err = row.Scan(&count); err != nil {
log.Error("d.CountKPIRate(mid:%d) err(%v)", mid, err)
}
return
}

View File

@@ -0,0 +1,99 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_AddBlockInfo(t *testing.T) {
var (
r = model.BlockedInfo{}
)
r.OriginTitle = "go"
r.OriginURL = "http:go"
r.OriginType = 1
r.OriginContent = "goc"
r.OriginContentModify = "gocm"
r.BlockedDays = 1
r.BlockedForever = 1
r.BlockedType = 1
r.UID = 888890
r.OperatorName = "lgs"
r.PunishType = 3
r.ReasonType = 3
r.CaseID = 10
Convey("should return err be nil", t, func() {
_, err := d.AddBlockInfo(context.TODO(), &r, time.Now())
So(err, ShouldBeNil)
})
}
func Test_UpdateKPIPendentStatus(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateKPIPendentStatus(context.TODO(), 1)
So(err, ShouldBeNil)
})
}
func Test_UpdateKPIHandlerStatus(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateKPIHandlerStatus(context.TODO(), 1)
So(err, ShouldBeNil)
})
}
func Test_UpdateCase(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateCase(context.TODO(), model.CaseStatusDealed, model.JudgeTypeUndeal, 304)
So(err, ShouldBeNil)
})
}
func Test_InvalidJury(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.InvalidJury(context.TODO(), 1, 88889021)
So(err, ShouldBeNil)
})
}
func Test_UpdateVoteRight(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateVoteRight(context.TODO(), 88889021)
So(err, ShouldBeNil)
})
}
func Test_UpdateVoteTotal(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateVoteTotal(context.TODO(), 88889021)
So(err, ShouldBeNil)
})
}
func Test_UpdatePunishResult(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdatePunishResult(context.TODO(), 1, 6)
So(err, ShouldBeNil)
})
}
func Test_BlockCount(t *testing.T) {
Convey("should return err be nil and count>=0", t, func() {
count, err := d.CountBlocked(context.TODO(), 88889021, time.Now())
So(err, ShouldBeNil)
So(count, ShouldBeGreaterThanOrEqualTo, 0)
})
}
func TestDao_CaseByID(t *testing.T) {
Convey("should return err be nil & res not be nil", t, func() {
res, err := d.CaseByID(context.TODO(), 348)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,92 @@
package dao
import (
"context"
"fmt"
"strconv"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_opinion = "op_v2_" // user opinion prefix.
_labourIsAnswer = "labour_%d" // key of labourIsAnswer
_juryInfo = "jy_" // key of jury info
_caseVoteTop = "ca_vo_top_%d"
)
// user opinion key.
func opinionKey(opid int64) string {
return _opinion + strconv.FormatInt(opid, 10)
}
// labourKey.
func labourKey(mid int64) string {
return fmt.Sprintf(_labourIsAnswer, mid)
}
// user jury info key.
func juryInfoKey(mid int64) string {
return _juryInfo + strconv.FormatInt(mid, 10)
}
func caseVoteTopKey(mid int64) string {
return fmt.Sprintf(_caseVoteTop, mid)
}
// DelOpinionCache del opinion cache info.
func (d *Dao) DelOpinionCache(c context.Context, vid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(opinionKey(vid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d) error(%v)", vid, err)
}
return
}
// DelAnswerStateCache del answer state cache info.
func (d *Dao) DelAnswerStateCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(labourKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d) error(%v)", mid, err)
}
return
}
// DelJuryInfoCache del jury cache info.
func (d *Dao) DelJuryInfoCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(juryInfoKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d) error(%v)", mid, err)
}
return
}
// DelCaseVoteTopCache del case vote total cache.
func (d *Dao) DelCaseVoteTopCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(caseVoteTopKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%d) error(%v)", mid, err)
}
return
}

View File

@@ -0,0 +1,22 @@
package dao
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_DelOpinionCache(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.DelOpinionCache(context.TODO(), 27517340)
So(err, ShouldBeNil)
})
}
func TestDaoDelJuryInfoCache(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.DelJuryInfoCache(context.TODO(), 27517340)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"context"
"time"
"go-common/library/log"
)
const (
_updateJuryExpiredSQL = "UPDATE blocked_jury SET status=1, expired=? WHERE mid = ?"
_selConfSQL = "SELECT config_key,content FROM blocked_config"
)
// UpdateJuryExpired update jury expired.
func (d *Dao) UpdateJuryExpired(c context.Context, mid int64, expired time.Time) (err error) {
if _, err = d.db.Exec(c, _updateJuryExpiredSQL, expired, mid); err != nil {
log.Error("d.UpdateJuryExpired err(%v)", err)
}
return
}
// LoadConf load conf.
func (d *Dao) LoadConf(c context.Context) (cf map[string]string, err error) {
cf = make(map[string]string)
rows, err := d.db.Query(c, _selConfSQL)
if err != nil {
log.Error("d.loadConf err(%v)", err)
return
}
defer rows.Close()
var (
key string
value string
)
for rows.Next() {
if err = rows.Scan(&key, &value); err != nil {
log.Error("rows.Scan err(%v)", err)
continue
}
cf[key] = value
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func Test_UpdateJuryExpired(t *testing.T) {
Convey("should return err be nil", t, func() {
err := d.UpdateJuryExpired(context.TODO(), 88889017, time.Now())
So(err, ShouldBeNil)
})
}
func Test_LoadConf(t *testing.T) {
Convey("should return err be nil & map be nil", t, func() {
m, err := d.LoadConf(context.TODO())
So(err, ShouldBeNil)
So(m, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,182 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_voteOpIdx = "vo_%d_%d"
_caseOpIdx = "caseop_"
_blockIdx = "bl_%d_%d"
_grantCaseKey = "gr_ca_li_v2"
)
func voteIndexKey(cid int64, otype int8) string {
return fmt.Sprintf(_voteOpIdx, otype, cid)
}
func caseIndexKey(cid int64) string {
return _caseOpIdx + strconv.FormatInt(cid, 10)
}
func blockIndexKey(otype, btype int64) string {
return fmt.Sprintf(_blockIdx, otype, btype)
}
// DelCaseIdx DEL case opinion idx.
func (d *Dao) DelCaseIdx(c context.Context, cid int64) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
if _, err = conn.Do("DEL", caseIndexKey(cid)); err != nil {
log.Error("del case idx err(%v)", err)
return
}
return
}
// DelBlockedInfoIdx ZREM block info idx.
func (d *Dao) DelBlockedInfoIdx(c context.Context, bl *model.BlockedInfo) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
conn.Send("ZREM", blockIndexKey(bl.OriginType, bl.BlockedType), bl.ID)
conn.Send("ZREM", blockIndexKey(0, -1), bl.ID)
conn.Send("ZREM", blockIndexKey(0, bl.BlockedType), bl.ID)
conn.Send("ZREM", blockIndexKey(bl.OriginType, -1), bl.ID)
if err = conn.Flush(); err != nil {
log.Error("conn.Flush err(%v)", err)
return
}
for i := 0; i < 4; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
}
}
return
}
// AddBlockInfoIdx ZADD block info idx.
func (d *Dao) AddBlockInfoIdx(c context.Context, bl *model.BlockedInfo) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
var mtime time.Time
if mtime, err = time.ParseInLocation("2006-01-02 15:04:05", bl.MTime, time.Local); err != nil {
log.Error("time.ParseInLocation err(%v)", err)
return
}
conn.Send("ZADD", blockIndexKey(bl.OriginType, bl.BlockedType), mtime.Unix(), bl.ID)
conn.Send("ZADD", blockIndexKey(0, -1), mtime.Unix(), bl.ID)
conn.Send("ZADD", blockIndexKey(0, bl.BlockedType), mtime.Unix(), bl.ID)
conn.Send("ZADD", blockIndexKey(bl.OriginType, -1), mtime.Unix(), bl.ID)
if err = conn.Flush(); err != nil {
log.Error("conn.Flush err(%v)", err)
return
}
for i := 0; i < 4; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
}
}
return
}
// DelVoteIdx DEL case opinion idx.
func (d *Dao) DelVoteIdx(c context.Context, cid int64) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", voteIndexKey(cid, 1)); err != nil {
log.Error("del case idx err(%v)", err)
return
}
if err = conn.Send("DEL", voteIndexKey(cid, 2)); err != nil {
log.Error("del case idx err(%v)", err)
return
}
conn.Flush()
for i := 0; i < 2; i++ {
conn.Receive()
}
return
}
// SetGrantCase set grant case ids.
func (d *Dao) SetGrantCase(c context.Context, mcases map[int64]*model.SimCase) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
args := redis.Args{}.Add(_grantCaseKey)
for cid, mcase := range mcases {
var bs []byte
bs, err = json.Marshal(mcase)
if err != nil {
log.Error("json.Marshal(%+v) error(%v)", mcase, err)
err = nil
continue
}
args = args.Add(cid).Add(string(bs))
}
if _, err = conn.Do("HMSET", args...); err != nil {
log.Error("conn.Send(HMSET,%v) error(%v)", args, err)
}
return
}
// DelGrantCase del grant case id.
func (d *Dao) DelGrantCase(c context.Context, cids []int64) (err error) {
var args = []interface{}{_grantCaseKey}
conn := d.redis.Get(c)
defer conn.Close()
for _, cid := range cids {
args = append(args, cid)
}
if _, err = conn.Do("HDEL", args...); err != nil {
log.Error("conn.Send(HDEL,%s) err(%v)", _grantCaseKey, err)
}
return
}
// TotalGrantCase get length of grant case ids.
func (d *Dao) TotalGrantCase(c context.Context) (count int, err error) {
conn := d.redis.Get(c)
defer conn.Close()
if count, err = redis.Int(conn.Do("HLEN", _grantCaseKey)); err != nil {
if err != redis.ErrNil {
log.Error("conn.Do(HLEN, %s) error(%v)", _grantCaseKey, err)
return
}
err = nil
}
return
}
// GrantCases get granting case cids.
func (d *Dao) GrantCases(c context.Context) (cids []int64, err error) {
conn := d.redis.Get(c)
defer conn.Close()
var ms map[string]string
if ms, err = redis.StringMap(conn.Do("HGETALL", _grantCaseKey)); err != nil {
if err == redis.ErrNil {
err = nil
}
return
}
for m, s := range ms {
if s == "" {
continue
}
cid, err := strconv.ParseInt(m, 10, 64)
if err != nil {
log.Error("strconv.ParseInt(%s) error(%v)", m, err)
err = nil
continue
}
cids = append(cids, cid)
}
return
}

View File

@@ -0,0 +1,174 @@
package dao
import (
"context"
"go-common/app/job/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaovoteIndexKey(t *testing.T) {
convey.Convey("voteIndexKey", t, func(ctx convey.C) {
var (
cid = int64(1)
otype = int8(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := voteIndexKey(cid, otype)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocaseIndexKey(t *testing.T) {
convey.Convey("caseIndexKey", t, func(ctx convey.C) {
var (
cid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := caseIndexKey(cid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoblockIndexKey(t *testing.T) {
convey.Convey("blockIndexKey", t, func(ctx convey.C) {
var (
otype = int64(1)
btype = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := blockIndexKey(otype, btype)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCaseIdx(t *testing.T) {
convey.Convey("DelCaseIdx", t, func(ctx convey.C) {
var (
c = context.Background()
cid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelCaseIdx(c, cid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelBlockedInfoIdx(t *testing.T) {
convey.Convey("DelBlockedInfoIdx", t, func(ctx convey.C) {
var (
c = context.Background()
bl = &model.BlockedInfo{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelBlockedInfoIdx(c, bl)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddBlockInfoIdx(t *testing.T) {
convey.Convey("AddBlockInfoIdx", t, func(ctx convey.C) {
var (
c = context.Background()
bl = &model.BlockedInfo{MTime: "2018-11-14 00:00:00"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddBlockInfoIdx(c, bl)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelVoteIdx(t *testing.T) {
convey.Convey("DelVoteIdx", t, func(ctx convey.C) {
var (
c = context.Background()
cid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelVoteIdx(c, cid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetGrantCase(t *testing.T) {
convey.Convey("SetGrantCase", t, func(ctx convey.C) {
var (
c = context.Background()
mcases = make(map[int64]*model.SimCase)
)
mcases[1] = &model.SimCase{}
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetGrantCase(c, mcases)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelGrantCase(t *testing.T) {
convey.Convey("DelGrantCase", t, func(ctx convey.C) {
var (
c = context.Background()
cids = []int64{1, 2}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelGrantCase(c, cids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTotalGrantCase(t *testing.T) {
convey.Convey("TotalGrantCase", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.TotalGrantCase(c)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGrantCases(t *testing.T) {
convey.Convey("GrantCases", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GrantCases(c)
ctx.Convey("Then err should be nil.cids should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
// ctx.So(cids, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,83 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/library/ecode"
"go-common/library/log"
)
// RegReply del reply.
func (d *Dao) RegReply(c context.Context, id int64, tid int8) (err error) {
params := url.Values{}
params.Set("oid", strconv.FormatInt(id, 10))
params.Set("mid", "0")
params.Set("type", strconv.FormatInt(int64(tid), 10))
var res struct {
Code int `json:"code"`
}
for i := 0; i <= 10; i++ {
if err = d.client.Post(c, d.regReplyURL, "", params, &res); err != nil {
log.Error("d.regReplyURL url(%s) res(%v) error(%v)", d.regReplyURL+"?"+params.Encode(), res, err)
continue
}
if res.Code != ecode.OK.Code() && res.Code != ecode.ReplySubjectExist.Code() {
log.Error("d.regReplyURL code(%v) url(%s)", res.Code, d.regReplyURL+"?"+params.Encode())
continue
}
log.Info("d.regReplyURL url(%s) res(%v)", d.regReplyURL+"?"+params.Encode(), res)
return
}
return
}
// DelReply del reply.
func (d *Dao) DelReply(c context.Context, rpid, tp, oid string) (err error) {
params := url.Values{}
params.Set("oid", oid)
params.Set("rpid", rpid)
params.Set("type", tp)
params.Set("adid", "-1")
params.Set("notify", "false")
params.Set("moral", "0")
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.delReplyURL, "", params, &res); err != nil {
log.Error("d.delReplyURL url(%s) res(%v) error(%v)", d.delReplyURL+"?"+params.Encode(), res, err)
return
}
if res.Code != 0 {
log.Error("d.delReplyURL url(%s) code(%d)", d.delReplyURL+"?"+params.Encode(), res.Code)
}
log.Info("d.delReplyURL url(%s) res(%v)", d.delReplyURL+"?"+params.Encode(), res)
return
}
// UpReplyState update reply state.
func (d *Dao) UpReplyState(c context.Context, oid, rpid int64, tp, state int8) (err error) {
params := url.Values{}
params.Set("oid", strconv.FormatInt(oid, 10))
params.Set("rpid", strconv.FormatInt(rpid, 10))
params.Set("type", strconv.FormatInt(int64(tp), 10))
params.Set("state", strconv.FormatInt(int64(state), 10))
params.Set("adid", "0")
var res struct {
Code int `json:"code"`
}
for i := 0; i <= 10; i++ {
if err = d.client.Post(c, d.upReplyStateURL, "", params, &res); err != nil {
log.Error("d.upReplyStateURL url(%s) res(%v) error(%v)", d.upReplyStateURL+"?"+params.Encode(), res, err)
continue
}
if res.Code != 0 {
log.Error("d.upReplyStateURL url(%s) code(%d)", d.upReplyStateURL+"?"+params.Encode(), res.Code)
continue
}
log.Info("d.upReplyStateURL url(%s) res(%v)", d.upReplyStateURL+"?"+params.Encode(), res)
return
}
return
}

View File

@@ -0,0 +1,59 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoRegReply(t *testing.T) {
convey.Convey("RegReply", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(1)
tid = int8(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.RegReply(c, id, tid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelReply(t *testing.T) {
convey.Convey("DelReply", t, func(ctx convey.C) {
var (
c = context.Background()
rpid = ""
tp = ""
oid = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelReply(c, rpid, tp, oid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpReplyState(t *testing.T) {
convey.Convey("UpReplyState", t, func(ctx convey.C) {
var (
c = context.Background()
oid = int64(0)
rpid = int64(0)
tp = int8(0)
state = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpReplyState(c, oid, rpid, tp, state)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}