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

21
app/job/main/credit/BUILD Normal file
View File

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

View File

@@ -0,0 +1,259 @@
### credit项目的Job用于清理缓存等。
##### Version 1.16.4
> 1.fix service close panic
##### Version 1.16.3
> 1.新增通知举报平台移交仲裁案件状态为移交仲裁接口
##### Version 1.16.2
> 1.增加封禁类型(恶意冒充他人)
##### Version 1.16.1
> 1.勋章发放使用新接口
##### Version 1.16.0
> 1.使用member-service的block的接口
##### Version 1.15.1
> 1. mc 空key删cache日志不清真
##### Version 1.15.0
> 1.风纪委缓存优化
##### Version 1.14.2
> 1.劳改是否答题增加缓存
##### Version 1.14.1
> 1.close 异常panic
##### Version 1.14.0
> 1.异常案件发放监控处理
##### Version 1.13.2
> 1.新增动态、相簿、小视频类封禁
##### Version 1.13.1
> 1.change block msg
##### Version 1.13.0
> 1.http to bm
##### Version 1.12.6
> 1.产品变动小黑屋封禁理由
##### Version 1.12.5
> 1.add reason code (28、29)
##### Version 1.12.4
> 1.add reason code (27)
##### Version 1.12.3
> 1. 观点换key
##### Version 1.12.2
> 1. 理由变更变更日志不幂等
##### Version 1.12.1
> 1. fix 参数类型错误bug
##### Version 1.12.0
> 1.小黑屋异步封禁和解禁
> 2.劳改答题状态同步
##### Version 1.11.0
> 1.众裁举报理由变更
> 2.风纪委kpi使用新的硬币接口
##### Version 1.10.4
> 1.修复conf bug
##### Version 1.10.3
> 1.删除 “发布色情低俗信息”
> 2.新增 “破坏网络安全”、“发布虚假误导信息”
##### Version 1.10.2
> 1. 更新“发布怂恿教唆信息”为“发布不适宜内容”
> 2. 新增“发布青少年不良内容”
##### Version 1.10.1
> 1.勋章添加重试
##### Version 1.10.0
> 1.自动移交被举报人去重
##### Version 1.9.3
> 1.不通过账号发封禁系统消息,应用程序发
##### Version 1.9.2
> 1. 去除老java删除cache的接口
##### Version 1.9.1
> 1. 挂件使用新接口
##### Version 1.9.0
> 1. 自动移交接入屏蔽词系统
##### Version 1.8.7
> 1. update CONTRIBUTORS.md
##### Version 1.8.6
> 1. 封禁保护
##### Version 1.8.5
> 1. add goconvey test
##### Version 1.8.4
> 1. 风纪委员奖励增加硬币礼包
##### Version 1.8.3
> 1. select db result not nil judge
##### Version 1.8.2
> 1. db result not nil judge
##### Version 1.8.1
> 1. fix_bug
##### Version 1.8.0
> 1.评论自动案件移交
##### Version 1.7.6
> 1.fix update total && right slow log && fix bug
##### Version 1.7.5
> 1.fix update total && right slow log
##### Version 1.7.4
> 1.代码优化
##### Version 1.7.3
> 1.binlog 处理封禁,失效风纪委员
##### Version 1.7.2
> 1.blockinfo 缓存更新优化
##### Version 1.7.1
> 1.封禁添加操作者id
##### Version 1.7.0
> 1.支持publish的status字段
> 2.支持info的status字段
##### Version 1.6.9
> 1.修改reason_type
> 2.添加公告注册评论重试
##### Version 1.6.8
> 1.新增大众仲裁逻辑
> 2.删除队列中获取案件cache
##### Version 1.6.7
> 1.修改reason_type
##### Version 1.6.6
> 1.业务整理
##### Version 1.6.5
> 1.注释删除观点发系统消息逻辑
##### Version 1.6.4
> 1.指针没有初始化报错
##### Version 1.6.3
> 1.db查询为空时不产生err信息
##### Version 1.6.2
> 1.消费binlog,删除观点发送系统消息
##### Version 1.6.1
> 1.添加job的load日志
> 2.添加清除队列的日志
##### Version 1.6.0
> 1.风纪委获取case逻辑变更
> 2.评论注册的错误http-client日志
##### Version 1.5.12
> 1.fix DelBlockedListIdx bug
##### Version 1.5.11
> 1.reduce moral
> 2.edit judge
> 3.edit Host URL
##### Version 1.5.11
> 1.reduce moral
> 2.edit judge
> 3.edit Host URL
##### Version 1.5.10
> 1.fix caselist cache bug
##### Version 1.5.9
> 1.credit blocked_case add reply type id
##### Version 1.5.8
> 1.credit blocked_case add reply
> 2.reply add 重试
##### Version 1.5.7
> 1.credit 3.0
##### Version 1.5.6
> 1.job add prom
##### Version 1.5.5
> 1.风纪委 发放勋章
##### Version 1.5.4
> 1.风纪委 发放新挂件
##### Version 1.5.1
> 1.风纪委 仅删除发通知消息
##### Version 1.5.0
> 1.jury2.2.0
##### Version 1.4.0
> 1.小黑板
##### Version 1.3.0
> 1.风纪委公开裁决
##### Version 1.2.0
> 1.风纪委众议
##### Version 1.1.0
> databus消费幂等
> 1.结案服务幂等
> 2.KPI奖励和通知幂等
##### Version 1.0.5
> 1.风纪委绩效考核,发送挂件
##### Version 1.0.4
> 1.注册评论
##### Version 1.0.1
> 1.兼容时间格式解析
##### Version 1.0.0
> 1.版本初始化
> 2.异步清缓存结案封禁用户

View File

@@ -0,0 +1,16 @@
# Owner
zhaogangtao
wanghuan01
zhoujiahui
# Author
wangyuzhe
hejianbing
liangguangsheng
# Reviewer
zhaogangtao
hejianbing
wangyuzhe
xiequan
lintanghui

View File

@@ -0,0 +1,22 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- hejianbing
- liangguangsheng
- wanghuan01
- wangyuzhe
- zhaogangtao
- zhoujiahui
labels:
- job
- job/main/credit
- main
options:
no_parent_owners: true
reviewers:
- hejianbing
- liangguangsheng
- lintanghui
- wangyuzhe
- xiequan
- zhaogangtao

View File

@@ -0,0 +1,11 @@
#### credit job
##### 项目简介
> 1.消费credit产生databus消息等异步操作
##### 编译环境
> 请只用golang v1.7.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common

View File

@@ -0,0 +1,45 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = [
"convey-test.toml",
"credit-job-test.toml",
],
importpath = "go-common/app/job/main/credit/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/credit/conf:go_default_library",
"//app/job/main/credit/http:go_default_library",
"//app/job/main/credit/service: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,141 @@
# This is a TOML document. Boom.
version = "1.0.0"
[xlog]
dir = "/data/log/credit-job/"
[bm]
addr = "0.0.0.0:6335"
timeout = "1s"
[host]
apiCoURI = "http://api.bilibili.co"
accountCoURI = "http://account.bilibili.co"
msgCoURI = "http://message.bilibili.co"
[app]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
[databus]
[databus.creditDBSub]
key = "0QHEzXlXE9Ijewj8V4zu"
secret = "0QHEzXlXE9Ijewj8V4zv"
group = "BlockedBinlog-UGC-S"
topic = "Blocked-T"
action = "sub"
offset = "old"
buffer = 2048
name = "credit-job/credit-db-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[databus.replyAllSub]
key = "875d05ffa843e297"
secret = "24d052bae2247fc59ee925d46ffd61e2"
group = "Reply-MainAccountLaw-S"
topic = "Reply-T"
action = "sub"
offset = "old"
buffer = 2048
name = "credit-job/reply-all-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[databus.labourSub]
key = "875d05ffa843e297"
secret = "24d052bae2247fc59ee925d46ffd61e2"
group = "Credit-MainAccountLaw-P"
topic = "Credit-T"
action = "pub"
offset = "new"
buffer = 2048
name = "credit-job/labour-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[rpcClient]
[rpcClient.archive]
timeout = "1s"
[rpcClient.member]
timeout = "1s"
[httpClient]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
dial = "100ms"
timeout = "1s"
keepAlive = "60s"
[httpClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[mysql]
addr = "172.16.33.205:3306"
dsn = "blocked:mUdFycLKSbvPgdE28lCveqN77SqsGOmy@tcp(172.16.33.205:3306)/blocked?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "1s"
execTimeout = "1s"
tranTimeout = "2s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[memcache]
name = "credit-job"
proto = "tcp"
# addr = "172.16.33.54:11211"
addr = "172.18.33.60:11219"
idle = 5
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "24h"
[redis]
name = "credit"
proto = "tcp"
# addr = "172.16.33.54:6379"
addr = "172.18.33.60:6893"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "720h"
[clearPath]
juryInfoCache = "http://blocked.bilibili.co/x/credit/cache/jury/del"
[judge]
confTimer="120s"
reservedTime="600s"

View File

@@ -0,0 +1,139 @@
# This is a TOML document. Boom.
version = "1.0.0"
[xlog]
dir = "/data/log/credit-job/"
[bm]
addr = "0.0.0.0:6335"
timeout = "1s"
[host]
apiCoURI = "http://api.bilibili.co"
accountCoURI = "http://account.bilibili.co"
msgCoURI = "http://message.bilibili.co"
[app]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
[databus]
[databus.creditDBSub]
key = "0QHEzXlXE9Ijewj8V4zu"
secret = "0QHEzXlXE9Ijewj8V4zv"
group = "BlockedBinlog-UGC-S"
topic = "Blocked-T"
action = "sub"
offset = "old"
buffer = 2048
name = "credit-job/credit-db-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[databus.replyAllSub]
key = "875d05ffa843e297"
secret = "24d052bae2247fc59ee925d46ffd61e2"
group = "Reply-MainAccountLaw-S"
topic = "Reply-T"
action = "sub"
offset = "old"
buffer = 2048
name = "credit-job/reply-all-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[databus.labourSub]
key = "875d05ffa843e297"
secret = "24d052bae2247fc59ee925d46ffd61e2"
group = "Credit-MainAccountLaw-P"
topic = "Credit-T"
action = "pub"
offset = "new"
buffer = 2048
name = "credit-job/labour-sub"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[rpcClient]
[rpcClient.archive]
timeout = "1s"
[rpcClient.member]
timeout = "1s"
[httpClient]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
dial = "100ms"
timeout = "1s"
keepAlive = "60s"
[httpClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[mysql]
addr = "172.16.33.205:3306"
dsn = "blocked:mUdFycLKSbvPgdE28lCveqN77SqsGOmy@tcp(172.16.33.205:3306)/blocked?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "1s"
execTimeout = "1s"
tranTimeout = "2s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[memcache]
name = "credit-job"
proto = "tcp"
addr = "172.16.33.54:11211"
idle = 5
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "24h"
[redis]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 100
active = 100
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "720h"
[clearPath]
juryInfoCache = "http://blocked.bilibili.co/x/credit/cache/jury/del"
[judge]
confTimer="120s"
reservedTime="600s"

View File

@@ -0,0 +1,49 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/job/main/credit/conf"
"go-common/app/job/main/credit/http"
"go-common/app/job/main/credit/service"
"go-common/library/log"
)
var (
srv *service.Service
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() error(%v)", err)
panic(err)
}
log.Init(conf.Conf.Xlog)
defer log.Close()
log.Info("credit-job start")
http.Init(conf.Conf)
signalHandler()
}
func signalHandler() {
var ch = make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
si := <-ch
switch si {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("get a signal %s, stop the consume process", si.String())
srv.Close()
time.Sleep(2 * time.Second)
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,40 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/job/main/credit/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/rpc:go_default_library",
"//library/queue/databus:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/BurntSushi/toml:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,167 @@
package conf
import (
"errors"
"flag"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
"go-common/library/database/sql"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/rpc"
"go-common/library/queue/databus"
"go-common/library/time"
"github.com/BurntSushi/toml"
)
// Conf global variable.
var (
Conf = &Config{}
client *conf.Client
confPath string
)
// Config struct of conf.
type Config struct {
// base
// host
Host *Host
// Env
Env string
// goroutine sleep
Tick time.Duration
// log
Xlog *log.Config
// databus
DataBus *DataBus
// bm service
BM *bm.ServerConfig
// httpClinet
HTTPClient *bm.ClientConfig
Mysql *sql.Config
Judge *Judge
Sms *Sms
Redis *Redis
Memcache *Memcache
// rpc client
RPCClient *RPC
}
// RPC rpc client config.
type RPC struct {
Archive *rpc.ClientConfig
Member *rpc.ClientConfig
}
// DataBus databus config.
type DataBus struct {
CreditDBSub *databus.Config
ReplyAllSub *databus.Config
LabourSub *databus.Config
}
// Host config host.
type Host struct {
APICoURI string
AccountCoURI string
MsgCoURI string
}
// Redis redis conf.
type Redis struct {
*redis.Config
Expire time.Duration
}
// Sms is sms monitor config.
type Sms struct {
Phone string
Token string
}
// Judge is judge config.
type Judge struct {
ConfTimer time.Duration // 定时load数据时间间隔
ReservedTime time.Duration // 结案前N分钟停止获取case
CaseGiveHours int64 // 案件发放时长
CaseCheckTime int64 // 单案审核时长
JuryRatio int64 // 投准率下限
JudgeRadio int64 // 判决阙值
CaseVoteMin int64 // 案件投票数下限
CaseObtainMax int64 // 每日获取案件数
CaseVoteMax int64 // 结案投票数
JuryApplyMax int64 // 每日发放风纪委上限
CaseLoadMax int // 案件发放最大队列数
CaseLoadSwitch int8 // 案件发放进入队列开关
CaseVoteMaxPercent int // 结案投票数的百分比
VoteNum
}
// VoteNum struct.
type VoteNum struct {
RateS int8 `json:"rate_s"`
RateA int8 `json:"rate_a"`
RateB int8 `json:"rate_b"`
RateC int8 `json:"rate_c"`
RateD int8 `json:"rate_d"`
}
// Memcache memcache.
type Memcache struct {
*memcache.Config
Expire time.Duration
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init create config instance.
func Init() (err error) {
if confPath != "" {
return local()
}
return remote()
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}

View File

@@ -0,0 +1,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)
})
})
})
}

View File

@@ -0,0 +1,34 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["http.go"],
importpath = "go-common/app/job/main/credit/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/credit/conf:go_default_library",
"//app/job/main/credit/service: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,42 @@
package http
import (
"net/http"
"go-common/app/job/main/credit/conf"
"go-common/app/job/main/credit/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
var svc *service.Service
// Init init
func Init(c *conf.Config) {
initService(c)
engineInner := bm.NewServer(c.BM)
// init inner router
innerRouter(engineInner)
if err := engineInner.Start(); err != nil {
log.Error("engineInner.Start() error(%v)", err)
panic(err)
}
}
// initService init services.
func initService(c *conf.Config) {
svc = service.New(c)
}
// innerRouter init local router api path.
func innerRouter(e *bm.Engine) {
//init api
e.Ping(ping)
}
func ping(c *bm.Context) {
if err := svc.Ping(c); err != nil {
log.Error("credit-job ping error")
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,38 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"blocked.go",
"case.go",
"credit.go",
"credit_state.go",
"jury.go",
"kpi.go",
"message.go",
"reply.go",
],
importpath = "go-common/app/job/main/credit/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["//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,19 @@
package model
import xtime "go-common/library/time"
// BlockAndMoralStatus blocked status and moral.
type BlockAndMoralStatus struct {
MID int64 `json:"mid"`
Status int8 `json:"status"`
STime xtime.Time `json:"start_time"`
ETime xtime.Time `json:"end_time"`
}
// BlockLabourAnswerLog .
type BlockLabourAnswerLog struct {
ID int64 `json:"id"`
MID int64 `json:"mid"`
Score int8 `json:"score"`
CTime string `json:"ctime"`
}

View File

@@ -0,0 +1,10 @@
package model
// CaseApplyModifyLog .
type CaseApplyModifyLog struct {
CID int64 `json:"case_id"`
AType int8 `json:"apply_type"`
OReason int8 `json:"origin_reason"`
AReason int8 `json:"apply_reason"`
Num int
}

View File

@@ -0,0 +1,33 @@
package model
import (
"encoding/json"
xtime "go-common/library/time"
)
// Message is simple message struct info.
type Message struct {
Action string `json:"action"`
Table string `json:"table"`
New json.RawMessage `json:"new"`
Old json.RawMessage `json:"old"`
}
// CreditInfo is simple creditInfo struct info.
type CreditInfo struct {
Mid int64 `json:"mid"`
Status int64 `json:"status"`
PunishType int64 `json:"punishType"`
PunishEnd xtime.Time `json:"punishEnd"`
CTime xtime.Time `json:"-"`
MTime xtime.Time `json:"-"`
}
// AutoCaseConf struct
type AutoCaseConf struct {
Reasons map[int8]struct{}
ReasonStr string
ReportScore int
Likes int
}

View File

@@ -0,0 +1,365 @@
package model
import (
"fmt"
)
// blocked const
const (
// item type
BUSSINESS = "credit-job"
// deal bussinss time type
DealTimeTypeNone = int8(0)
DealTimeTypeDay = int8(1)
DealTimeTypeYear = int8(2)
// default time
DefaultTime = "1979-12-31 16:00:00"
TimeFormatSec = "2006-01-02 15:04:05"
// Case Status
CaseStatusGranting = 1 // 发放中
CaseStatusGrantStop = 2 // 停止发放
CaseStatusDealing = 3 // 结案中
CaseStatusDealed = 4 // 已裁决
CaseStatusRestart = 5 // 待重启
CaseStatusUndealed = 6 // 未裁决
CaseStatusFreeze = 7 // 冻结中
CaseStatusQueueing = 8 // 队列中
// Judge Status.
JudgeTypeUndeal = 0 // 未裁决
JudgeTypeViolate = 1 // 违规
JudgeTypeLegal = 2 // 未违规
// Vote Status.
VoteTypeUndo = 0 // 未投票
VoteTypeViolate = 1 // 违规-封禁
VoteTypeDelete = 4 // 违规-删除
VoteTypeLegal = 2 // 不违规
VoteTypeGiveUp = 3 // 放弃投票
// punish type.
PunishTypeMoral = int8(1)
PunishTypeBlock = int8(2)
PunishTypeForever = int8(3)
// blocked_info blocked_forever
NotInBlockedForever = int8(0)
InBlockedForever = int8(1)
// Block Time.
Punish3Days = 1
Punish7Days = 2
PunishForever = 3
PunishCustom = 4
Punish15Days = 5
PunishBlock = 0
PunishJury = 1
// origin_type.
OriginReply = int8(1) // 评论
OriginDM = int8(2) // 弹幕
OriginMsg = int8(3) // 私信
OriginTag = int8(4) // 标签
OriginMember = int8(5) // 个人资料
OriginArchive = int8(6) // 投稿
OriginMusic = int8(7) // 音频
OriginArticle = int8(8) // 专栏
OriginSpaceTop = int8(9) // 空间头图
OriginDsynamic = int8(10) // 动态
OriginPhoto = int8(11) // 相册
OriginMinVideo = int8(12) // 小视频
// Jury Invalid
JuryBlocked = 1
JuryExpire = 2
JuryAdmin = 3
// Case Load Switch
StateCaseLoadClose = int8(0)
StateCaseLoadOpen = int8(1)
// Blocked Opinio State
OpinionStateOpen = int8(0)
OpinionStateClose = int8(1)
OpinionStateCloseAndMsg = int8(2)
// blocked_jury.case_type
JudeCaseTypePrivate = int8(0) // 小众众裁
JudeCaseTypePublic = int8(1) // 大众众裁
// Reply regist type.
ReplyBlocked = int8(6)
ReplyPublish = int8(7)
ReplyCase = int8(15)
// blocked_publish.publish_status
PublishClose = int8(0)
PublishOpen = int8(1)
// status
StatusClose = int8(1)
StatusOpen = int8(0)
// blocked_case.punish_result
BlockNone = int8(0)
Block3Days = int8(1)
Block7Days = int8(2)
BlockForever = int8(3)
BlockCustom = int8(4)
Block15Days = int8(5)
BlockOnlyDel = int8(6)
// block time
BlockTimeForever = 0 // 永久封禁
BlockTimeThree = 3 // 3天封禁
BlockTimeSeven = 7 // 7天封禁
BlockTimeFifteen = 15 // 15天封禁
// reasonType
ReasonOtherType = int8(0)
ReasonBrushScreen = int8(1)
ReasonGrabFloor = int8(2)
ReasonGamblingFraud = int8(4)
ReasonProhibited = int8(5)
ReasonGarbageAds = int8(6)
ReasonPersonalAttacks = int8(7)
ReasonViolatePrivacy = int8(8)
ReasonLeadBattle = int8(9)
ReasonSpoiler = int8(10)
ReasonAddUnrelatedTags = int8(11)
ReasonDelOtherTags = int8(12)
ReasonPornographic = int8(13)
ReasonVulgar = int8(14)
ReasonBloodyViolence = int8(15)
ReasonAnimusVideoUp = int8(16)
ReasonIllegalWebsite = int8(17)
ReasonSpreadErrinfo = int8(18)
ReasonAbettingEncouragement = int8(19)
ReasonAnimusBrushScreen = int8(20)
ReasonAccountViolation = int8(21)
ReasonMaliciousPlagiarism = int8(22)
ReasonPosingAsHomemade = int8(23)
ReasonPostTeenBadContent = int8(24)
ReasonDestroyCyberSecurity = int8(25)
ReasonPostingMisleadingInfo = int8(26)
ReasonCounterfeitOfficialAuth = int8(27)
ReasonPublishInappropriateContent = int8(28)
ReasonViolationOperatingRules = int8(29)
ReasonIllegalCreateTopic = int8(30)
ReasonIllegalDrawLottery = int8(31)
ReasonIllegalFakeMan = int8(32)
// reply reasonType
ReplyReasonOtherType = int8(0)
ReplyReasonGarbageAds = int8(1)
ReplyReasonPornographic = int8(2)
ReplyReasonAnimusBrushScreen = int8(3)
ReplyReasonLeadBattle = int8(4)
ReplyReasonSpoiler = int8(5)
ReplyReasonPolitical = int8(6)
ReplyReasonPersonalAttacks = int8(7)
ReplyReasonIrrelevantVideo = int8(8)
ReplyReasonProhibited = int8(9)
ReplyReasonVulgar = int8(10)
ReplyReasonIllegalWebsite = int8(11)
ReplyReasonGamblingFraud = int8(12)
ReplyReasonSpreadErrinfo = int8(13)
ReplyReasonAbettingEncouragement = int8(14)
ReplyReasonViolatePrivacy = int8(15)
ReplyReasonGrabFloor = int8(16)
ReplyReasonPostTeenBadContent = int8(17)
// tag reasonType
TagReasonAddUnrelatedTags = int8(1)
TagReasonProhibited = int8(2)
TagReasonPersonalAttacks = int8(3)
TagReasonSpoiler = int8(4)
TagReasonDelOtherTags = int8(5)
// moral originType
MoralOriginDM = int8(1)
MoralOriginReply = int8(2)
MoralOriginTag = int8(3)
// block status
BlockStatusNone = int8(0)
BlockStatusForever = int8(1)
BlockStatusOn = int8(2)
// defealt deduct moral val
DefealtMoralVal = -10
// dm notify status
DMNotifyNotDel = 0
DMNotifyDel = 1
// msg content
_dealMsgTitle = "%s违规处理通知"
_dealMsgContent = `您好,根据用户举报与风纪委众裁,您在#{"%s"}{%s}下的%s 『%s』已被移除。请自觉遵守国家相关法律法规及《社区规则》bilibili良好的社区氛围需要大家一起维护
其中《社区规则》为可点击超链接地址https://www.bilibili.com/blackboard/blackroom.html`
// moral remark
MoralRemark = "违规惩罚"
)
var (
_punishType = map[int8]string{
PunishTypeMoral: "节操",
PunishTypeBlock: "封禁",
PunishTypeForever: "永久封禁",
}
_reasonType = map[int8]string{
ReasonOtherType: "其他",
ReasonBrushScreen: "刷屏",
ReasonGrabFloor: "抢楼",
ReasonGamblingFraud: "发布赌博诈骗信息",
ReasonProhibited: "发布违禁相关信息",
ReasonGarbageAds: "发布垃圾广告信息",
ReasonPersonalAttacks: "发布人身攻击言论",
ReasonViolatePrivacy: "发布侵犯他人隐私信息",
ReasonLeadBattle: "发布引战言论",
ReasonSpoiler: "发布剧透信息",
ReasonAddUnrelatedTags: "恶意添加无关标签",
ReasonDelOtherTags: "恶意删除他人标签",
ReasonPornographic: "发布色情信息",
ReasonVulgar: "发布低俗信息",
ReasonBloodyViolence: "发布暴力血腥信息",
ReasonAnimusVideoUp: "涉及恶意投稿行为",
ReasonIllegalWebsite: "发布非法网站信息",
ReasonSpreadErrinfo: "发布传播不实信息",
ReasonAbettingEncouragement: "发布怂恿教唆信息",
ReasonAnimusBrushScreen: "恶意刷屏",
ReasonAccountViolation: "账号违规",
ReasonMaliciousPlagiarism: "恶意抄袭",
ReasonPosingAsHomemade: "冒充自制原创",
ReasonPostTeenBadContent: "发布青少年不良内容",
ReasonDestroyCyberSecurity: "破坏网络安全",
ReasonPostingMisleadingInfo: "发布虚假误导信息",
ReasonCounterfeitOfficialAuth: "仿冒官方认证账号",
ReasonPublishInappropriateContent: "发布不适宜内容",
ReasonViolationOperatingRules: "违反运营规则",
ReasonIllegalCreateTopic: "恶意创建话题",
ReasonIllegalDrawLottery: "发布违规抽奖",
ReasonIllegalFakeMan: "恶意冒充他人",
}
_originType = map[int8]string{
OriginReply: "评论",
OriginDM: "弹幕",
OriginMsg: "私信",
OriginTag: "标签",
OriginMember: "个人资料",
OriginArchive: "投稿",
OriginMusic: "音频",
OriginArticle: "专栏",
OriginSpaceTop: "空间头图",
OriginDsynamic: "动态",
OriginPhoto: "相册",
OriginMinVideo: "小视频",
}
_reasonToFreeze = map[int8]bool{
ReasonGamblingFraud: true,
ReasonViolatePrivacy: true,
ReasonProhibited: true,
ReasonPornographic: true,
ReasonVulgar: true,
ReasonSpoiler: false,
ReasonGrabFloor: false,
ReasonGarbageAds: false,
ReasonLeadBattle: false,
ReasonBrushScreen: false,
ReasonPersonalAttacks: false,
}
_replyReasonType = map[int8]int8{
ReplyReasonOtherType: ReasonOtherType,
ReplyReasonGarbageAds: ReasonGarbageAds,
ReplyReasonPornographic: ReasonPornographic,
ReplyReasonAnimusBrushScreen: ReasonAnimusBrushScreen,
ReplyReasonLeadBattle: ReasonLeadBattle,
ReplyReasonSpoiler: ReasonSpoiler,
ReplyReasonPolitical: ReasonOtherType,
ReplyReasonPersonalAttacks: ReasonPersonalAttacks,
ReplyReasonIrrelevantVideo: ReasonOtherType,
ReplyReasonProhibited: ReasonProhibited,
ReplyReasonVulgar: ReasonVulgar,
ReplyReasonIllegalWebsite: ReasonIllegalWebsite,
ReplyReasonGamblingFraud: ReasonGamblingFraud,
ReplyReasonSpreadErrinfo: ReasonSpreadErrinfo,
ReplyReasonAbettingEncouragement: ReasonAbettingEncouragement,
ReplyReasonViolatePrivacy: ReasonViolatePrivacy,
ReplyReasonGrabFloor: ReasonGrabFloor,
ReplyReasonPostTeenBadContent: ReasonPostTeenBadContent,
}
_tagReasonType = map[int8]int8{
TagReasonAddUnrelatedTags: ReasonAddUnrelatedTags,
TagReasonProhibited: ReasonProhibited,
TagReasonPersonalAttacks: ReasonPersonalAttacks,
TagReasonSpoiler: ReasonSpoiler,
TagReasonDelOtherTags: ReasonDelOtherTags,
}
// _orginMoralType 对应节操来源类型
_orginMoralType = map[int8]int8{
OriginReply: MoralOriginReply,
OriginDM: MoralOriginDM,
OriginTag: MoralOriginTag,
}
_blockDay = map[int8]string{
BlockTimeForever: "永久封禁",
BlockTimeThree: "封禁3天",
BlockTimeSeven: "封禁7天",
BlockTimeFifteen: "封禁15天",
}
)
// ReasonToFreeze get reason yes or no to freeze.
func ReasonToFreeze(reasonType int8) bool {
return _reasonToFreeze[reasonType]
}
// OrginMoralType get moral bussiness Type by blocked orgin.
func OrginMoralType(blockOrginType int8) int8 {
return _orginMoralType[blockOrginType]
}
// PunishTypeDesc get punishType desc
func PunishTypeDesc(punishType int8) string {
return _punishType[punishType]
}
// ReasonTypeDesc get reasonType desc
func ReasonTypeDesc(reasonType int8) string {
return _reasonType[reasonType]
}
// OriginTypeDesc get originType desc
func OriginTypeDesc(originType int8) string {
return _originType[originType]
}
// BlockedDayDesc is blocked day desc
func BlockedDayDesc(day int8) string {
return _blockDay[day]
}
// BlockedReasonTypeByReply get blocked reason type.
func BlockedReasonTypeByReply(replyReasonType int8) int8 {
return _replyReasonType[replyReasonType]
}
// BlockedReasonTypeByTag get blocked reason type.
func BlockedReasonTypeByTag(tagReasonType int8) int8 {
return _tagReasonType[tagReasonType]
}
// OriginMsgContent get msg content by oTitle, oURL , oContent and oType
func OriginMsgContent(oTitle, oURL, oContent string, oType int8) (msgTitle, msgCon string) {
msgTitle = fmt.Sprintf(_dealMsgTitle, _originType[oType])
msgCon = fmt.Sprintf(_dealMsgContent, oTitle, oURL, _originType[oType], oContent)
return
}

View File

@@ -0,0 +1,164 @@
package model
import (
xtime "go-common/library/time"
)
// Case is jury case info.
type Case struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Status int64 `json:"status"`
Origin
JudgeType int64 `json:"judge_type"`
PunishResult int64 `json:"punish_result"`
Agree int64 `json:"vote_rule"`
Against int64 `json:"vote_break"`
VoteDelete int64 `json:"vote_delete"`
PunishStatus int64 `json:"pubish_status"`
BlockedDay int64 `json:"blocked_days"`
RelationID string `json:"relation_id"`
Operator string `json:"operator"`
PutTotal int64 `json:"put_total"`
Stime string `json:"start_time"`
Etime string `json:"end_time"`
Ctime string `json:"ctime"`
CaseType int8 `json:"case_type"`
OPID int64 `json:"oper_id"`
BusinessTime string `json:"business_time"`
BCtime xtime.Time
}
// Publish is blocked_publish info.
type Publish struct {
ID int64 `json:"id"`
Title string `json:"title"`
Subtitle string `json:"sub_title"`
PStatus int8 `json:"publish_status"`
SStatus int8 `json:"stick_status"`
Content string `json:"content"`
URL string `json:"url"`
PType int8 `json:"ptype"`
STime string `json:"show_time"`
}
// SimCase is simple case struct info.
type SimCase struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
VoteRule int64 `json:"vote_rule"`
VoteBreak int64 `json:"vote_break"`
VoteDelete int64 `json:"vote_delete"`
CaseType int8 `json:"case_type"`
Stime xtime.Time `json:"start_time"`
Etime xtime.Time `json:"end_time"`
}
// Jury is simple jury struct info.
type Jury struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Status int8 `json:"status"`
}
// CaseVote is simple caseVote struct info.
type CaseVote struct {
ID int64 `json:"id"`
CID int64 `json:"cid"`
MID int64 `json:"mid"`
Vote int8 `json:"vote"`
Expired xtime.Time `json:"expired"`
}
// BLogCaseVote is simple blogCaseVote struct info.
type BLogCaseVote struct {
ID int64 `json:"-"`
CID int64 `json:"cid"`
MID int64 `json:"mid"`
Vote int8 `json:"-"`
Expired string `json:"-"`
Ctime string `json:"-"`
Mtime string `json:"-"`
}
// Opinion is simple opinion struct info.
type Opinion struct {
Cid int64 `json:"cid"`
Vid int64 `json:"vid"`
Content string `json:"content"`
State int8 `json:"state"`
}
// BlockDays get user blocked days.
func (c *Case) BlockDays() (forever int8, days int64) {
switch c.PunishResult {
case Punish3Days:
days = 3
case Punish7Days:
days = 7
case Punish15Days:
days = 15
case PunishForever:
forever = int8(1)
case PunishCustom:
days = c.BlockedDay
}
return
}
// Origin is origin info of blocked.
type Origin struct {
OriginTitle string `json:"origin_title"`
OriginURL string `json:"origin_url"`
OriginContent string `json:"origin_content"`
OriginContentModify string `json:"origin_content_modify"`
OriginType int64 `json:"origin_type"`
ReasonType int64 `json:"reason_type"`
}
// BlockedInfo user block info.
type BlockedInfo struct {
ID int64 `json:"id"`
UID int64 `json:"uid"`
Origin
BlockedRemark string `json:"blocked_remark"`
PunishTime string `json:"punish_time"`
PunishType int64 `json:"punish_type"`
MoralNum int64 `json:"moral_num"`
BlockedDays int64 `json:"blocked_days"`
PublishStatus int64 `json:"publish_status"`
BlockedType int64 `json:"blocked_type"`
BlockedForever int8 `json:"blocked_forever"`
OperatorName string `json:"operator_name"`
CaseID int64 `json:"case_id"`
OPID int64 `json:"oper_id"`
Status int64 `json:"status"`
MTime string `json:"mtime"`
}
// Kpi is jury kpi info.
type Kpi struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Rate int8 `json:"rate"`
Rank int64 `json:"rank"`
RankPer int64 `json:"rank_per"`
RankTotal int64 `json:"rankTotal"`
HandlerStatus int64 `json:"handlerStatus"`
}
// PunishResultDays punish res days.
func PunishResultDays(blockedTimes int64) (punishResult, blockedDay int64) {
switch {
case blockedTimes == 0:
punishResult = int64(Block7Days)
blockedDay = BlockTimeSeven
case blockedTimes == 1:
punishResult = int64(Block15Days)
blockedDay = BlockTimeFifteen
case blockedTimes > 1:
punishResult = int64(BlockForever)
blockedDay = BlockTimeForever
}
return
}

View File

@@ -0,0 +1,79 @@
package model
// const kpi const
const (
// account pendPendant
_accountPendPendantS = 140
_accountPendPendantA = 139
_accountPendPendantB = 138
// _accountPendPendantC = 0
// KPI level and pendant info
_kpiLevelS = int8(1)
_kpiLevelA = int8(2)
_kpiLevelB = int8(3)
_kpiLevelC = int8(4)
_kpiNameplateA = 72
_kpiNameplateB = 71
_kpiNameplateC = 70
_kpiRateTimesA = 12
_kpiRateTimesB = 6
_kpiRateTimesC = 3
_kpiCoinsS = float64(20)
_kpiCoinsA = float64(10)
_kpiCoinsB = float64(5)
_kpiCoinsDefealt = float64(0)
// kpi defealt send days
KPIDefealtPendSendDays = 30
KPICoinsReason = "风纪委员任期奖励"
)
// var kpi var.
var (
// credit level mapping pendant info.
_levelPendant = map[int8][]int64{
_kpiLevelS: {_accountPendPendantS, _accountPendPendantA, _accountPendPendantB},
_kpiLevelA: {_accountPendPendantA, _accountPendPendantB},
_kpiLevelB: {_accountPendPendantB},
_kpiLevelC: {},
}
)
// LevelPendantByKPI get levelPendant by kpi level.
func LevelPendantByKPI(kpiLevel int8) (lps []int64, ok bool) {
lps, ok = _levelPendant[kpiLevel]
return
}
// KpiCoinsRate get coins by rate.
func KpiCoinsRate(rate int8) (coins float64) {
switch rate {
case _kpiLevelS:
coins = _kpiCoinsS
case _kpiLevelA:
coins = _kpiCoinsA
case _kpiLevelB:
coins = _kpiCoinsB
default:
coins = _kpiCoinsDefealt
}
return
}
// KpiPlateIDRateTimes get plate_id by rate times.
func KpiPlateIDRateTimes(rateTimes int) (plateID int64) {
switch rateTimes {
case _kpiRateTimesA:
plateID = _kpiNameplateA
case _kpiRateTimesB:
plateID = _kpiNameplateB
case _kpiRateTimesC:
plateID = _kpiNameplateC
}
return
}

View File

@@ -0,0 +1,69 @@
package model
import (
xtime "go-common/library/time"
)
const (
// RouteReplyReport report
RouteReplyReport = "report_add"
)
// Reply param struct
type Reply struct {
Action string `json:"action"`
MID int64 `json:"mid"`
Subject *ReplySubject `json:"subject"`
Reply *ReplyMain `json:"reply"`
Report *ReplyReport `json:"report"`
}
// ReplySubject param struct
type ReplySubject struct {
OID int64 `json:"oid"`
Type int8 `json:"type"`
MID int64 `json:"mid"`
State int8 `json:"state"`
CTime xtime.Time `json:"ctime"`
}
// ReplyMain param struct
type ReplyMain struct {
RPID int64 `json:"rpid"`
OID int64 `json:"oid"`
Type int8 `json:"type"`
MID int64 `json:"mid"`
Root int64 `json:"root"`
Parent int64 `json:"parent"`
Floor int32 `json:"floor"`
Count int32 `json:"count"`
Rcount int32 `json:"rcount"`
Like int64 `json:"like"`
Hate int64 `json:"hate"`
State int8 `json:"state"`
Content *struct {
Message string `json:"message"`
} `json:"content"`
CTime xtime.Time `json:"ctime"`
}
// ReplyReport param struct
type ReplyReport struct {
ID int64 `json:"id"`
OID int64 `json:"oid"`
Type int8 `json:"type"`
RPID int64 `json:"rpid"`
MID int64 `json:"mid"`
Reason int8 `json:"reason"`
Content string `json:"content"`
State int8 `json:"state"`
Score int `json:"score"`
Count int `json:"count"`
CTime xtime.Time `json:"ctime"`
}
// LabourAnswer param struct
type LabourAnswer struct {
MID int64 `json:"mid"`
MTime xtime.Time `json:"mtime"`
}

View File

@@ -0,0 +1,41 @@
package model
// const reply
const (
SubTypeArchive = int8(1) // 稿件
SubTypeTopic = int8(2) // 专题
SubTypeDrawyoo = int8(3) // 画站
SubTypeActivity = int8(4) // 活动
SubTypeLive = int8(5) // 直播小视频
SubTypeForbiden = int8(6) // 封禁信息
SubTypeNotice = int8(7) // 公告信息
SubTypeLiveAct = int8(8) // 直播活动
SubTypeActArc = int8(9) // 主站活动稿件
SubTypeLiveNotice = int8(10) // 直播公告
SubTypeLivePicture = int8(11) // 文画
SubTypeArticle = int8(12) // 文章
SubTypeTicket = int8(13) // 票务
SubTypeMusic = int8(14) // 音乐
SubTypeCredit = int8(15) // 风纪委案件
SubTypePgcCmt = int8(16) // pgc点评
SubTypeDynamic = int8(17) // 庐山动态
SubTypePlaylist = int8(18) // 播单
SubTypeMusicList = int8(19) // 音乐播单
ReportStateNew = int8(0) // 待审
ReportStateDelete = int8(1) // 移除
ReportStateIgnore = int8(2) // 忽略
ReportStateDeleteOne = int8(3) // 一审移除
ReportStateIgnoreOne = int8(4) // 一审忽略
ReportStateDeleteTwo = int8(5) // 二审移除
ReportStateIgnoreTwo = int8(6) // 二审忽略
ReportStateAddJuge = int8(8) // 移交仲裁
AppealBusinessID = int64(13) // 举报工单业务id
// AutoOPID auto oper_id
AutoOPID = int64(877)
// ReplyOriginURL reply origin url.
ReplyOriginURL = `https://www.bilibili.com/video/av%d/#reply%d`
)

View File

@@ -0,0 +1,71 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"blocked_test.go",
"case_test.go",
"extra_func_test.go",
"jury_test.go",
"reply_test.go",
"service_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",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"blocked.go",
"case.go",
"credit.go",
"extra_func.go",
"jury.go",
"kpi.go",
"reply.go",
"service.go",
],
importpath = "go-common/app/job/main/credit/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/credit/conf:go_default_library",
"//app/job/main/credit/dao:go_default_library",
"//app/job/main/credit/model:go_default_library",
"//app/service/main/archive/api/gorpc:go_default_library",
"//app/service/main/archive/model/archive:go_default_library",
"//app/service/main/member/api/gorpc:go_default_library",
"//app/service/main/member/model/block:go_default_library",
"//library/log:go_default_library",
"//library/queue/databus: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,106 @@
package service
import (
"context"
"encoding/json"
"strconv"
"time"
"go-common/app/job/main/credit/model"
blkmdl "go-common/app/service/main/member/model/block"
"go-common/library/log"
xtime "go-common/library/time"
)
// InvalidJury invalid juryer.
func (s *Service) InvalidJury(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
mr := &model.BlockedInfo{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if err = s.dao.InvalidJury(c, model.JuryBlocked, mr.UID); err != nil {
log.Error("s.dao.InvalidJury(%d %d) error(%v)", model.JuryBlocked, mr.UID, err)
}
return
}
// UnBlockAccount unblock account.
func (s *Service) UnBlockAccount(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
nMR := &model.BlockedInfo{}
if err = json.Unmarshal(nwMsg, nMR); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
oMR := &model.BlockedInfo{}
if err = json.Unmarshal(oldMsg, oMR); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(oldMsg), err)
return
}
if int8(oMR.Status) != model.StatusOpen {
return
}
if int8(nMR.Status) != model.StatusClose {
return
}
var id int64
if id, err = s.dao.BlockedInfoID(c, nMR.UID); err != nil {
log.Error("s.dao.BlockedInfoID(%+v) error(%v)", oMR, err)
return
}
if id != nMR.ID {
log.Warn("databus id(%d) do uid(%d) unblocked info(%d) not right!", nMR.ID, nMR.UID, id)
return
}
if err = s.dao.UnBlockAccount(c, oMR); err != nil {
log.Error("s.dao.UnBlockAccount(%+v) error(%v)", oMR, err)
}
return
}
// CheckBlock check user block state
func (s *Service) CheckBlock(c context.Context, mid int64) (ok bool, err error) {
var block *blkmdl.RPCResInfo
if block, err = s.memRPC.BlockInfo(c, &blkmdl.RPCArgInfo{MID: mid}); err != nil {
log.Error("s.memRPC.BlockInfo(%d) error(%+v)", err)
return
}
status := int8(block.BlockStatus)
if status == model.BlockStatusOn {
log.Warn("mid(%d) in blocked", mid)
return
}
if status == model.BlockStatusForever {
log.Warn("mid(%d) in blocked forever", mid)
return
}
ok = true
return
}
// NotifyBlockAnswer notify block answer status
func (s *Service) NotifyBlockAnswer(c context.Context, nwMsg []byte) (err error) {
mr := &model.BlockLabourAnswerLog{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.Score < 100 {
log.Warn("mid(%d) answer score(%d) lt 100", mr.Score, mr.Score)
return
}
var ts time.Time
if ts, err = time.ParseInLocation(model.TimeFormatSec, mr.CTime, time.Local); err != nil {
log.Error("time.ParseInLocation(%s) error(%v)", mr.CTime, err)
return
}
key := strconv.FormatInt(mr.MID, 10)
msg := &model.LabourAnswer{MID: mr.MID, MTime: xtime.Time(ts.Unix())}
if err = s.labourSub.Send(c, key, msg); err != nil {
log.Error("PubLabour.Pub(%s, %+v) error (%v)", key, msg, err)
}
if err = s.dao.DelAnswerStateCache(c, mr.MID); err != nil {
log.Error("DelAnswerStateCache(%d) error (%v)", mr.MID, err)
}
return
}

View File

@@ -0,0 +1,20 @@
package service
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_CheckBlock(t *testing.T) {
var (
c = context.TODO()
)
mid := int64(304)
Convey("should return err be nil", t, func() {
ok, err := s.CheckBlock(c, mid)
So(err, ShouldBeNil)
So(ok, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,265 @@
package service
import (
"context"
"encoding/json"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/log"
xtime "go-common/library/time"
"go-common/library/xstr"
)
// loadCase load grant case to list.
func (s *Service) loadCase() (err error) {
c := context.TODO()
if s.c.Judge.CaseLoadSwitch != model.StateCaseLoadOpen {
log.Warn("case load switch off!")
return
}
count, err := s.dao.TotalGrantCase(c)
if err != nil {
log.Error("s.dao.CaseGrantCount error(%v)", err)
return
}
loadCount := s.c.Judge.CaseLoadMax - count
if loadCount <= 0 {
log.Info("load case full caseLoadMax(%d) listCount(%d)", s.c.Judge.CaseLoadMax, count)
return
}
log.Info("need load count(%d) on already que len(%d) and max(%d)", loadCount, count, s.c.Judge.CaseLoadMax)
mcases, err := s.dao.Grantcase(c, loadCount)
if err != nil {
log.Error("s.dao.Grantcase(%d) error(%v)", loadCount, err)
return
}
if len(mcases) == 0 {
log.Warn("granting case is zero!")
return
}
var cids []int64
for cid := range mcases {
cids = append(cids, cid)
}
now := time.Now()
stime := xtime.Time(now.Unix())
etime := xtime.Time(now.Add(time.Duration(s.c.Judge.CaseGiveHours) * time.Hour).Unix())
if err = s.dao.UpGrantCase(c, cids, stime, etime); err != nil {
log.Error("s.dao.UpGrantCase(%s) error(%v)", xstr.JoinInts(cids), err)
return
}
for _, v := range mcases {
v.Stime = stime
v.Etime = etime
}
if err = s.dao.SetGrantCase(c, mcases); err != nil {
log.Error("s.dao.SetMIDCaseGrant(%s) error(%v)", xstr.JoinInts(cids), err)
}
log.Info("load cases(%s) to queue on start_time(%v) and end_time(%v)", xstr.JoinInts(cids), stime, etime)
return
}
// DealCaseApplyReason deal with case apply reason.
func (s *Service) DealCaseApplyReason(c context.Context, nwMsg []byte) (err error) {
mr := &model.CaseApplyModifyLog{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
var (
aReasons []int64
cas []*model.CaseApplyModifyLog
)
if aReasons, err = s.dao.CaseApplyReasons(c, mr.CID); err != nil {
log.Error("s.dao.CaseApplyReasons(%d) error(%v)", mr.CID, err)
return
}
if len(aReasons) == 0 {
log.Warn("apply reason(%s) is nil", xstr.JoinInts(aReasons))
return
}
if cas, err = s.dao.CaseApplyReasonNum(c, mr.CID, aReasons); err != nil {
log.Error("s.dao.CaseApplyReasonNum(%d,%s) error(%v)", mr.CID, xstr.JoinInts(aReasons), err)
return
}
var (
max int
reason int8
)
for _, v := range cas {
if v.Num > max {
max = v.Num
reason = v.AReason
}
}
standard := int(s.c.Judge.CaseVoteMax * int64(s.c.Judge.CaseVoteMaxPercent) / 100)
if max < standard {
log.Warn("apply reason num(%d) not enough standard(%d)", max, standard)
return
}
if reason == mr.OReason {
log.Warn("max reason(%d) eq orgin reason(%d)", reason, mr.OReason)
return
}
var effect int64
if effect, err = s.dao.UpBlockedCaseReason(c, mr.CID, reason); err != nil {
log.Error("s.dao.UpBlockedCaseReason(%d,%d) error(%v)", mr.CID, reason, err)
return
}
if effect <= 0 {
log.Warn("update case_id(%d) and reason(%d) notIdempotent", mr.CID, reason)
return
}
if model.ReasonToFreeze(reason) {
if err = s.dao.UpBlockedCaseStatus(c, mr.CID, model.CaseStatusFreeze); err != nil {
log.Error("s.dao.UpBlockedCaseStatus(%d,%d) error(%v)", mr.CID, model.CaseStatusFreeze, err)
return
}
}
if err = s.dao.AddBlockedCaseModifyLog(c, mr.CID, mr.AType, mr.OReason, mr.AReason); err != nil {
log.Error("s.dao.AddBlockedCaseModifyLog(%d,%d,%d,%d) error(%v)", mr.CID, mr.AType, mr.OReason, mr.AReason, err)
}
return
}
// GrantCase push case in list.
func (s *Service) GrantCase(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
mr := &model.Case{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.Status != model.CaseStatusGranting {
return
}
stime, err := time.ParseInLocation(time.RFC3339, mr.Stime, time.Local)
if err != nil {
stime, err = time.ParseInLocation("2006-01-02 15:04:05", mr.Stime, time.Local)
if err != nil {
log.Error("time.ParseInLocation(%s) error(%v)", mr.Stime, err)
return
}
err = nil
}
etime, err := time.ParseInLocation(time.RFC3339, mr.Etime, time.Local)
if err != nil {
etime, err = time.ParseInLocation("2006-01-02 15:04:05", mr.Etime, time.Local)
if err != nil {
log.Error("time.ParseInLocation(%s) error(%v)", mr.Etime, err)
return
}
err = nil
}
simCase := &model.SimCase{
ID: mr.ID,
Mid: mr.Mid,
VoteRule: mr.Agree,
VoteBreak: mr.Against,
VoteDelete: mr.VoteDelete,
CaseType: mr.CaseType,
Stime: xtime.Time(stime.Unix()),
Etime: xtime.Time(etime.Unix()),
}
mcases := make(map[int64]*model.SimCase)
mcases[mr.ID] = simCase
if err = s.dao.SetGrantCase(c, mcases); err != nil {
log.Error("s.dao.SetMIDCaseGrant(%+v) error(%v)", mr, err)
}
return
}
// DelGrantCase del case in list.
func (s *Service) DelGrantCase(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
mr := &model.Case{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.Status == model.CaseStatusDealing && mr.CaseType == model.JudeCaseTypePrivate {
return
}
if mr.Status == model.CaseStatusGranting || mr.Status == model.CaseStatusDealed || mr.Status == model.CaseStatusRestart {
return
}
cids := []int64{mr.ID}
// 删除冻结和停止发放中的cid
if err = s.dao.DelGrantCase(c, cids); err != nil {
log.Error("s.dao.SetMIDCaseGrant(%d) error(%v)", mr.ID, err)
}
log.Info("cid(%d) status(%d) remove hash list on start_time(%s) and end_time(%s)", mr.ID, mr.Status, mr.Stime, mr.Etime)
return
}
// DelCaseInfoCache del case info cache.
func (s *Service) DelCaseInfoCache(c context.Context, nwMsg []byte) (err error) {
mr := &model.Case{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if err = s.dao.DelCaseInfoCache(c, mr.ID); err != nil {
log.Error("s.dao.DelCaseInfoCache(%d) error(%v)", mr.ID, err)
return
}
log.Info("cid(%d) del case_info cache", mr.ID)
return
}
// DelVoteCaseCache del vote case cache.
func (s *Service) DelVoteCaseCache(c context.Context, nwMsg []byte) (err error) {
mr := &model.BLogCaseVote{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if err = s.dao.DelVoteCaseCache(c, mr.MID, mr.CID); err != nil {
log.Error("s.dao.DelCaseInfoCache(%d,%d) error(%v)", mr.MID, mr.CID, err)
return
}
log.Info("mid(%d) cid(%d) del vote_case cache", mr.MID, mr.CID)
if err = s.dao.DelJuryInfoCache(c, mr.MID); err != nil {
log.Error("s.dao.DelJuryInfoCache(%d) error(%v)", mr.MID, err)
}
log.Info("mid(%d) del jury cache", mr.MID, mr.CID)
if err = s.dao.DelCaseVoteTopCache(c, mr.MID); err != nil {
log.Error("s.dao.DelCaseVoteTopCache(%d) error(%v)", mr.MID, err)
}
log.Info("mid(%d) del vote top cache", mr.MID)
return
}
// loadDealWrongCase deal wrong case status in cache .
func (s *Service) loadDealWrongCase() (err error) {
var (
cids, wcids []int64
mcids map[int64]int8
c = context.TODO()
)
if cids, err = s.dao.GrantCases(c); err != nil {
log.Error("s.dao.GrantCases error(%+v)", err)
return
}
if len(cids) == 0 {
log.Warn("deal wrong (granting case is zero!)")
return
}
if mcids, err = s.dao.CasesStatus(c, cids); err != nil {
log.Error("s.dao.CasesStatus(%s) error(%+v)", xstr.JoinInts(cids), err)
return
}
for cid, status := range mcids {
if status != model.CaseStatusGranting {
wcids = append(wcids, cid)
}
}
if len(wcids) == 0 {
return
}
if err = s.dao.DelGrantCase(c, wcids); err != nil {
log.Error("s.dao.DelGrantCase(%s) error(%+v)", xstr.JoinInts(wcids), err)
return
}
log.Info("load del wrong cases(%s) from queue", xstr.JoinInts(wcids))
return
}

View File

@@ -0,0 +1,59 @@
package service
import (
"context"
"encoding/json"
"testing"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_DelCaseInfoCache(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.ID = 304
mr.Status = model.CaseStatusDealing
mr.JudgeType = model.JudgeTypeViolate
mr.OriginTitle = "304"
mr.Mid = 1
mr.OriginURL = "http:304"
mr.OriginContent = "304cont"
mr.OriginType = 4
mr.Operator = "lgs"
mr.Status = 4
mr.ReasonType = 3
mr.RelationID = "10741-4052410"
mr.PunishResult = 2
bb, _ := json.Marshal(mr)
Convey("should return err be nil", t, func() {
err := s.DelCaseInfoCache(c, bb)
So(err, ShouldBeNil)
})
}
func Test_UpdateVoteCount(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.ID = 304
mr.Status = model.CaseStatusDealing
mr.JudgeType = model.JudgeTypeViolate
mr.OriginTitle = "304"
mr.Mid = 1
mr.OriginURL = "http:304"
mr.OriginContent = "304cont"
mr.OriginType = 4
mr.Operator = "lgs"
mr.Status = 4
mr.ReasonType = 3
mr.RelationID = "10741-4052410"
mr.PunishResult = 2
Convey("should return err be nil", t, func() {
s.UpdateVoteCount(c, mr)
})
}

View File

@@ -0,0 +1,96 @@
package service
import (
"context"
"encoding/json"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/log"
)
const (
_blockedJuryTable = "blocked_jury"
_blockedInfoTable = "blocked_info"
_blockedCaseTable = "blocked_case"
_voteOpinion = "blocked_opinion"
_blockedKpiTable = "blocked_kpi"
_blockedPublishTable = "blocked_publish"
_blockedVoteCaseTable = "blocked_case_vote"
_blockedCaseApplyLogTable = "blocked_case_apply_log"
_blockedLabourAnswerLog = "blocked_labour_answer_log"
_retry = 3
_retrySleep = time.Second * 1
)
func (s *Service) creditConsumer() {
var err error
for res := range s.credbSub.Messages() {
mu := &model.Message{}
if err = json.Unmarshal(res.Value, mu); err != nil {
log.Error("credit-job,json.Unmarshal (%v) error(%v)", string(res.Value), err)
continue
}
for i := 0; ; i++ {
err = s.dealCredit(mu)
if err != nil {
log.Error("s.flush error(%v)", err)
time.Sleep(_retrySleep)
if i > _retry && s.c.Env == "prod" {
s.dao.Sms(context.TODO(), s.c.Sms.Phone, s.c.Sms.Token, "credit-job update cache fail for 5 times")
i = 0
}
continue
}
break
}
if err = res.Commit(); err != nil {
log.Error("databus.Commit err(%v)", err)
}
log.Info("subproc key:%v,topic: %v, part:%v offset:%v,message %s,", res.Key, res.Topic, res.Partition, res.Offset, res.Value)
}
}
// dealAction deal databus action
func (s *Service) dealCredit(mu *model.Message) (err error) {
switch mu.Table {
case _blockedCaseTable:
if mu.Action == "insert" {
s.RegReply(context.TODO(), mu.Table, mu.New, mu.Old)
}
err = s.Judge(context.TODO(), mu.New, mu.Old)
s.GrantCase(context.TODO(), mu.New, mu.Old)
s.DelGrantCase(context.TODO(), mu.New, mu.Old)
s.DelCaseInfoCache(context.TODO(), mu.New)
case _blockedInfoTable:
if mu.Action == "insert" {
s.RegReply(context.TODO(), mu.Table, mu.New, mu.Old)
s.InvalidJury(context.TODO(), mu.New, mu.Old)
}
if mu.Action == "update" {
s.UnBlockAccount(context.TODO(), mu.New, mu.Old)
}
s.UpdateCache(context.TODO(), mu.New)
case _blockedKpiTable:
if mu.Action == "insert" {
s.KPIReward(context.TODO(), mu.New, mu.Old)
}
case _voteOpinion:
s.DeleteIdx(context.TODO(), mu.New)
case _blockedPublishTable:
s.RegReply(context.TODO(), mu.Table, mu.New, mu.Old)
case _blockedVoteCaseTable:
s.DelVoteCaseCache(context.TODO(), mu.New)
case _blockedLabourAnswerLog:
if mu.Action == "insert" {
s.NotifyBlockAnswer(context.TODO(), mu.New)
}
case _blockedCaseApplyLogTable:
if mu.Action == "insert" {
s.DealCaseApplyReason(context.TODO(), mu.New)
}
case _blockedJuryTable:
s.DelJuryInfoCache(context.TODO(), mu.New)
}
return
}

View File

@@ -0,0 +1,154 @@
package service
import (
"context"
"encoding/json"
"strings"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/log"
)
// UpdateVoteCount update user vote count.
func (s *Service) UpdateVoteCount(c context.Context, mr *model.Case) {
cvs, err := s.dao.CaseVotesCID(c, mr.ID)
if err != nil {
log.Error("s.dao.CaseVotesCID(%d)", mr.ID)
return
}
for _, cv := range cvs {
switch {
case mr.JudgeType == model.JudgeTypeViolate:
if cv.Vote == model.VoteTypeDelete || cv.Vote == model.VoteTypeViolate {
if err = s.dao.UpdateVoteRight(c, cv.MID); err != nil {
log.Error("s.dao.UpdateVoteRight(%d)", cv.MID)
}
} else if cv.Vote == model.VoteTypeLegal {
if err = s.dao.UpdateVoteTotal(c, cv.MID); err != nil {
log.Error("s.dao.UpdateVoteTotal(%d)", cv.MID)
}
}
case mr.JudgeType == model.JudgeTypeLegal:
if cv.Vote == model.VoteTypeLegal {
if err = s.dao.UpdateVoteRight(c, cv.MID); err != nil {
log.Error("s.dao.UpdateVoteRight(%d)", cv.MID)
}
} else if cv.Vote == model.VoteTypeViolate || cv.Vote == model.VoteTypeDelete {
if err = s.dao.UpdateVoteTotal(c, cv.MID); err != nil {
log.Error("s.dao.UpdateVoteTotal(%d)", cv.MID)
}
}
}
time.Sleep(100 * time.Millisecond)
}
}
// UpdateCache update blocked info cache.
func (s *Service) UpdateCache(c context.Context, nwMsg []byte) (err error) {
mr := &model.BlockedInfo{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.PublishStatus == int64(model.PublishClose) || mr.Status == int64(model.StatusClose) {
s.dao.DelBlockedInfoIdx(c, mr)
} else {
s.dao.AddBlockInfoIdx(c, mr)
}
return
}
// DelOrigin delorigin content.
func (s *Service) DelOrigin(c context.Context, cs *model.Case) {
switch int8(cs.OriginType) {
case model.OriginReply:
if cs.RelationID != "" {
args := strings.Split(cs.RelationID, "-")
if len(args) != 3 {
return
}
s.dao.DelReply(c, args[0], args[1], args[2])
}
case model.OriginTag:
if cs.RelationID != "" {
args := strings.Split(cs.RelationID, "-")
if len(args) != 2 {
return
}
s.dao.DelTag(c, args[0], args[1])
}
case model.OriginDM:
if cs.RelationID != "" {
args := strings.Split(cs.RelationID, "-")
if len(args) != 4 {
return
}
s.dao.ReportDM(c, args[2], args[1], model.DMNotifyDel)
}
}
}
// DeleteIdx del cache idx.
func (s *Service) DeleteIdx(c context.Context, nwMsg []byte) (err error) {
var opinion *model.Opinion
if err = json.Unmarshal(nwMsg, &opinion); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
s.dao.DelOpinionCache(c, opinion.Vid)
s.dao.DelCaseIdx(c, opinion.Cid)
s.dao.DelVoteIdx(c, opinion.Cid)
return
}
// jugeBlockedUser
func (s *Service) jugeBlockedUser(c context.Context, mid int64, timeStr string, bType int8) (ok bool, count int64, err error) {
var ts, nts time.Time
if ts, err = time.ParseInLocation(model.TimeFormatSec, timeStr, time.Local); err != nil {
log.Error("time.ParseInLocation(%s) error(%v)", timeStr, err)
return
}
switch bType {
case model.DealTimeTypeNone:
nts = ts
case model.DealTimeTypeDay:
nts = ts.AddDate(0, 0, -1)
case model.DealTimeTypeYear:
nts = ts.AddDate(-1, 0, 0)
}
if count, err = s.dao.CountBlocked(c, mid, nts); err != nil {
log.Error("s.dao.CountBlocked(%d,%s) error(%v)", mid, nts, err)
return
}
if count == 0 {
ok = true
}
return
}
// DelJuryInfoCache .
func (s *Service) DelJuryInfoCache(c context.Context, nwMsg []byte) (err error) {
mr := &model.Jury{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if err = s.dao.DelJuryInfoCache(c, mr.Mid); err != nil {
log.Error("s.dao.DelJuryInfoCache(%d) error(%v)", mr.Mid, err)
}
return
}
// DelCaseVoteTopCache .
func (s *Service) DelCaseVoteTopCache(c context.Context, nwMsg []byte) (err error) {
mr := &model.CaseVote{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if err = s.dao.DelCaseVoteTopCache(c, mr.MID); err != nil {
log.Error("s.dao.DelCaseVoteTopCache(%d) error(%v)", mr.MID, err)
}
return
}

View File

@@ -0,0 +1,50 @@
package service
import (
"context"
"encoding/json"
"testing"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_DelOrigin(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.OriginType = int64(model.OriginTag)
mr.RelationID = "57-4052400"
Convey("should return err be nil", t, func() {
s.DelOrigin(c, mr)
})
}
func Test_DelOrigin2(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.OriginType = int64(model.OriginReply)
mr.RelationID = "111002543-3-400"
Convey("should return err be nil", t, func() {
s.DelOrigin(c, mr)
})
}
func TestServiceDelJuryInfoCache(t *testing.T) {
var (
c = context.TODO()
mr = &model.Jury{}
)
mr.ID = 304
mr.Status = model.CaseStatusDealing
mr.Mid = 1
Convey("should return err be nil", t, func() {
b, _ := json.Marshal(&mr)
err := s.DelJuryInfoCache(c, b)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,193 @@
package service
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/log"
)
const (
_msgTitle = "风纪委员任期结束"
_msgContext = "您的风纪委员资格已到期,任职期间的总结报告已生成。感谢您对社区工作的大力支持!#{点击查看}{" + "\"http://www.bilibili.com/judgement/\"" + "}"
_appealTitle = "账号违规处理通知"
_appealContent = `抱歉,你的账号因"在%s中%s",现已进行%s处理账号解封需要满足以下两个条件:1.账号封禁时间已满。2.完成解封答题( #{点击进入解封答题}{"http://www.bilibili.com/blackroom/releaseexame.html"} 全部完成后解封。封禁期间将无法投稿、发送及回复消息无法发布评论、弹幕无法对他人评论进行回复、赞踩操作无法进行投币、编辑标签、添加关注、添加收藏操作。如对处罚有异议可在7日内进行申诉
#{点击申诉}{"http://www.bilibili.com/judgement/appeal?bid=%d"} 。请遵守社区规范,共同维护良好的社区氛围!`
)
// Judge judge case.
func (s *Service) Judge(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
var (
sum int64
mr = &model.Case{}
bc model.Case
judge int64
status int64
yratio int64
nratio int64
judgeRadio = s.c.Judge.JudgeRadio
voteMin = s.c.Judge.CaseVoteMin
)
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.CaseType == model.JudeCaseTypePublic {
return
}
if mr.Status != model.CaseStatusDealing {
return
}
if bc, err = s.dao.CaseByID(c, mr.ID); err != nil {
log.Error("s.dao.CaseByID error(%v)", err)
return
}
if bc.Status == model.CaseStatusDealed || bc.Status == model.CaseStatusUndealed {
return
}
sum = mr.Against + mr.Agree + mr.VoteDelete
if voteMin <= 0 {
log.Error("CaseVoteMin(%d) error(%v)", voteMin, err)
return
}
if sum < voteMin {
status = model.CaseStatusUndealed
judge = model.JudgeTypeUndeal
s.dao.UpdateCase(c, status, judge, mr.ID)
return
}
yratio = mr.Agree * 100 / sum
nratio = (mr.Against + mr.VoteDelete) * 100 / sum
if judgeRadio <= 50 {
log.Error("CaseJudgeRadio(%d) error(%v)", judgeRadio, err)
return
}
if yratio >= judgeRadio {
status = model.CaseStatusDealed
judge = model.JudgeTypeLegal
} else if nratio >= judgeRadio {
status = model.CaseStatusDealed
judge = model.JudgeTypeViolate
} else {
status = model.CaseStatusUndealed
judge = model.JudgeTypeUndeal
}
s.dao.UpdateCase(c, status, judge, mr.ID)
mr.Status = status
mr.JudgeType = judge
if status == model.CaseStatusDealed {
s.BlockUser(c, mr)
s.UpdateVoteCount(c, mr)
s.dao.DelGrantCase(c, []int64{mr.ID})
} else {
if mr.OriginType == int64(model.OriginDM) {
if mr.RelationID != "" {
args := strings.Split(mr.RelationID, "-")
if len(args) != 4 {
return
}
s.dao.ReportDM(c, args[2], args[1], model.DMNotifyNotDel)
}
}
}
return
}
// BlockUser add user block.
func (s *Service) BlockUser(c context.Context, mr *model.Case) (err error) {
if mr.JudgeType == model.JudgeTypeViolate {
s.DelOrigin(c, mr)
if mr.Against <= mr.VoteDelete+mr.Agree {
err = s.dealMoralCase(c, mr)
return
}
var (
ok bool
punishType int64
)
forever, days := mr.BlockDays()
if forever != model.InBlockedForever {
punishType = int64(model.PunishTypeBlock)
} else {
punishType = int64(model.PunishTypeForever)
}
r := &model.BlockedInfo{
UID: mr.Mid,
PunishType: punishType,
BlockedType: model.PunishJury,
OperatorName: mr.Operator,
CaseID: mr.ID,
Origin: mr.Origin,
OPID: mr.OPID,
BlockedForever: forever,
BlockedDays: days,
}
r.OriginContentModify = r.OriginContent
if ok, err = s.CheckBlock(c, mr.Mid); err != nil || !ok {
return
}
if mr.BusinessTime != model.DefaultTime {
ok, _, err = s.jugeBlockedUser(c, mr.Mid, mr.BusinessTime, model.DealTimeTypeNone)
if err != nil {
log.Error("s.jugeBlockedUser(%d,%s,%d) error(%v)", mr.Mid, mr.BusinessTime, model.DealTimeTypeNone, err)
return
}
} else {
ok, _, err = s.jugeBlockedUser(c, mr.Mid, mr.Ctime, model.DealTimeTypeDay)
if err != nil {
log.Error("s.jugeBlockedUser(%d,%s,%d) error(%v)", mr.Mid, mr.Ctime, model.DealTimeTypeDay, err)
return
}
}
if ok {
var id int64
id, err = s.dao.AddBlockInfo(c, r, time.Now())
if err != nil {
log.Error("s.dao.AddBlockInfo error(%v)", err)
return
}
if err = s.dao.BlockAccount(c, r); err != nil {
log.Error("s.dao.BlockAccount(%+v) error(%v)", r, err)
return
}
s.dao.SendMsg(c, mr.Mid, _appealTitle, fmt.Sprintf(_appealContent, model.OriginTypeDesc(int8(mr.OriginType)), model.ReasonTypeDesc(int8(mr.ReasonType)), model.BlockedDayDesc(int8(mr.BlockedDay)), id))
}
} else if mr.JudgeType == model.JudgeTypeLegal {
if mr.JudgeType == int64(model.OriginDM) {
s.dao.UpdatePunishResult(c, mr.ID, model.BlockNone)
if mr.RelationID != "" {
args := strings.Split(mr.RelationID, "-")
if len(args) != 4 {
return
}
s.dao.ReportDM(c, args[2], args[1], model.DMNotifyNotDel)
}
}
}
return
}
func (s *Service) dealMoralCase(c context.Context, mr *model.Case) (err error) {
if err = s.dao.UpdatePunishResult(c, mr.ID, model.BlockOnlyDel); err != nil {
log.Error("UpdatePunishResult error(%v)", err)
return
}
title, content := model.OriginMsgContent(mr.OriginTitle, mr.OriginURL, mr.OriginContent, int8(mr.OriginType))
for i := 0; i <= 5; i++ {
if err := s.dao.AddMoral(c, mr.Mid, model.DefealtMoralVal, model.OrginMoralType(int8(mr.OriginType)), model.BUSSINESS, model.ReasonTypeDesc(int8(mr.ReasonType)), model.MoralRemark, ""); err != nil {
continue
}
break
}
for i := 0; i <= 5; i++ {
if err := s.dao.SendMsg(c, mr.Mid, title, content); err != nil {
continue
}
break
}
return
}

View File

@@ -0,0 +1,83 @@
package service
import (
"context"
"encoding/json"
"testing"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_BlockUser(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.ID = 304
mr.JudgeType = model.JudgeTypeViolate
mr.OriginTitle = "304"
mr.Mid = 1
mr.OriginURL = "http:304"
mr.OriginContent = "304cont"
mr.OriginType = 4
mr.Operator = "lgs"
mr.Status = 4
mr.ReasonType = 3
mr.RelationID = "10741-4052410"
mr.PunishResult = 2
Convey("should return err be nil", t, func() {
err := s.BlockUser(c, mr)
So(err, ShouldBeNil)
})
}
func Test_Judge(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.ID = 304
mr.Status = model.CaseStatusDealing
mr.JudgeType = model.JudgeTypeViolate
mr.OriginTitle = "304"
mr.Mid = 1
mr.OriginURL = "http:304"
mr.OriginContent = "304cont"
mr.OriginType = 4
mr.Operator = "lgs"
mr.Status = 4
mr.ReasonType = 3
mr.RelationID = "10741-4052410"
mr.PunishResult = 2
Convey("should return err be nil", t, func() {
b, _ := json.Marshal(&mr)
err := s.Judge(c, b, b)
So(err, ShouldBeNil)
})
}
func Test_dealMoralCase(t *testing.T) {
var (
c = context.TODO()
mr = &model.Case{}
)
mr.ID = 304
mr.Status = model.CaseStatusDealing
mr.JudgeType = model.JudgeTypeViolate
mr.OriginTitle = "304"
mr.Mid = 1
mr.OriginURL = "http:304"
mr.OriginContent = "304cont"
mr.OriginType = 4
mr.Operator = "lgs"
mr.Status = 4
mr.ReasonType = 3
mr.RelationID = "10741-4052410"
mr.PunishResult = 2
Convey("dealMoralCase", t, func() {
err := s.dealMoralCase(c, mr)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,70 @@
package service
import (
"context"
"encoding/json"
"time"
"go-common/app/job/main/credit/model"
"go-common/library/log"
)
// KPIReward send reward to user by kpi info.
func (s *Service) KPIReward(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {
var (
mr = &model.Kpi{}
res model.Kpi
nameplentID int64
coins float64
)
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if res, err = s.dao.KPIInfo(c, mr.ID); err != nil {
log.Error("json.KPIInf(%d) error(%v)", mr.ID, err)
return
}
if res.HandlerStatus == 1 {
return
}
s.dao.SendMsg(c, mr.Mid, _msgTitle, _msgContext)
coins = model.KpiCoinsRate(mr.Rate)
if coins > 0 {
s.dao.AddMoney(c, mr.Mid, coins, model.KPICoinsReason)
}
s.dao.UpdateKPIHandlerStatus(c, mr.ID)
if pend, ok := model.LevelPendantByKPI(int8(mr.Rate)); ok {
expired := time.Now().AddDate(0, 0, 30)
if err = s.dao.UpdateJuryExpired(c, mr.Mid, expired); err != nil {
return
}
if len(pend) > 0 {
if err = s.dao.SendPendant(c, mr.Mid, pend, model.KPIDefealtPendSendDays); err != nil {
log.Error("s.dao.SendPendant err(%v)", err)
}
if err == nil {
s.dao.UpdateKPIPendentStatus(c, mr.ID)
}
if mr.Mid%50 == 1 {
time.Sleep(time.Second)
}
}
}
num, err := s.dao.CountKPIRate(c, mr.Mid)
if err != nil {
log.Error("s.dao.CountKPIRate(mid:%d) err(%v)", mr.Mid, err)
return
}
nameplentID = model.KpiPlateIDRateTimes(num)
if nameplentID != 0 {
for i := 0; i <= 5; i++ {
if err = s.dao.SendMedal(c, mr.Mid, nameplentID); err != nil {
log.Error("s.dao.SendMedal(mid:%d nameNameplatid:%d) err(%v)", mr.Mid, nameplentID, err)
continue
}
break
}
}
return
}

View File

@@ -0,0 +1,198 @@
package service
import (
"context"
"encoding/json"
"fmt"
"time"
"go-common/app/job/main/credit/model"
"go-common/app/service/main/archive/model/archive"
"go-common/library/log"
)
func (s *Service) replyAllConsumer() {
defer s.wg.Done()
var (
msgs = s.replyAllSub.Messages()
err error
c = context.TODO()
)
for {
msg, ok := <-msgs
if !ok {
log.Error("s.replyAllSub.Message closed")
return
}
msg.Commit()
m := &model.Reply{}
if err = json.Unmarshal(msg.Value, m); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", string(msg.Value), err)
continue
}
switch m.Action {
case model.RouteReplyReport:
err = s.addReplyReport(c, m)
default:
log.Warn("replyAllConsumer unknown message action(%s)", m.Action)
}
if err != nil {
log.Error("replyMessage key(%s) value(%s) partition(%d) offset(%d) commit error(%v)", msg.Key, msg.Value, msg.Partition, msg.Offset, err)
continue
}
log.Info("replyMessage key(%s) value(%s) partition(%d) offset(%d) commit", msg.Key, msg.Value, msg.Partition, msg.Offset)
}
}
func (s *Service) addReplyReport(c context.Context, m *model.Reply) (err error) {
if m.Reply == nil || m.Subject == nil || m.Report == nil {
log.Warn("reply content(%+v) empty!", m)
return
}
if m.Report.State == model.ReportStateAddJuge {
log.Warn("rpid(%d) state(%d) is in juge", m.Report.RPID, m.Report.State)
return
}
if m.Report.Type != model.SubTypeArchive {
log.Warn("m.Report.Type(%d) model.SubTypeArchive(%d)", m.Report.Type, model.SubTypeArchive)
return
}
var ca *model.AutoCaseConf
if ca, err = s.dao.AutoCaseConf(c, model.OriginReply); err != nil {
log.Error("s.dao.AutoCaseConf(%d) error(%v)", model.OriginReply, err)
return
}
if ca == nil {
log.Warn("otype(%d) auto acse conf is not set !", model.OriginReply)
return
}
replyReportReason := model.BlockedReasonTypeByReply(m.Report.Reason)
if _, ok := ca.Reasons[replyReportReason]; !ok {
log.Warn("m.Report.Reason(%d) not int ca.Reasons(%+v)", m.Report.Reason, ca.Reasons)
return
}
if m.Report.Score < ca.ReportScore {
log.Warn("m.Report.Score(%d) ca.ReportScore(%d)", m.Report.Score, ca.ReportScore)
return
}
if m.Reply.Like > int64(ca.Likes) {
log.Warn("m.Reply.Like(%d) ca.Likes(%d)", m.Reply.Like, ca.Likes)
return
}
var disCount, total int64
if disCount, err = s.dao.CountCaseMID(c, m.Reply.MID, model.OriginReply); err != nil {
log.Error("s.dao.CountBlocked(%d) err(%v)", m.Reply.MID, err)
return
}
if disCount > 0 {
log.Warn("rpid(%d) mid(%d) report in 24 hours", m.Report.RPID, m.Reply.MID)
return
}
if total, err = s.dao.CountBlocked(c, m.Reply.MID, time.Now().AddDate(-1, 0, 0)); err != nil {
log.Error("s.dao.CountBlocked(%d) err(%v)", m.Reply.MID, err)
return
}
punishResult, blockedDay := model.PunishResultDays(total)
mc := &model.Case{
Mid: m.Reply.MID,
Status: model.CaseStatusGrantStop,
RelationID: fmt.Sprintf("%d-%d-%d", m.Report.RPID, m.Report.Type, m.Report.OID),
PunishResult: punishResult,
BlockedDay: blockedDay,
OPID: model.AutoOPID,
BCtime: m.Reply.CTime,
}
mc.Origin = model.Origin{
OriginTitle: s.replyOriginTitle(c, m.Report.OID, m.Report.Type),
OriginContent: m.Reply.Content.Message,
OriginType: int64(model.OriginReply),
OriginURL: s.replyOriginURL(m.Report.RPID, m.Report.OID, m.Report.Type),
ReasonType: int64(replyReportReason),
}
var count int64
if count, err = s.dao.CaseRelationIDCount(c, model.OriginReply, mc.RelationID); err != nil {
log.Error("ss.dao.CaseRelationIDCount(%d,%s) err(%v)", model.OriginReply, mc.RelationID, err)
return
}
if count > 0 {
log.Warn("rpid(%d) state(%d) is alreadly juge", m.Report.RPID, m.Report.State)
return
}
var need bool
if need, err = s.dao.CheckFilter(c, "credit", m.Reply.Content.Message, ""); err != nil {
log.Error("s.dao.CheckFilter(%s,%s) error(%v)", "credit", m.Reply.Content.Message, err)
return
}
if need {
log.Warn("reply(%d) message(%s) is filter", m.Report.RPID, m.Reply.Content.Message)
return
}
if err = s.dao.AddBlockedCase(c, mc); err != nil {
log.Error("s.dao.AddBlockedCase(%+v) err(%v)", mc, err)
return
}
s.dao.UpReplyState(c, m.Report.OID, m.Report.RPID, m.Report.Type, model.ReportStateAddJuge)
s.dao.UpAppealState(c, model.AppealBusinessID, m.Report.OID, m.Report.RPID)
return
}
func (s *Service) replyOriginTitle(c context.Context, oid int64, oType int8) (title string) {
switch oType {
case model.SubTypeArchive:
arg := &archive.ArgAid2{Aid: oid}
arc, err := s.arcRPC.Archive3(c, arg)
if err != nil {
log.Error("s.arcRPC.Archive3(%v) error(%v)", arg, err)
return
}
title = arc.Title
return
}
return
}
func (s *Service) replyOriginURL(rpid, oid int64, oType int8) string {
switch oType {
case model.SubTypeArchive:
return fmt.Sprintf(model.ReplyOriginURL, oid, rpid)
}
return ""
}
// RegReply regist reply subject.
func (s *Service) RegReply(c context.Context, table string, nwMsg []byte, oldMsg []byte) (err error) {
var (
replyType int8
replyID int64
)
switch table {
case _blockedCaseTable:
mr := &model.Case{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
replyType = model.ReplyCase
replyID = mr.ID
case _blockedInfoTable:
mr := &model.BlockedInfo{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
replyType = model.ReplyBlocked
replyID = mr.ID
case _blockedPublishTable:
mr := &model.Publish{}
if err = json.Unmarshal(nwMsg, mr); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(nwMsg), err)
return
}
if mr.PStatus != model.PublishOpen {
return
}
replyType = model.ReplyPublish
replyID = mr.ID
}
return s.dao.RegReply(c, replyID, replyType)
}

View File

@@ -0,0 +1,40 @@
package service
import (
"context"
"testing"
"go-common/app/job/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_addReplyReport(t *testing.T) {
var (
c = context.TODO()
mr = &model.Reply{
Subject: &model.ReplySubject{
OID: 2222,
},
Reply: &model.ReplyMain{
Like: 1,
MID: 27515628,
Content: &struct {
Message string `json:"message"`
}{Message: "xxxx"},
},
Report: &model.ReplyReport{
State: model.ReportStateNew,
Type: model.SubTypeArchive,
Reason: model.ReplyReasonGarbageAds,
Score: 2,
RPID: 1111,
OID: 2222,
},
}
)
Convey("should return err be nil", t, func() {
err := s.addReplyReport(c, mr)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,135 @@
package service
import (
"context"
"encoding/json"
"strconv"
"sync"
"time"
"go-common/app/job/main/credit/conf"
"go-common/app/job/main/credit/dao"
archive "go-common/app/service/main/archive/api/gorpc"
memrpc "go-common/app/service/main/member/api/gorpc"
"go-common/library/log"
"go-common/library/queue/databus"
)
// Service struct of service.
type Service struct {
c *conf.Config
dao *dao.Dao
credbSub *databus.Databus
replyAllSub *databus.Databus
labourSub *databus.Databus
arcRPC *archive.Service2
memRPC *memrpc.Service
// wait group
wg sync.WaitGroup
}
// New create service instance and return.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
dao: dao.New(c),
credbSub: databus.New(c.DataBus.CreditDBSub),
replyAllSub: databus.New(c.DataBus.ReplyAllSub),
labourSub: databus.New(c.DataBus.LabourSub),
arcRPC: archive.New2(c.RPCClient.Archive),
memRPC: memrpc.New(c.RPCClient.Member),
}
s.loadConf()
s.loadCase()
s.loadDealWrongCase()
s.wg.Add(1)
go s.replyAllConsumer()
go s.creditConsumer()
go s.loadConfproc()
return
}
// Ping check service health.
func (s *Service) Ping(c context.Context) error {
return s.dao.Ping(c)
}
func (s *Service) loadConfproc() {
for {
time.Sleep(time.Duration(s.c.Judge.ConfTimer))
s.loadConf()
s.loadCase()
s.loadDealWrongCase()
}
}
func (s *Service) loadConf() {
m, err := s.dao.LoadConf(context.TODO())
if err != nil {
log.Error("loadConf error(%v)", err)
return
}
if s.c.Judge.CaseGiveHours, err = strconv.ParseInt(m["case_give_hours"], 10, 64); err != nil {
log.Error("loadConf CaseGiveHours error(%v)", err)
}
if s.c.Judge.CaseCheckTime, err = strconv.ParseInt(m["case_check_hours"], 10, 64); err != nil {
log.Error("loadConf CaseCheckTime error(%v)", err)
}
if s.c.Judge.JuryRatio, err = strconv.ParseInt(m["jury_vote_radio"], 10, 64); err != nil {
log.Error("loadConf JuryRatio error(%v)", err)
}
if s.c.Judge.JudgeRadio, err = strconv.ParseInt(m["case_judge_radio"], 10, 64); err != nil {
log.Error("loadConf JudgeRadio error(%v)", err)
}
if s.c.Judge.CaseVoteMin, err = strconv.ParseInt(m["case_vote_min"], 10, 64); err != nil {
log.Error("loadConf CaseVoteMin error(%v)", err)
}
if s.c.Judge.CaseObtainMax, err = strconv.ParseInt(m["case_obtain_max"], 10, 64); err != nil {
log.Error("loadConf CaseObtainMax error(%v)", err)
}
if s.c.Judge.CaseVoteMax, err = strconv.ParseInt(m["case_vote_max"], 10, 64); err != nil {
log.Error("loadConf CaseVoteMax error(%v)", err)
}
if s.c.Judge.JuryApplyMax, err = strconv.ParseInt(m["jury_apply_max"], 10, 64); err != nil {
log.Error("loadConf JuryApplyMax error(%v)", err)
}
if s.c.Judge.CaseLoadMax, err = strconv.Atoi(m["case_load_max"]); err != nil {
log.Error("loadConf CaseLoadMax error(%v)", err)
}
var caseLoadSwitch int64
if caseLoadSwitch, err = strconv.ParseInt(m["case_load_switch"], 10, 64); err != nil {
log.Error("loadConf CaseLoadSwitch error(%v)", err)
}
s.c.Judge.CaseLoadSwitch = int8(caseLoadSwitch)
if s.c.Judge.CaseVoteMaxPercent, err = strconv.Atoi(m["case_vote_max_percent"]); err != nil {
log.Error("loadConf CaseVoteMaxPercent error(%v)", err)
}
if _, ok := m["vote_num"]; !ok {
s.c.Judge.VoteNum.RateS = 1
s.c.Judge.VoteNum.RateA = 1
s.c.Judge.VoteNum.RateB = 1
s.c.Judge.VoteNum.RateC = 1
s.c.Judge.VoteNum.RateD = 1
return
}
if err = json.Unmarshal([]byte(m["vote_num"]), &s.c.Judge.VoteNum); err != nil {
log.Error("loadConf vote_num error(%v)", err)
}
}
// Close kafka consumer close.
func (s *Service) Close() {
if s == nil {
return
}
if s.dao != nil {
s.dao.Close()
}
if s.credbSub != nil {
s.credbSub.Close()
}
if s.replyAllSub != nil {
s.replyAllSub.Close()
}
s.wg.Wait()
}

View File

@@ -0,0 +1,31 @@
package service
import (
"flag"
"path/filepath"
"testing"
"time"
"go-common/app/job/main/credit/conf"
. "github.com/smartystreets/goconvey/convey"
)
var (
s *Service
)
func init() {
dir, _ := filepath.Abs("../cmd/convey-test.toml")
flag.Set("conf", dir)
conf.Init()
s = New(conf.Conf)
time.Sleep(time.Second)
}
func TestService_loadCase(t *testing.T) {
Convey("should return err be nil", t, func() {
s.loadConf()
s.loadCase()
})
}