Initial commit

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

10
app/interface/main/space/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
.idea/*
.project
.buildpath
.externalToolBuilders
.settings
.DS_Store
.a
*.iml
.vscode/*
space

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/interface/main/space/cmd:all-srcs",
"//app/interface/main/space/conf:all-srcs",
"//app/interface/main/space/dao:all-srcs",
"//app/interface/main/space/http:all-srcs",
"//app/interface/main/space/model:all-srcs",
"//app/interface/main/space/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,393 @@
### space
#### Version 2.8.2
##### Features
> 1.arc search list add field.
#### Version 2.8.1
##### Features
> 1.dynamic/list must need dynamic data.
#### Version 2.8.0
##### Features
> 1.新增 app/top/photo 接口
#### Version 2.7.2
##### Features
> 1.errgroup with context
> 2.channel redis cache fix
#### Version 2.7.1
##### Features
> 1.errgroup change
> 2.max dy card cnt rule change
#### Version 2.7.0
##### Features
> 1.稿件列表切换数据源
> 2.app/index get top photo change.
#### Version 2.6.0
##### Features
> 1.空间禁止mid
#### Version 2.5.6
##### Features
> 1.top arc res nil.
#### Version 2.5.5
##### Features
> 1.acc info privacy fix.
#### Version 2.5.4
##### Features
> 1.acc info add coin field.
#### Version 2.5.3
##### Features
> 1.fix masterpiece nil.
#### Version 2.5.2
##### Features
> 1.fix masterpiece empty cache.
#### Version 2.5.1
##### Features
> 1.fix masterpiece panic.
#### Version 2.5.0
##### Features
> 1.rm prom error
#### Version 2.4.1
##### Features
> 1.app/index internal
> 2.cache change to fanout
#### Version 2.4.0
##### Features
> 1.空间禁止mid
#### Version 2.3.1
##### Features
> 1.tab game字段fix
#### Version 2.3.0
##### Features
> 1.dynamic/list 新增privacy字段
#### Version 2.2.1
##### Features
> 1.shop 相关依赖接口替换
#### Version 2.2.0
##### Features
> 1.rm net ip.
#### Version 2.1.0
##### Features
> 1.dynamic/list 接口合并,折叠功能
> 2.ugc pay 相关修改
#### Version 2.0.0
##### Features
> 1.arc,arcs,coin 切 grpc
#### Version 1.26.0
##### Features
> 1.新增web/index internal聚合接口
#### Version 1.25.0
##### Features
> 1.notice新增block逻辑
#### Version 1.24.3
##### Features
> 1.app/index tab vmid fix.
#### Version 1.24.2
##### Features
> 1.app/index game tab fix.
#### Version 1.24.1
##### Features
> 1.app/index 接口新增be_relation信息
#### Version 1.24.0
##### Features
> 1.新增acc/relation 接口
> 2.fix fmt 错误
> 3.mc 使用生成器生成json改成pb
#### Version 1.23.0
##### Features
> 1.新增acc/relation接口
#### Version 1.22.0
##### Features
> 1.新增app/player/game 接口
#### Version 1.21.1
##### Features
> 1.通过 member 获取封禁信息
#### Version 1.21.0
##### Features
> 1.app/index 支持 pad
#### Version 1.20.5
##### Bug Fixes
> 1.coin/list 新增投币相关字段
#### Version 1.20.4
##### Bug Fixes
> 1.app/index block返回是否封禁过期
#### Version 1.20.3
##### Bug Fixes
> 1.top photo 调用url fix
#### Version 1.20.2
##### Features
> 1.coin/video 错误返回空 list
#### Version 1.20.1
##### Features
> 1.dynamic返回数据extension支持
#### Version 1.20.0
##### Features
> 1.app/index 新增封禁,挂件相关字段
#### Version 1.19.9
##### Features
> 1.hbase conf 兼容性修改
#### Version 1.19.8
##### Features
> 1.hbase 包修改
#### Version 1.19.7
##### Bug Fixes
> 1.dynamic/list 接口第二页数据问题
#### Version 1.19.6
##### Features
> 1.新增 acc/info internal接口
> 2.改用metadata.remoteIP
> 3.use bm
#### Version 1.19.5
##### Features
> 1.新增番剧tab
#### Version 1.19.4
##### Features
> 1.fav/arc参数order fix
#### Version 1.19.3
##### Features
> 1.fav搜全部收藏夹参数fix
#### Version 1.19.2
##### Features
> 1.番剧tab先取消
#### Version 1.19.1
##### Features
> 1.fav nav 接口新增权限判断
#### Version 1.19.0
##### Features
> 1.新增fav video 接口
> 2.tab 新增番剧
#### Version 1.18.0
##### Features
> 1.rm http parse
> 2.identify grpc
#### Version 1.17.5
##### Features
> 1.修改访问直播房间uri
> 2.修改访问动态列表uri
#### Version 1.17.4
##### Features
> 1.rm omitempty.
#### Version 1.17.3
##### Features
> 1.fix privacy set panic.
#### Version 1.17.1
##### Features
> 1.新增fans_group.
#### Version 1.17.0
##### Features
> 1.新增web端用户信息接口
> 2.新增用户拥有主题列表接口
> 3.新增空间玩过的游戏接口
#### Version 1.16.4
##### Bug Fixes
> 1.fix privacy batch edit cache error.
#### Version 1.16.3
##### Bug Fixes
> 1.fix relation empty struct.
#### Version 1.16.1
##### Bug Fixes
> 1.dynamic list privacy fix.
#### Version 1.16.0
##### Features
> 1.新增h5空间置顶取消置顶接口
> 2.新增app首页动态列表接口
> 3.新增空间稿件搜索,空间稿件列表接口
#### Version 1.15.3
##### Bug Fixes
> 1.fix privacy field word.
#### Version 1.15.2
##### Bug Fixes
> 1.index order 数据异常兼容
#### Version 1.15.1
##### Features
> 1.去除多余配置
#### Version 1.15.0
##### Features
> 1.nav num 新增audio字段
#### Version 1.14.1
##### Features
> 1.myinfo 接口新增用户等级详细信息
#### Version 1.14.0
##### Features
> 1.新增lastplaygame接口
> 2.新增空间稿件列表接口
#### Version 1.14.0
##### Features
> 1.新增internal接口
> 2.fix setting 逻辑
#### Version 1.13.0
##### Features
> 1.迁移到main目录
#### Version 1.12.0
##### Features
> 1.新增我的信息接口
> 2.新增用户标签,用户签名相关操作接口
> 3.新增置顶视频,代表作操作接口
> 4.新增空间公告接口
#### Version 1.11.1
##### Features
> 1.使用account-service v7
#### Version 1.11.0
##### Features
> 1.新增 tag 相关操作接口
> 2.新增 bangumi 订阅相关操作接口
> 3.新增 coin video 接口
> 4.新增 setting 相关操作接口
#### Version 1.10.2
##### Features
> 1.nav 接口vmid fix
#### Version 1.10.1
##### Features
> 1.fav 相关接口传mid 和 vmid
#### Version 1.10.0
##### Features
> 1.album/index 接口报错返回空list
#### Version 1.9.0
##### Features
> 1.fav/nav 接口新增movie字段
#### Version 1.8.0
##### Features
> 1.新增 album/index,fav/nav 接口
> 2.navnum 接口新增album字段
#### Version 1.7.0
##### Features
> 1.接入 bm
#### Version 1.6.1
##### Features
> 1.新增 shop ecode
#### Version 1.6.0
##### Features
> 1.新增 shop 接口
#### Version 1.5.2
##### Features
> 1.arc panic fix
#### Version 1.5.1
##### Features
> 1.修改失效稿件返回字段
> 2.配合log修改发布
#### Version 1.5.0
##### Features
> 1.新增upstat接口返回总视频和专栏阅读数
#### Version 1.4.0
##### Features
> 1.nav num 添加playlist
#### Version 1.3.1
##### Features
> 1.errgroup 引包修改
#### Version 1.3.0
##### Features
> 1.专栏文章列表新增功能
#### Version 1.2.2
##### Features
> 1.Archive2 to Archive3
#### Version 1.2.1
##### Bug Fixes
> 1.rider empty list
#### Version 1.2.0
##### Features
> 1.channel 修改加屏蔽开关
##### Bug Fixes
> 1.channel redis AddFlat to Add
#### Version 1.1.1
##### Bug Fixes
> 1.channel index panic 修改
#### Version 1.1.0
##### Bug Fixes
> 1.channel count 判断逻辑修改
> 2.del channel cache 新增删除sort缓存
#### Version 1.0.1
##### Features
> 1.redis receive 修改
#### Version 1.0.0
##### Features
> 1.初始化项目
> 2.新增频道相关接口
> 3.新增协管相关接口
> 4.新增up主专栏接口

View File

@@ -0,0 +1,11 @@
# Owner
liweijia
zhapuyu
# Author
wuhao02
# Reviewer
zhapuyu
guanyanliang
liweijia

View File

@@ -0,0 +1,17 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- liweijia
- wuhao02
- zhapuyu
labels:
- interface
- interface/main/space
- main
options:
no_parent_owners: true
reviewers:
- guanyanliang
- liweijia
- wuhao02
- zhapuyu

View File

@@ -0,0 +1,18 @@
#### web-interface
##### 项目简介
> 1.提供空间接口
##### 编译环境
> 请使用golang v1.8.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common
##### 编译执行
> 在主目录执行go build。
> 编译后可执行 ./cmd/cmd -conf space-test.toml 使用项目本地配置文件启动服务。
> 也可执行 ./space -conf_appid=space -conf_version=v2.1.0 -conf_host=172.16.33.134:9011 -conf_path=/data/conf/web-interface -conf_env=10 -conf_token=SEHXM8x1vYhIUaZvQUmyWnMYJrF9jHJY 使用配置中心测试环境配置启动服务如无法启动可检查token是否正确。
##### 特别说明
> http接口文档可参考 http://info.bilibili.co/pages/viewpage.action?pageId=4531201

View File

@@ -0,0 +1,49 @@
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 = ["space-test.toml"],
importpath = "go-common/app/interface/main/space/cmd",
tags = ["automanaged"],
deps = [
"//app/interface/main/space/conf:go_default_library",
"//app/interface/main/space/http:go_default_library",
"//app/interface/main/space/service:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/trace: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"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)

View File

@@ -0,0 +1,51 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/interface/main/space/conf"
"go-common/app/interface/main/space/http"
"go-common/app/interface/main/space/service"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init error(%v)", err)
panic(err)
}
log.Init(conf.Conf.Log)
trace.Init(conf.Conf.Tracer)
defer trace.Close()
defer log.Close()
log.Info("space-interface start")
// ecode
ecode.Init(conf.Conf.Ecode)
//server init
svr := service.New(conf.Conf)
http.Init(conf.Conf, svr)
// signal handler
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("space get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("space-interface exit")
time.Sleep(time.Second)
return
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}

View File

@@ -0,0 +1,172 @@
# This is a TOML document. Boom.
[identify]
whiteAccessKey = ""
whiteMid = 0
[identify.app]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
[identify.memcache]
name = "go-business/identify"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 10
idle = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://passport.bilibili.com"
secret = "http://open.bilibili.com"
[identify.httpClient]
key = "7c7ac0db1aa05587"
secret = "9a6d62d93290c5f771ad381e9ca23f26"
dial = "30ms"
timeout = "150ms"
keepAlive = "60s"
[identify.httpClient.breaker]
window ="10s"
sleep ="100ms"
bucket = 10
ratio = 0.5
request = 100
[identify.httpClient.url]
"http://passport.bilibili.co/intranet/auth/tokenInfo" = {timeout = "100ms"}
"http://passport.bilibili.co/intranet/auth/cookieInfo" = {timeout = "100ms"}
"http://open.bilibili.co/api/getsecret" = {timeout = "500ms"}
[supervisor]
On = true
Begin = "2018-01-20T00:00:00+08:00"
End = "2018-01-30T23:59:59+08:00"
[log]
dir = "/data/log/space-interface/"
#[log.syslog]
# proto = "udp"
# addr = "172.18.19.22:9999"
# project = "space"
# chanSize = 10240
[app]
key = "364a740488811396"
secret = "995a63b0bae95afd7d1b0b892d0e14d2"
[HTTPServer]
addr = "0.0.0.0:6901"
timeout = "1s"
[mysql]
addr = "172.16.33.205"
dsn = "space:9TtI2XkoEqk6GpIL@tcp(172.16.33.205:3306)/space?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
idleTimeout = "4h"
queryTimeout = "100ms"
execTimeout = "100ms"
tranTimeout = "200ms"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[hbase]
master = ""
meta = ""
dialTimeout = "1s"
readTimeout = "300ms"
readsTimeout = "600ms"
writeTimeout = "200ms"
writesTimeout = "600ms"
[hbase.zookeeper]
root = ""
addrs = ["10.23.58.154:2181","10.23.58.141:2181","10.23.58.20:2181"]
timeout = "30s"
[redis]
name = "space/channel"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 10
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
clExpire = "10m"
upArtExpire = "24h"
upArcExpire = "24h"
[memcache]
proto = "tcp"
addr = "127.0.0.1:11211"
idle = 10
active = 10
dialTimeout = "2s"
readTimeout = "2s"
writeTimeout = "2s"
idleTimeout = "80s"
expire = "1h"
settingExpire = "24h"
noticeExpire = "24h"
topArcExpire = "24h"
mpExpire = "24h"
themeExpire = "24h"
[rule]
maxChNameLen = 20
maxChIntroLen = 60
maxChLimit = 10
maxChArcLimit = 300
MaxChArcAddLimit = 100
maxChArcsPs = 100
maxRiderPs = 30
maxArticlePs = 30
chIndexCnt = 5
maxNoticeLen = 150
maxTopReasonLen = 40
maxMpReasonLen = 40
maxMpLimit = 3
BlackFre="3s"
[httpClient]
[httpClient.read]
key = "364a740488811396"
secret = "995a63b0bae95afd7d1b0b892d0e14d2"
dial = "1s"
timeout = "300ms"
keepAlive = "60s"
[httpClient.write]
key = "364a740488811396"
secret = "995a63b0bae95afd7d1b0b892d0e14d2"
dial = "1s"
timeout = "2s"
keepAlive = "60s"
[httpClient.game]
key = "EeOpM531WqQnBvu4"
secret = "gHtKtXTHZJDqGP1tg9ORFs0YWV3kW12V"
dial = "1s"
timeout = "500ms"
keepAlive = "60s"
[host]
api = "http://uat-api.bilibili.co"
bangumi = "http://uat-bangumi.bilibili.com"
show = "http://uat-show.bilibili.co"
mall = "http://fat1-mall.bilibili.co"
apivc = "http://api.vc.bilibili.co"
apilive = "http://api.live.bilibili.co"
acc = "http://account.bilibili.co"
game = "http://api.biligame.com"
search = "http://s.search.bilibili.co"
space = "http://space.bilibili.co"
elec = "http://uat-elec.bilibili.com"
#appGame = "http://line1-game-open-api.biligame.net"
[routerConfig]
[routerConfig.supervisor]
On = true
Begin = "2017-10-17T00:00:00+08:00"
End = "2017-10-30T23:59:59+08:00"

View File

@@ -0,0 +1,50 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/interface/main/space/conf",
tags = ["automanaged"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf:go_default_library",
"//library/database/hbase.v2:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/supervisor:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//library/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"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)

View File

@@ -0,0 +1,211 @@
package conf
import (
"errors"
"flag"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
"go-common/library/database/sql"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/supervisor"
"go-common/library/net/http/blademaster/middleware/verify"
"go-common/library/net/rpc"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"go-common/library/time"
"go-common/library/database/hbase.v2"
"github.com/BurntSushi/toml"
)
// global var
var (
confPath string
client *conf.Client
// Conf config
Conf = &Config{}
)
// Config config set
type Config struct {
// elk
Log *log.Config
// App
App *blademaster.App
// tracer
Tracer *trace.Config
// Auth
Auth *auth.Config
// Verify
Verify *verify.Config
// Supervisor
Supervisor *supervisor.Config
// BM
BM *httpServers
// HTTPServer
HTTPServer *blademaster.ServerConfig
// Ecode
Ecode *ecode.Config
// ArchiveRPC
AccountRPC *rpc.ClientConfig
ArticleRPC *rpc.ClientConfig
AssistRPC *rpc.ClientConfig
TagRPC *rpc.ClientConfig
FavoriteRPC *rpc.ClientConfig
FilterRPC *rpc.ClientConfig
ThumbupRPC *rpc.ClientConfig
RelationRPC *rpc.ClientConfig
MemberRPC *rpc.ClientConfig
// grpc
AccClient *warden.ClientConfig
ArcClient *warden.ClientConfig
CoinClient *warden.ClientConfig
UpClient *warden.ClientConfig
// Mysql
Mysql *sql.Config
// Redis
Redis *redisConf
// Mc
Memcache *memConf
// Rule
Rule *rule
// HTTP client
HTTPClient *httpClient
// Host
Host *host
// HBase hbase config
HBase *Hbase
}
type redisConf struct {
*redis.Config
ClExpire time.Duration
UpArtExpire time.Duration
UpArcExpire time.Duration
}
type memConf struct {
*memcache.Config
SettingExpire time.Duration
NoticeExpire time.Duration
TopArcExpire time.Duration
MpExpire time.Duration
ThemeExpire time.Duration
TopDyExpire time.Duration
}
type rule struct {
MaxChNameLen int
MaxChIntroLen int
MaxChLimit int
MaxChArcLimit int
MaxChArcAddLimit int
MaxChArcsPs int
MaxRiderPs int
MaxArticlePs int
ChIndexCnt int
MaxNoticeLen int
MaxTopReasonLen int
MaxMpReasonLen int
MaxMpLimit int
// RealNameOn
RealNameOn bool
// No limit notice mids
NoNoticeMids []int64
// default top photo
TopPhoto string
// dynamic list switch
Merge bool
ActFold bool
// block mids
BlockMids []int64
//BlackFre space blacklist frequency
BlackFre time.Duration
}
type host struct {
Bangumi string
API string
Mall string
APIVc string
APILive string
Acc string
Game string
AppGame string
Search string
Elec string
Space string
}
type httpClient struct {
Read *blademaster.ClientConfig
Write *blademaster.ClientConfig
Game *blademaster.ClientConfig
}
type httpServers struct {
Outer *blademaster.ServerConfig
}
// Hbase .
type Hbase struct {
*hbase.Config
ReadTimeout time.Duration
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init init conf
func Init() 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,126 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"account_test.go",
"album_test.go",
"archive_test.go",
"audio_test.go",
"bangumi_test.go",
"blacklist_test.go",
"bplus_test.go",
"channel_redis_test.go",
"dao.cache_test.go",
"dao_test.go",
"elec_test.go",
"fav_test.go",
"game_test.go",
"hbase_test.go",
"index_order_test.go",
"live_test.go",
"masterpiece_test.go",
"mc.cache_test.go",
"mysql_test.go",
"notice_test.go",
"privacy_test.go",
"redis_test.go",
"shop_test.go",
"tag_test.go",
"theme_test.go",
"top_arc_test.go",
"top_dy_test.go",
"top_photo_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/space/conf:go_default_library",
"//app/interface/main/space/model:go_default_library",
"//library/ecode: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 = [
"account.go",
"album.go",
"archive.go",
"audio.go",
"bangumi.go",
"blacklist.go",
"bplus.go",
"cache.go",
"channel_redis.go",
"dao.cache.go",
"dao.go",
"elec.go",
"fav.go",
"game.go",
"hbase.go",
"index_order.go",
"live.go",
"masterpiece.go",
"mc.cache.go",
"mysql.go",
"notice.go",
"privacy.go",
"redis.go",
"shop.go",
"tag.go",
"theme.go",
"top_arc.go",
"top_dy.go",
"top_photo.go",
],
importpath = "go-common/app/interface/main/space/dao",
tags = ["automanaged"],
deps = [
"//app/interface/main/space/conf:go_default_library",
"//app/interface/main/space/model:go_default_library",
"//app/service/main/favorite/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/hbase.v2: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/net/metadata:go_default_library",
"//library/stat/prom:go_default_library",
"//library/sync/pipeline/fanout:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
"//vendor/github.com/tsuna/gohbase/hrpc: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"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)

View File

@@ -0,0 +1,98 @@
package dao
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strconv"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_accTagsURI = "/api/tag/get"
_accTagsSetURI = "/api/tag/set"
_liveMetalURI = "/fans_medal/v1/medal/get_medal_opened"
_isAnsweredURI = "/x/internal/credit/labour/isanswered"
)
// AccTags get account tags.
func (d *Dao) AccTags(c context.Context, mid int64) (data json.RawMessage, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mids", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
List json.RawMessage `json:"list"`
}
if err = d.httpR.Get(c, d.accTagsURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s) error(%v)", d.accTagsURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s) code(%d) error", d.accTagsURL, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.List
return
}
// SetAccTags set account tags.
func (d *Dao) SetAccTags(c context.Context, tags, ck string) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("tags", tags)
var req *http.Request
if req, err = d.httpW.NewRequest(http.MethodGet, d.accTagsSetURL, ip, params); err != nil {
log.Error("d.httpW.NewRequest(%s) error(%v)", d.accTagsSetURL, err)
return
}
req.Header.Set("Cookie", ck)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Do(c, req, &res); err != nil {
log.Error("d.httpW.Do(%s) error(%v)", d.accTagsSetURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpW.Get(%s) code(%d) error", d.accTagsSetURL, res.Code)
err = ecode.Int(res.Code)
}
return
}
// IsAnswered get if block account answered.
func (d *Dao) IsAnswered(c context.Context, mid, start int64) (status int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("start", strconv.FormatInt(start, 10))
var res struct {
Code int `json:"code"`
Data struct {
Status int `json:"status"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.isAnsweredURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s) error(%v)", d.isAnsweredURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s) code(%d) error", d.isAnsweredURL, res.Code)
err = ecode.Int(res.Code)
return
}
status = res.Data.Status
return
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAccTags(t *testing.T) {
convey.Convey("AccTags", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.AccTags(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoIsAnswered(t *testing.T) {
convey.Convey("IsAnswered", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
start = time.Now().Unix()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
status, err := d.IsAnswered(c, mid, start)
ctx.Convey("Then err should be nil.status should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(status, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,69 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_albumCountURI = "/link_draw/v1/doc/upload_count"
_albumListURI = "/link_draw/v1/doc/doc_list"
)
// AlbumCount get album count.
func (d *Dao) AlbumCount(c context.Context, mid int64) (count int64, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("uid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data model.AlbumCount `json:"data"`
}
if err = d.httpR.Get(c, d.albumCountURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s) mid(%d) error(%v)", d.albumCountURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s) mid(%d) code(%d)", d.albumCountURL, mid, res.Code)
err = ecode.Int(res.Code)
return
}
count = res.Data.AllCount
return
}
// AlbumList get album list.
func (d *Dao) AlbumList(c context.Context, mid int64, pn, ps int) (list []*model.Album, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("uid", strconv.FormatInt(mid, 10))
params.Set("page_num", strconv.Itoa(pn))
params.Set("page_size", strconv.Itoa(ps))
var res struct {
Code int `json:"code"`
Data struct {
Items []*model.Album `json:"items"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.albumListURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s) mid(%d) error(%v)", d.albumListURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s) mid(%d) code(%d)", d.albumListURL, mid, res.Code)
err = ecode.Int(res.Code)
return
}
list = res.Data.Items
return
}

View File

@@ -0,0 +1,28 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_AlbumCount(t *testing.T) {
convey.Convey("test album count", t, func(ctx convey.C) {
mid := int64(28272030)
data, err := d.AlbumCount(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%d", data)
})
}
func TestDao_AlbumList(t *testing.T) {
convey.Convey("test album list", t, func(ctx convey.C) {
mid := int64(28272030)
pn := 0
ps := 1
data, err := d.AlbumList(context.Background(), mid, pn, ps)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}

View File

@@ -0,0 +1,60 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_arcSearchURI = "/space/search/v2"
_arcSearchType = "sub_video"
_additionalRanks = "-6"
)
// ArcSearchList archive search.
func (d *Dao) ArcSearchList(c context.Context, arg *model.SearchArg) (data *model.SearchRes, total int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("search_type", _arcSearchType)
params.Set("additional_ranks", _additionalRanks)
if arg.Mid > 0 {
params.Set("mid", strconv.FormatInt(arg.Mid, 10))
}
params.Set("page", strconv.Itoa(arg.Pn))
params.Set("pagesize", strconv.Itoa(arg.Ps))
params.Set("clientip", ip)
if arg.Tid > 0 {
params.Set("tid", strconv.FormatInt(arg.Tid, 10))
}
if arg.Order != "" {
params.Set("order", arg.Order)
}
if arg.Keyword != "" {
params.Set("keyword", arg.Keyword)
}
var res struct {
Code int `json:"code"`
Total int `json:"total"`
Result *model.SearchRes `json:"result"`
}
if err = d.httpR.Get(c, d.arcSearchURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s,%v) error(%v)", d.arcSearchURL, arg, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%v) code error(%d)", d.arcSearchURL, arg, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Result
total = res.Total
return
}

View File

@@ -0,0 +1,29 @@
package dao
import (
"context"
"encoding/json"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_ArcSearchList(t *testing.T) {
convey.Convey("test search arc list", t, func(ctx convey.C) {
arg := &model.SearchArg{
Mid: 2,
Tid: 0,
Order: "",
Keyword: "",
Pn: 1,
Ps: 20,
}
data, count, err := d.ArcSearchList(context.Background(), arg)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%d", count)
str, _ := json.Marshal(data)
convey.Printf("%s", string(str))
})
}

View File

@@ -0,0 +1,88 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/net/metadata"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_audioCntURI = "/x/internal/v1/audio/personal/audio-cnt"
_audioCardURI = "/x/internal/v1/audio/privilege/mcard"
_audioUpperCertURI = "/audio/music-service-c/internal/upper-cert"
)
// AudioCard get audio card info.
func (d *Dao) AudioCard(c context.Context, mid ...int64) (cardm map[int64]*model.AudioCard, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", xstr.JoinInts(mid))
var res struct {
Code int `json:"code"`
Data map[int64]*model.AudioCard `json:"data"`
}
if err = d.httpR.Get(c, d.audioCardURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.audioCardURL+"?"+params.Encode())
return
}
cardm = res.Data
return
}
// AudioUpperCert get audio upper cert.
func (d *Dao) AudioUpperCert(c context.Context, uid int64) (cert *model.AudioUpperCert, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("uid", strconv.FormatInt(uid, 10))
var res struct {
Code int `json:"code"`
Data *model.AudioUpperCert `json:"data"`
}
if err = d.httpR.Get(c, d.audioUpperCertURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.audioUpperCertURL+"?"+params.Encode())
return
}
cert = res.Data
return
}
// AudioCnt get audio cnt.
func (d *Dao) AudioCnt(c context.Context, mid int64) (count int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
Song int `json:"song"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.audioCntURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.audioCntURL+"?"+params.Encode())
return
}
count = res.Data.Song
return
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_AudioCard(t *testing.T) {
convey.Convey("test audio card", t, func(ctx convey.C) {
mid := int64(28272030)
data, err := d.AudioCard(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_AudioUpperCert(t *testing.T) {
convey.Convey("test audio upper cert", t, func(ctx convey.C) {
mid := int64(28272030)
data, err := d.AudioUpperCert(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_AudioCnt(t *testing.T) {
convey.Convey("test audio cnt", t, func(ctx convey.C) {
mid := int64(28272030)
data, err := d.AudioCnt(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}

View File

@@ -0,0 +1,98 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_build = "0"
_platform = "web"
_bangumiURI = "/api/get_concerned_season"
_bangumiConcernURI = "/api/concern_season"
_bangumiUnConcernURI = "/api/unconcern_season"
)
// BangumiList get bangumi sub list by mid.
func (d *Dao) BangumiList(c context.Context, mid int64, pn, ps int) (data []*model.Bangumi, count int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("page", strconv.Itoa(pn))
params.Set("pagesize", strconv.Itoa(ps))
params.Set("build", _build)
params.Set("platform", _platform)
var res struct {
Code int `json:"code"`
Count string `json:"count"`
Result []*model.Bangumi `json:"result"`
}
if err = d.httpR.Get(c, d.bangumiURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.bangumiURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.bangumiURL, mid, err)
err = ecode.Int(res.Code)
return
}
data = res.Result
count, _ = strconv.Atoi(res.Count)
return
}
// BangumiConcern bangumi concern.
func (d *Dao) BangumiConcern(c context.Context, mid, seasonID int64) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("season_id", strconv.FormatInt(seasonID, 10))
params.Set("build", _build)
params.Set("platform", _platform)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.bangumiConcernURL, ip, params, &res); err != nil {
log.Error("d.httpW.Post(%s,%d) error(%v)", d.bangumiConcernURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpW.Post(%s,%d) error(%v)", d.bangumiConcernURL, mid, err)
err = ecode.Int(res.Code)
}
return
}
// BangumiUnConcern bangumi cancel sub.
func (d *Dao) BangumiUnConcern(c context.Context, mid, seasonID int64) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("season_id", strconv.FormatInt(seasonID, 10))
params.Set("build", _build)
params.Set("platform", _platform)
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.bangumiUnConcernURL, ip, params, &res); err != nil {
log.Error("d.httpW.Post(%s,%d) error(%v)", d.bangumiUnConcernURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpW.Post(%s,%d) error(%v)", d.bangumiUnConcernURL, mid, err)
err = ecode.Int(res.Code)
}
return
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_BangumiList(t *testing.T) {
convey.Convey("test bangumi list", t, func(ctx convey.C) {
data, count, err := d.BangumiList(context.Background(), 908085, 1, 10)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
convey.Printf("%d", count)
})
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"context"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_blacklistSQL = `SELECT mid FROM blacklist WHERE status = 0`
)
// Blacklist get blacklist from db.
func (d *Dao) Blacklist(c context.Context) (blacklist []int64, err error) {
var (
rows *xsql.Rows
)
if rows, err = d.db.Query(c, _blacklistSQL); err != nil {
log.Error("dao.Modules.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var mid int64
if err = rows.Scan(&mid); err != nil {
log.Error("Space dao Modules:row.Scan() error(%v)", err)
return
}
blacklist = append(blacklist, mid)
}
if err = rows.Err(); err != nil {
log.Error("Space dao Modules.Err() error(%v)", err)
}
return
}

View File

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

View File

@@ -0,0 +1,134 @@
package dao
import (
"context"
"net/http"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_groupsCountURI = "/link_group/v1/member/created_groups_num"
_dynamicListURI = "/dynamic_svr/v0/dynamic_svr/co_space_history"
_dynamicCntURI = "/dynamic_svr/v0/dynamic_svr/space_dy_num"
_dynamicURI = "/dynamic_svr/v1/dynamic_svr/get_dynamic_detail"
)
// GroupsCount .
func (d *Dao) GroupsCount(c context.Context, mid, vmid int64) (count int, err error) {
var (
req *http.Request
ip = metadata.String(c, metadata.RemoteIP)
)
params := url.Values{}
params.Set("master_uid", strconv.FormatInt(vmid, 10))
if req, err = d.httpR.NewRequest(http.MethodGet, d.groupsCountURL, ip, params); err != nil {
return
}
req.Header.Set("X-BiliLive-UID", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data *struct {
Num int `json:"num"`
}
}
if err = d.httpR.Do(c, req, &res); err != nil {
err = errors.Wrapf(err, "url(%s) header(X-BiliLive-UID:%s)", req.URL.String(), req.Header.Get("X-BiliLive-UID"))
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrapf(ecode.Int(res.Code), "url(%s) header(X-BiliLive-UID:%s)", req.URL.String(), req.Header.Get("X-BiliLive-UID"))
return
}
if res.Data != nil {
count = res.Data.Num
}
return
}
// DynamicCnt dynamic count.
func (d *Dao) DynamicCnt(c context.Context, mid int64) (cnt int64, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("uids", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
Items []*struct {
UID int64 `json:"uid"`
Num int64 `json:"num"`
} `json:"items"`
}
}
if err = d.httpR.Get(c, d.dynamicCntURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.dynamicCntURL+"?"+params.Encode())
return
}
if len(res.Data.Items) > 0 && res.Data.Items[0].UID == mid {
cnt = res.Data.Items[0].Num
}
return
}
// DynamicList .
func (d *Dao) DynamicList(c context.Context, mid, vmid, dyID int64, qn, page int) (data *model.DyList, err error) {
ip := metadata.String(c, metadata.RemoteIP)
params := url.Values{}
if mid > 0 {
params.Set("visitor_uid", strconv.FormatInt(mid, 10))
}
params.Set("host_uid", strconv.FormatInt(vmid, 10))
params.Set("offset_dynamic_id", strconv.FormatInt(dyID, 10))
params.Set("qn", strconv.Itoa(qn))
params.Set("page", strconv.Itoa(page))
var res struct {
Code int `json:"code"`
Data *model.DyList `json:"data"`
}
if err = d.httpR.Get(c, d.dynamicListURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.dynamicListURL+"?"+params.Encode())
return
}
data = res.Data
return
}
// Dynamic .
func (d *Dao) Dynamic(c context.Context, mid, dynamicID int64, qn int) (data *model.DyCard, err error) {
ip := metadata.String(c, metadata.RemoteIP)
params := url.Values{}
if mid > 0 {
params.Set("uid", strconv.FormatInt(mid, 10))
}
params.Set("dynamic_id", strconv.FormatInt(dynamicID, 10))
params.Set("qn", strconv.Itoa(qn))
var res struct {
Code int `json:"code"`
Data struct {
Card *model.DyCard `json:"card"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.dynamicURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.dynamicURL+"?"+params.Encode())
return
}
data = res.Data.Card
return
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
"testing"
"gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_GroupsCount(t *testing.T) {
convey.Convey("test group count", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.groupsCountURL).Reply(200).JSON(`{"code":0,"data":{"num":1}}`)
mid := int64(28272030)
vmid := int64(28272030)
data, err := d.GroupsCount(context.Background(), mid, vmid)
convey.So(err, convey.ShouldBeNil)
convey.So(data, convey.ShouldNotBeNil)
convey.Printf("%d", data)
})
}
func TestDao_DynamicCnt(t *testing.T) {
convey.Convey("test dynamic cnt", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.dynamicCntURL).Reply(200).JSON(`{"code":0,"msg":"","message":"","data":{"items":[{"uid":2089809,"num":345}],"_gt_":0}}`)
vmid := int64(2089809)
data, err := d.DynamicCnt(context.Background(), vmid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%d", data)
})
}
func TestDao_DynamicList(t *testing.T) {
convey.Convey("test dynamic list", t, func(ctx convey.C) {
mid := int64(29313802)
vmid := int64(34709144)
data, err := d.DynamicList(context.Background(), mid, vmid, 0, 16, 1)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%d", data)
})
}
func TestDao_Dynamic(t *testing.T) {
convey.Convey("test dynamic item", t, func(ctx convey.C) {
mid := int64(27515256)
dyID := int64(118606711587078278)
data, err := d.Dynamic(context.Background(), mid, dyID, 16)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}

View File

@@ -0,0 +1,59 @@
package dao
import (
"context"
"go-common/app/interface/main/space/model"
)
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache: -nullcache=&model.Notice{Notice:"ff2364a0be3d20e46cc69efb36afe9a5"} -check_null_code=$.Notice=="ff2364a0be3d20e46cc69efb36afe9a5"
Notice(c context.Context, mid int64) (*model.Notice, error)
// cache: -nullcache=&model.AidReason{Aid:-1} -check_null_code=$!=nil&&$.Aid==-1
TopArc(c context.Context, mid int64) (*model.AidReason, error)
// cache: -nullcache=&model.AidReasons{List:[]*model.AidReason{{Aid:-1}}} -check_null_code=len($.List)==1&&$.List[0].Aid==-1
Masterpiece(c context.Context, mid int64) (*model.AidReasons, error)
// cache: -nullcache=&model.ThemeDetails{List:[]*model.ThemeDetail{{ID:-1}}} -check_null_code=len($.List)==1&&$.List[0].ID==-1
Theme(c context.Context, mid int64) (*model.ThemeDetails, error)
// cache: -nullcache=-1 -check_null_code=$==-1
TopDynamic(c context.Context, mid int64) (int64, error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// get notice data from mc cache.
// mc: -key=noticeKey
CacheNotice(c context.Context, mid int64) (*model.Notice, error)
// set notice data to mc cache.
// mc: -key=noticeKey -expire=d.mcNoticeExpire -encode=pb
AddCacheNotice(c context.Context, mid int64, data *model.Notice) error
// mc: -key=noticeKey
DelCacheNotice(c context.Context, mid int64) error
// get top archive data from mc cache.
// mc: -key=topArcKey
CacheTopArc(c context.Context, mid int64) (*model.AidReason, error)
// set top archive data to mc cache.
// mc: -key=topArcKey -expire=d.mcTopArcExpire -encode=pb
AddCacheTopArc(c context.Context, mid int64, data *model.AidReason) error
// get top archive data from mc cache.
// mc: -key=masterpieceKey
CacheMasterpiece(c context.Context, mid int64) (*model.AidReasons, error)
// set top archive data to mc cache.
// mc: -key=masterpieceKey -expire=d.mcMpExpire -encode=pb
AddCacheMasterpiece(c context.Context, mid int64, data *model.AidReasons) error
// get theme data from mc cache.
// mc: -key=themeKey
CacheTheme(c context.Context, mid int64) (*model.ThemeDetails, error)
// set theme data to mc cache.
// mc: -key=themeKey -expire=d.mcThemeExpire -encode=pb
AddCacheTheme(c context.Context, mid int64, data *model.ThemeDetails) error
// mc: -key=themeKey
DelCacheTheme(c context.Context, mid int64) error
// get top dynamic id cache.
// mc: -key=topDyKey
CacheTopDynamic(c context.Context, key int64) (int64, error)
// set top dynamic id cache.
// mc: -key=topDyKey -expire=d.mcTopDyExpire -encode=raw
AddCacheTopDynamic(c context.Context, key int64, value int64) error
}

View File

@@ -0,0 +1,430 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyCl = "cl_%d"
_keyClArc = "cla_%d_%d"
)
func keyCl(mid int64) string {
return fmt.Sprintf(_keyCl, mid)
}
func keyClArc(mid, cid int64) string {
return fmt.Sprintf(_keyClArc, mid, cid)
}
func keyClArcSort(mid, cid int64) string {
return keyClArc(mid, cid) + "_s"
}
// ChannelCache get channel cache.
func (d *Dao) ChannelCache(c context.Context, mid, cid int64) (channel *model.Channel, err error) {
var (
bs []byte
key = keyCl(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = redis.Bytes(conn.Do("HGET", key, cid)); err != nil {
if err == redis.ErrNil {
err = nil
channel = nil
} else {
log.Error("conn.Do(HGET,%s,%d) error(%v)", key, cid, err)
}
return
}
channel = new(model.Channel)
if err = json.Unmarshal(bs, channel); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(bs), err)
}
return
}
// SetChannelCache add channel data cache.
func (d *Dao) SetChannelCache(c context.Context, mid, cid int64, channel *model.Channel) (err error) {
var (
bs []byte
ok bool
key = keyCl(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(channel); err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
if ok, err = redis.Bool(conn.Do("EXPIRE", key, d.clExpire)); err != nil || !ok {
log.Error("conn.Do(EXPIRE %s) error(%v)", key, err)
return
}
if err = conn.Send("HSET", key, cid, bs); err != nil {
log.Error("conn.Send(HSET,%s,%d) error(%v)", key, cid, err)
return
}
if err = conn.Send("EXPIRE", key, d.clExpire); err != nil {
log.Error("conn.Send(EXPIRE,%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("add conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("add conn.Receive()%d error(%v)", i+1, err)
return
}
}
return
}
// DelChannelCache delete channel cache from list.
func (d *Dao) DelChannelCache(c context.Context, mid, cid int64) (err error) {
var (
key = keyCl(mid)
arcsKey = keyClArc(mid, cid)
sortKey = keyClArcSort(mid, cid)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("HDEL", key, cid); err != nil {
log.Error("conn.Send(HDEL,%s,%d) error(%v)", key, cid, err)
return
}
if err = conn.Send("DEL", arcsKey); err != nil {
log.Error("conn.Send(DEL,%s) error(%v)", arcsKey, err)
}
if err = conn.Send("DEL", sortKey); err != nil {
log.Error("conn.Send(DEL,%s) error(%v)", sortKey, err)
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
for i := 0; i < 3; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("add conn.Receive()%d error(%v)", i+1, err)
return
}
}
return
}
// SetChannelListCache add channel data cache.
func (d *Dao) SetChannelListCache(c context.Context, mid int64, channelList []*model.Channel) (err error) {
var (
bs []byte
key = keyCl(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key, err)
return
}
args := redis.Args{}.Add(key)
for _, channel := range channelList {
if bs, err = json.Marshal(channel); err != nil {
log.Error("json.Marshal() error(%v)", err)
continue
} else {
args = args.Add(channel.Cid).Add(string(bs))
}
}
if err = conn.Send("HMSET", args...); err != nil {
log.Error("conn.Send(HMSET, %s) error(%v)", key, err)
return
}
if err = conn.Send("EXPIRE", key, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.clExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 3; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// ChannelListCache get channel list cache.
func (d *Dao) ChannelListCache(c context.Context, mid int64) (channels []*model.Channel, err error) {
var (
bss [][]byte
key = keyCl(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bss, err = redis.ByteSlices(conn.Do("HGETALL", key)); err != nil {
log.Error("conn.Do(HGETALL,%s) error(%v)", key, err)
return
}
for i := 1; i <= len(bss); i += 2 {
channel := new(model.Channel)
if err = json.Unmarshal(bss[i], channel); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", string(bss[i]), err)
continue
}
channels = append(channels, channel)
}
return
}
// ChannelArcsCache get channel archives cache.
func (d *Dao) ChannelArcsCache(c context.Context, mid, cid int64, start, end int, order bool) (arcs []*model.ChannelArc, err error) {
var (
bss [][]byte
values []interface{}
key = keyClArc(mid, cid)
sortKey = keyClArcSort(mid, cid)
conn = d.redis.Get(c)
cmd = "ZREVRANGE"
)
defer conn.Close()
if order {
cmd = "ZRANGE"
}
if values, err = redis.Values(conn.Do(cmd, sortKey, start, end, "WITHSCORES")); err != nil {
log.Error("conn.Do(ZREVRANGE, %s) error(%v)", sortKey, err)
return
} else if len(values) == 0 {
return
}
arg := redis.Args{}.Add(key)
for len(values) > 0 {
arcSort := new(model.ChannelArcSort)
if values, err = redis.Scan(values, &arcSort.Aid, &arcSort.OrderNum); err != nil {
log.Error("redis.Scan(%v) error(%v)", values, err)
return
}
if arcSort.Aid > 0 {
arg = arg.Add(arcSort.Aid)
}
}
if bss, err = redis.ByteSlices(conn.Do("HMGET", arg...)); err != nil {
log.Error("conn.Do(HMGET,%s) error(%v)", key, err)
return
}
for _, bs := range bss {
if len(bs) == 0 {
continue
}
if len(bs) > 0 {
arc := new(model.ChannelArc)
if err = json.Unmarshal(bs, arc); err != nil {
log.Error("json.Unmarshal(%s) mid(%d) cid(%d) error(%v)", string(bs), mid, cid, err)
err = nil
continue
}
arcs = append(arcs, arc)
}
}
return
}
// AddChannelArcCache add channel archives cache.
func (d *Dao) AddChannelArcCache(c context.Context, mid, cid int64, arcs []*model.ChannelArc) (err error) {
var (
bs []byte
ok bool
key = keyClArc(mid, cid)
sortKey = keyClArcSort(mid, cid)
conn = d.redis.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("EXPIRE", key, d.clExpire)); err != nil && ok {
log.Error("conn.Do(EXPIRE %s) error(%v)", key, err)
return
}
if ok, err = redis.Bool(conn.Do("EXPIRE", sortKey, d.clExpire)); err != nil && ok {
log.Error("conn.Do(EXPIRE %s) error(%v)", key, err)
return
}
args1 := redis.Args{}.Add(key)
args2 := redis.Args{}.Add(sortKey)
for _, arc := range arcs {
if bs, err = json.Marshal(arc); err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
args1 = args1.Add(arc.Aid).Add(string(bs))
args2 = args2.Add(arc.OrderNum).Add(arc.Aid)
}
if err = conn.Send("HMSET", args1...); err != nil {
log.Error("conn.Send(HMSET, %s, %v) error(%v)", key, args1, err)
return
}
if err = conn.Send("EXPIRE", key, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s) error(%v)", key, err)
return
}
if err = conn.Send("ZADD", args2...); err != nil {
log.Error("conn.Send(ZADD, %s, %v) error(%v)", sortKey, args2, err)
return
}
if err = conn.Send("EXPIRE", sortKey, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s) error(%v)", sortKey, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 4; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// SetChannelArcSortCache set channel archives sort cache
func (d *Dao) SetChannelArcSortCache(c context.Context, mid, cid int64, sort []*model.ChannelArcSort) (err error) {
var (
key = keyClArc(mid, cid)
sortKey = keyClArcSort(mid, cid)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", sortKey); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", sortKey, err)
return
}
args := redis.Args{}.Add(sortKey)
for _, v := range sort {
args = args.Add(v.OrderNum).Add(v.Aid)
}
if err = conn.Send("ZADD", args...); err != nil {
log.Error("conn.Send(ZADD, %s) error(%v)", sortKey, err)
return
}
if err = conn.Send("EXPIRE", sortKey, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", sortKey, d.clExpire, err)
return
}
if err = conn.Send("EXPIRE", key, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.clExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 4; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// DelChannelArcCache delete channel archive cache from cache list.
func (d *Dao) DelChannelArcCache(c context.Context, mid, cid, aid int64) (err error) {
key := keyClArc(mid, cid)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("HDEL", key, aid); err != nil {
log.Error("conn.Send(ZREM,%s,%d) error(%v)", key, aid, err)
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
}
return
}
// DelChannelArcsCache delete all channel arcs cache when delete channel
func (d *Dao) DelChannelArcsCache(c context.Context, mid, cid int64) (err error) {
key := keyClArc(mid, cid)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", key); err != nil {
log.Error("conn.Send(DEL,%s,%d,%d) error(%v)", key, mid, cid, err)
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
}
return
}
// SetChannelArcsCache add channel archive cache.
func (d *Dao) SetChannelArcsCache(c context.Context, mid, cid int64, arcs []*model.ChannelArc) (err error) {
var (
bs []byte
key1 = keyClArc(mid, cid)
key2 = keyClArcSort(mid, cid)
conn = d.redis.Get(c)
)
defer conn.Close()
if err = conn.Send("DEL", key1); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key1, err)
return
}
if err = conn.Send("DEL", key2); err != nil {
log.Error("conn.Send(DEL, %s) error(%v)", key2, err)
return
}
args1 := redis.Args{}.Add(key1)
args2 := redis.Args{}.Add(key2)
for _, arc := range arcs {
if bs, err = json.Marshal(arc); err != nil {
log.Error("json.Marshal() error(%v)", err)
continue
} else {
args1 = args1.Add(arc.Aid).Add(string(bs))
}
args2 = args2.Add(arc.OrderNum).Add(arc.Aid)
}
if err = conn.Send("HMSET", args1...); err != nil {
log.Error("conn.Send(HMSET, %s) error(%v)", key1, err)
return
}
if err = conn.Send("ZADD", args2...); err != nil {
log.Error("conn.Send(ZADD, %s) error(%v)", key2, err)
return
}
if err = conn.Send("EXPIRE", key1, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key1, d.clExpire, err)
return
}
if err = conn.Send("EXPIRE", key2, d.clExpire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key2, d.clExpire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 6; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,240 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyCl(t *testing.T) {
convey.Convey("keyCl", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyCl(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyClArc(t *testing.T) {
convey.Convey("keyClArc", t, func(ctx convey.C) {
var (
mid = int64(2222)
cid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyClArc(mid, cid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyClArcSort(t *testing.T) {
convey.Convey("keyClArcSort", t, func(ctx convey.C) {
var (
mid = int64(2222)
cid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyClArcSort(mid, cid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetChannelListCache(t *testing.T) {
convey.Convey("SetChannelListCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
channelList = []*model.Channel{{Cid: 2222, Mid: 2222, Name: "2222"}, {Cid: 3333, Mid: 2222, Name: "3333"}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetChannelListCache(c, mid, channelList)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetChannelCache(t *testing.T) {
convey.Convey("SetChannelCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
channel = &model.Channel{Cid: 2222, Mid: 2222}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetChannelCache(c, mid, cid, channel)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoChannelCache(t *testing.T) {
convey.Convey("ChannelCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
channel, err := d.ChannelCache(c, mid, cid)
ctx.Convey("Then err should be nil.channel should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(channel, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelChannelCache(t *testing.T) {
convey.Convey("DelChannelCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelChannelCache(c, mid, cid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoChannelListCache(t *testing.T) {
convey.Convey("ChannelListCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
channels, err := d.ChannelListCache(c, mid)
ctx.Convey("Then err should be nil.channels should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", channels)
})
})
})
}
func TestDaoChannelArcsCache(t *testing.T) {
convey.Convey("ChannelArcsCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
start = int(0)
end = int(1)
order bool
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
arcs, err := d.ChannelArcsCache(c, mid, cid, start, end, order)
ctx.Convey("Then err should be nil.arcs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.Printf("%+v", arcs)
})
})
})
}
func TestDaoAddChannelArcCache(t *testing.T) {
convey.Convey("AddChannelArcCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
arcs = []*model.ChannelArc{{ID: 2222, Mid: 2222, Cid: 2222, Aid: 2222}, {ID: 3333, Mid: 3333, Cid: 3333, Aid: 3333}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddChannelArcCache(c, mid, cid, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetChannelArcSortCache(t *testing.T) {
convey.Convey("SetChannelArcSortCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
sort = []*model.ChannelArcSort{{Aid: 4444, OrderNum: 100}, {Aid: 5555, OrderNum: 200}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetChannelArcSortCache(c, mid, cid, sort)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelChannelArcCache(t *testing.T) {
convey.Convey("DelChannelArcCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
aid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelChannelArcCache(c, mid, cid, aid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelChannelArcsCache(t *testing.T) {
convey.Convey("DelChannelArcsCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelChannelArcsCache(c, mid, cid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetChannelArcsCache(t *testing.T) {
convey.Convey("SetChannelArcsCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
cid = int64(2222)
arcs = []*model.ChannelArc{{ID: 2222, Mid: 2222, Cid: 2222, Aid: 2222}, {ID: 2222, Mid: 2222, Cid: 2222, Aid: 3333}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetChannelArcsCache(c, mid, cid, arcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,204 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package dao is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache: -nullcache=&model.Notice{Notice:"ff2364a0be3d20e46cc69efb36afe9a5"} -check_null_code=$.Notice=="ff2364a0be3d20e46cc69efb36afe9a5"
Notice(c context.Context, mid int64) (*model.Notice, error)
// cache: -nullcache=&model.AidReason{Aid:-1} -check_null_code=$!=nil&&$.Aid==-1
TopArc(c context.Context, mid int64) (*model.AidReason, error)
// cache: -nullcache=&model.AidReasons{List:[]*model.AidReason{{Aid:-1}}} -check_null_code=len($.List)==1&&$.List[0].Aid==-1
Masterpiece(c context.Context, mid int64) (*model.AidReasons, error)
// cache: -nullcache=&model.ThemeDetails{List:[]*model.ThemeDetail{{ID:-1}}} -check_null_code=len($.List)==1&&$.List[0].ID==-1
Theme(c context.Context, mid int64) (*model.ThemeDetails, error)
// cache: -nullcache=-1 -check_null_code=$==-1
TopDynamic(c context.Context, mid int64) (int64, error)
}
*/
package dao
import (
"context"
"go-common/app/interface/main/space/model"
"go-common/library/stat/prom"
)
var _ _cache
// Notice get data from cache if miss will call source method, then add to cache.
func (d *Dao) Notice(c context.Context, id int64) (res *model.Notice, err error) {
addCache := true
res, err = d.CacheNotice(c, id)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res.Notice == "ff2364a0be3d20e46cc69efb36afe9a5" {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("Notice")
return
}
prom.CacheMiss.Incr("Notice")
res, err = d.RawNotice(c, id)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.Notice{Notice: "ff2364a0be3d20e46cc69efb36afe9a5"}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheNotice(c, id, miss)
})
return
}
// TopArc get data from cache if miss will call source method, then add to cache.
func (d *Dao) TopArc(c context.Context, id int64) (res *model.AidReason, err error) {
addCache := true
res, err = d.CacheTopArc(c, id)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res != nil && res.Aid == -1 {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("TopArc")
return
}
prom.CacheMiss.Incr("TopArc")
res, err = d.RawTopArc(c, id)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.AidReason{Aid: -1}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheTopArc(c, id, miss)
})
return
}
// Masterpiece get data from cache if miss will call source method, then add to cache.
func (d *Dao) Masterpiece(c context.Context, id int64) (res *model.AidReasons, err error) {
addCache := true
res, err = d.CacheMasterpiece(c, id)
if err != nil {
addCache = false
err = nil
}
defer func() {
if len(res.List) == 1 && res.List[0].Aid == -1 {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("Masterpiece")
return
}
prom.CacheMiss.Incr("Masterpiece")
res, err = d.RawMasterpiece(c, id)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.AidReasons{List: []*model.AidReason{{Aid: -1}}}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheMasterpiece(c, id, miss)
})
return
}
// Theme get data from cache if miss will call source method, then add to cache.
func (d *Dao) Theme(c context.Context, id int64) (res *model.ThemeDetails, err error) {
addCache := true
res, err = d.CacheTheme(c, id)
if err != nil {
addCache = false
err = nil
}
defer func() {
if len(res.List) == 1 && res.List[0].ID == -1 {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("Theme")
return
}
prom.CacheMiss.Incr("Theme")
res, err = d.RawTheme(c, id)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.ThemeDetails{List: []*model.ThemeDetail{{ID: -1}}}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheTheme(c, id, miss)
})
return
}
// TopDynamic get data from cache if miss will call source method, then add to cache.
func (d *Dao) TopDynamic(c context.Context, id int64) (res int64, err error) {
addCache := true
res, err = d.CacheTopDynamic(c, id)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res == -1 {
res = 0
}
}()
if res != 0 {
prom.CacheHit.Incr("TopDynamic")
return
}
prom.CacheMiss.Incr("TopDynamic")
res, err = d.RawTopDynamic(c, id)
if err != nil {
return
}
miss := res
if miss == 0 {
miss = -1
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheTopDynamic(c, id, miss)
})
return
}

View File

@@ -0,0 +1,88 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoNotice(t *testing.T) {
convey.Convey("Notice", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Notice(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTopArc(t *testing.T) {
convey.Convey("TopArc", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2089809)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.TopArc(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoMasterpiece(t *testing.T) {
convey.Convey("Masterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Masterpiece(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTheme(t *testing.T) {
convey.Convey("Theme", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Theme(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTopDynamic(t *testing.T) {
convey.Convey("TopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.TopDynamic(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,172 @@
package dao
import (
"context"
"fmt"
"time"
"go-common/app/interface/main/space/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
"go-common/library/sync/pipeline/fanout"
"go-common/library/database/hbase.v2"
)
// Dao dao struct.
type Dao struct {
// config
c *conf.Config
// db
db *sql.DB
// hbase
hbase *hbase.Client
// stmt
channelStmt []*sql.Stmt
channelListStmt []*sql.Stmt
channelCntStmt []*sql.Stmt
channelArcCntStmt []*sql.Stmt
// redis
redis *redis.Pool
// mc
mc *memcache.Pool
// http client
httpR *bm.Client
httpW *bm.Client
httpGame *bm.Client
// api URL
bangumiURL string
bangumiConcernURL string
bangumiUnConcernURL string
favFolderURL string
favArcURL string
favAlbumURL string
favMovieURL string
shopURL string
shopLinkURL string
albumCountURL string
albumListURL string
tagSubURL string
tagCancelSubURL string
tagSubListURL string
accTagsURL string
accTagsSetURL string
isAnsweredURL string
lastPlayGameURL string
appPlayedGameURL string
arcSearchURL string
webTopPhotoURL string
topPhotoURL string
liveMetalURL string
liveURL string
medalStatusURL string
groupsCountURL string
elecURL string
audioCardURL string
audioUpperCertURL string
audioCntURL string
dynamicListURL string
dynamicURL string
dynamicCntURL string
// expire
clExpire int32
upArtExpire int32
upArcExpire int32
mcSettingExpire int32
mcNoticeExpire int32
mcTopArcExpire int32
mcMpExpire int32
mcThemeExpire int32
mcTopDyExpire int32
// cache
cache *fanout.Fanout
}
// New new dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// config
c: c,
db: sql.NewMySQL(c.Mysql),
hbase: hbase.NewClient(c.HBase.Config),
redis: redis.NewPool(c.Redis.Config),
mc: memcache.NewPool(c.Memcache.Config),
httpR: bm.NewClient(c.HTTPClient.Read),
httpW: bm.NewClient(c.HTTPClient.Write),
httpGame: bm.NewClient(c.HTTPClient.Game),
bangumiURL: c.Host.Bangumi + _bangumiURI,
bangumiConcernURL: c.Host.Bangumi + _bangumiConcernURI,
bangumiUnConcernURL: c.Host.Bangumi + _bangumiUnConcernURI,
favFolderURL: c.Host.API + _favFolderURI,
favArcURL: c.Host.API + _favArchiveURI,
favAlbumURL: c.Host.APILive + _favAlbumURI,
favMovieURL: c.Host.Bangumi + _favMovieURI,
shopURL: c.Host.Mall + _shopURI,
shopLinkURL: c.Host.Mall + _shopLinkURI,
albumCountURL: c.Host.APIVc + _albumCountURI,
albumListURL: c.Host.APIVc + _albumListURI,
tagSubURL: c.Host.API + _tagSubURI,
tagCancelSubURL: c.Host.API + _tagCancelSubURI,
tagSubListURL: c.Host.API + _subTagListURI,
accTagsURL: c.Host.Acc + _accTagsURI,
accTagsSetURL: c.Host.Acc + _accTagsSetURI,
isAnsweredURL: c.Host.API + _isAnsweredURI,
lastPlayGameURL: c.Host.Game + _lastPlayGameURI,
appPlayedGameURL: c.Host.AppGame + _appPlayedGameURI,
arcSearchURL: c.Host.Search + _arcSearchURI,
webTopPhotoURL: c.Host.Space + _webTopPhotoURI,
topPhotoURL: c.Host.Space + _topPhotoURI,
liveMetalURL: c.Host.APILive + _liveMetalURI,
liveURL: c.Host.APILive + _liveURI,
medalStatusURL: c.Host.APILive + _medalStatusURI,
groupsCountURL: c.Host.APIVc + _groupsCountURI,
elecURL: c.Host.Elec + _elecURI,
audioCardURL: c.Host.API + _audioCardURI,
audioUpperCertURL: c.Host.API + _audioUpperCertURI,
audioCntURL: c.Host.API + _audioCntURI,
dynamicListURL: c.Host.APIVc + _dynamicListURI,
dynamicURL: c.Host.APIVc + _dynamicURI,
dynamicCntURL: c.Host.APIVc + _dynamicCntURI,
// expire
clExpire: int32(time.Duration(c.Redis.ClExpire) / time.Second),
upArtExpire: int32(time.Duration(c.Redis.UpArtExpire) / time.Second),
upArcExpire: int32(time.Duration(c.Redis.UpArcExpire) / time.Second),
mcSettingExpire: int32(time.Duration(c.Memcache.SettingExpire) / time.Second),
mcNoticeExpire: int32(time.Duration(c.Memcache.NoticeExpire) / time.Second),
mcTopArcExpire: int32(time.Duration(c.Memcache.TopArcExpire) / time.Second),
mcMpExpire: int32(time.Duration(c.Memcache.MpExpire) / time.Second),
mcThemeExpire: int32(time.Duration(c.Memcache.ThemeExpire) / time.Second),
mcTopDyExpire: int32(time.Duration(c.Memcache.TopDyExpire) / time.Second),
// cache
cache: fanout.New("cache"),
}
d.channelStmt = make([]*sql.Stmt, _chSub)
d.channelListStmt = make([]*sql.Stmt, _chSub)
d.channelCntStmt = make([]*sql.Stmt, _chSub)
d.channelArcCntStmt = make([]*sql.Stmt, _chSub)
for i := 0; i < _chSub; i++ {
d.channelStmt[i] = d.db.Prepared(fmt.Sprintf(_chSQL, i))
d.channelListStmt[i] = d.db.Prepared(fmt.Sprintf(_chListSQL, i))
d.channelCntStmt[i] = d.db.Prepared(fmt.Sprintf(_chCntSQL, i))
d.channelArcCntStmt[i] = d.db.Prepared(fmt.Sprintf(_chArcCntSQL, i))
}
return
}
// Ping ping dao
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.db.Ping(c); err != nil {
return
}
err = d.pingRedis(c)
return
}
func (d *Dao) pingRedis(c context.Context) (err error) {
conn := d.redis.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}

View File

@@ -0,0 +1,46 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/interface/main/space/conf"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "dev" {
flag.Set("app_id", "main.web-svr.space-interface")
flag.Set("conf_token", "445a6be6947d52172ca5c4f3a55e3993")
flag.Set("tree_id", "5242")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/space-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.httpR.SetTransport(gock.DefaultTransport)
d.httpGame.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,45 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_elecURI = "/api/elec/info/query"
_elecMonthRank = "1"
)
// ElecInfo .
func (d *Dao) ElecInfo(c context.Context, mid, paymid int64) (data *model.ElecInfo, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("pay_mid", strconv.FormatInt(paymid, 10))
params.Set("type", _elecMonthRank)
var res struct {
Code int `json:"code"`
Data *model.ElecInfo `json:"data"`
}
if err = d.httpR.Get(c, d.elecURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
if res.Code == 500011 {
return
}
err = errors.Wrap(ecode.Int(res.Code), d.elecURL+"?"+params.Encode())
return
}
data = res.Data
return
}

View File

@@ -0,0 +1,18 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_ElecInfo(t *testing.T) {
convey.Convey("test elec info", t, func(ctx convey.C) {
mid := int64(28272030)
paymid := int64(0)
data, err := d.ElecInfo(context.Background(), mid, paymid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}

View File

@@ -0,0 +1,155 @@
package dao
import (
"context"
"net/http"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
favmdl "go-common/app/service/main/favorite/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_favFolderURI = "/x/internal/v2/fav/folder"
_favArchiveURI = "/x/internal/v2/fav/video"
_favAlbumURI = "/userext/v1/Fav/getMyFav"
_favMovieURI = "/follow/api/list/mine"
_samplePage = "1"
_samplePs = "1"
)
// FavFolder favorite folder list.
func (d *Dao) FavFolder(c context.Context, mid, vmid int64) (res []*favmdl.VideoFolder, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("vmid", strconv.FormatInt(vmid, 10))
var rs struct {
Code int `json:"code"`
Data []*favmdl.VideoFolder `json:"data"`
}
if err = d.httpR.Get(c, d.favFolderURL, ip, params, &rs); err != nil {
log.Error("d.http.Get(%s,%d) error(%v)", d.favFolderURL, mid, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.http.Get(%s,%d) code(%d)", d.favFolderURL, mid, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = rs.Data
return
}
// LiveFavCount get live(vc or album) favorite count.
func (d *Dao) LiveFavCount(c context.Context, mid int64, favType int) (count int, err error) {
var (
req *http.Request
rs struct {
Code int `json:"code"`
Data struct {
PageInfo struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPage int `json:"total_page"`
Count int `json:"count"`
} `json:"pageinfo"`
} `json:"data"`
}
ip = metadata.String(c, metadata.RemoteIP)
)
params := url.Values{}
params.Set("biz_type", strconv.Itoa(favType))
if req, err = d.httpR.NewRequest("GET", d.favAlbumURL, ip, params); err != nil {
log.Error("d.httpR.NewRequest %s error(%v)", d.favAlbumURL, err)
return
}
req.Header.Set("X-BILILIVE-UID", strconv.FormatInt(mid, 10))
if err = d.httpR.Do(c, req, &rs); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.favAlbumURL, mid, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) code(%d)", d.favAlbumURL, mid, rs.Code)
err = ecode.Int(rs.Code)
return
}
count = rs.Data.PageInfo.Count
return
}
// MovieFavCount get movie fav count
func (d *Dao) MovieFavCount(c context.Context, mid int64, favType int) (count int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("season_type", strconv.Itoa(favType))
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("page", _samplePage)
params.Set("pagesize", _samplePs)
params.Set("build", _build)
params.Set("platform", _platform)
var (
rs struct {
Code int `json:"code"`
Count string `json:"count"`
}
)
if err = d.httpR.Get(c, d.favMovieURL, ip, params, &rs); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.favMovieURL, mid, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) code(%d)", d.favMovieURL, mid, rs.Code)
err = ecode.Int(rs.Code)
return
}
count, _ = strconv.Atoi(rs.Count)
return
}
// FavArchive fav archive.
func (d *Dao) FavArchive(c context.Context, mid int64, arg *model.FavArcArg) (res *favmdl.SearchArchive, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
if mid > 0 {
params.Set("mid", strconv.FormatInt(mid, 10))
}
params.Set("vmid", strconv.FormatInt(arg.Vmid, 10))
params.Set("fid", strconv.FormatInt(arg.Fid, 10))
if arg.Tid > 0 {
params.Set("tid", strconv.FormatInt(arg.Tid, 10))
}
if arg.Keyword != "" {
params.Set("keyword", arg.Keyword)
}
if arg.Order != "" {
params.Set("order", arg.Order)
}
params.Set("pn", strconv.Itoa(arg.Pn))
params.Set("ps", strconv.Itoa(arg.Ps))
var rs struct {
Code int `json:"code"`
Data *favmdl.SearchArchive `json:"data"`
}
if err = d.httpR.Get(c, d.favArcURL, ip, params, &rs); err != nil {
log.Error("d.http.Get(%s,%d) error(%v)", d.favArcURL, mid, err)
return
}
if rs.Code != ecode.OK.Code() {
log.Error("d.http.Get(%s,%d) code(%d)", d.favArcURL, mid, rs.Code)
err = ecode.Int(rs.Code)
return
}
res = rs.Data
return
}

View File

@@ -0,0 +1,57 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDao_AlbumFavCount(t *testing.T) {
convey.Convey("test album fav count", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.favAlbumURL).Reply(200).JSON(`{"code": 0, "data":{"pageinfo":{"count":1}}}`)
mid := int64(88895029)
favType := 2
data, err := d.LiveFavCount(context.Background(), mid, favType)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_MovieFavCount(t *testing.T) {
convey.Convey("test movie fav count", t, func(ctx convey.C) {
mid := int64(88895029)
favType := 2
data, err := d.MovieFavCount(context.Background(), mid, favType)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_FavFolder(t *testing.T) {
convey.Convey("test fav folder", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.favFolderURL).Reply(200).JSON(`{"code": 0, "data":[]}`)
mid := int64(88895029)
vmid := int64(0)
data, err := d.FavFolder(context.Background(), mid, vmid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_FavArchive(t *testing.T) {
convey.Convey("test fav archive", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.favArcURL).Reply(200).JSON(`{"code": 0}`)
mid := int64(88895029)
arg := &model.FavArcArg{}
data, err := d.FavArchive(context.Background(), mid, arg)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}

View File

@@ -0,0 +1,82 @@
package dao
import (
"context"
"net/url"
"strconv"
"time"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_lastPlayGameURI = "/user/games.mid"
_appPlayedGameURI = "/game/recent/play"
_platformAndroid = "android"
_platformIOS = "ios"
_platTypeAndroid = 1
_platTypeIOS = 2
)
// LastPlayGame get last play game.
func (d *Dao) LastPlayGame(c context.Context, mid int64) (data []*model.Game, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data []*model.Game `json:"games"`
}
if err = d.httpR.Get(c, d.lastPlayGameURL, ip, params, &res); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.lastPlayGameURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) code error(%d)", d.lastPlayGameURL, mid, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Data
return
}
// AppPlayedGame get app player games.
func (d *Dao) AppPlayedGame(c context.Context, mid int64, platform string, pn, ps int) (data []*model.AppGame, count int, err error) {
var platformType int
switch platform {
case _platformAndroid:
platformType = _platTypeAndroid
case _platformIOS:
platformType = _platTypeIOS
}
params := url.Values{}
params.Set("uid", strconv.FormatInt(mid, 10))
params.Set("platform_type", strconv.Itoa(platformType))
params.Set("page_num", strconv.Itoa(pn))
params.Set("page_size", strconv.Itoa(ps))
params.Set("ts", strconv.FormatInt(time.Now().Unix()*1000, 10))
var res struct {
Code int `json:"code"`
Data struct {
List []*model.AppGame `json:"list"`
TotalCount int `json:"total_count"`
}
}
if err = d.httpGame.Get(c, d.appPlayedGameURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("AppPlayedGame d.httpR.Get(%s,%d) error(%v)", d.appPlayedGameURL+params.Encode(), mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("AppPlayedGame d.httpR.Get(%s,%d) code error(%d)", d.appPlayedGameURL+params.Encode(), mid, res.Code)
err = ecode.Int(res.Code)
return
}
data = res.Data.List
count = res.Data.TotalCount
return
}

View File

@@ -0,0 +1,83 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoLastPlayGame(t *testing.T) {
convey.Convey("LastPlayGame", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(908085)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.lastPlayGameURL).Reply(200).JSON(`{
"code": 0,
"games": [
{
"website": "https://www.bilibili.com/blackboard/activity-zlzyfk.html",
"image": "http://i0.hdslb.com/bfs/game/abfe03ca09e2051e5edc2693499f5db4d72e0e79.png",
"name": ""
}
]
}`)
data, err := d.LastPlayGame(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
ctx.Convey("When code not equal 0", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.lastPlayGameURL).Reply(200).JSON(`{"code": -3}`)
data, err := d.LastPlayGame(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.Printf("%+v", data)
})
})
})
}
func TestDaoAppPlayedGame(t *testing.T) {
convey.Convey("AppPlayedGame", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(89090481)
platform = _platformAndroid
pn = int(1)
ps = int(20)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.appPlayedGameURL).Reply(200).JSON(`
{
"code": 0,
"message": "ok",
"data": {
"list": [
{
"game_base_id": 97,
"game_name": "碧蓝航线",
"game_icon": "https://i0.hdslb.com/bfs/game/3f975ae90395bd323f585a788eb5e852e7af625e.jpg",
"grade": 8.8,
"detail_url": "bilibili://game_center/detail?id=97&sourceFrom=666"
}
],
"total_count": 1
}
}`)
data, count, err := d.AppPlayedGame(c, mid, platform, pn, ps)
ctx.Convey("Then err should be nil.data,count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,121 @@
package dao
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"strconv"
"time"
"go-common/app/interface/main/space/model"
"go-common/library/log"
"github.com/tsuna/gohbase/hrpc"
)
const (
_hBaseArticleTable = "read_auth_stats_daily"
_hBaseUpStatTablePrefix = "up_stats_"
)
func hbaseMd5Key(mid int64) string {
hasher := md5.New()
hasher.Write([]byte(strconv.Itoa(int(mid))))
return hex.EncodeToString(hasher.Sum(nil))
}
// UpArcStat get up archive stat.
func (d *Dao) UpArcStat(c context.Context, mid int64, date string) (stat *model.UpArcStat, err error) {
var (
result *hrpc.Result
ctx, cancel = context.WithTimeout(c, time.Duration(d.c.HBase.ReadTimeout))
key = hbaseMd5Key(mid)
tableName = _hBaseUpStatTablePrefix + date // change table at 12:00am
)
defer cancel()
if result, err = d.hbase.GetStr(ctx, tableName, key); err != nil {
log.Error("UpArcStat d.hbase.GetStr tableName(%s)|mid(%d)|key(%v)|error(%v)", tableName, mid, key, err)
return
}
if result == nil {
return
}
stat = &model.UpArcStat{}
for _, c := range result.Cells {
if c == nil {
continue
}
v, _ := strconv.ParseInt(string(c.Value[:]), 10, 64)
if !bytes.Equal(c.Family, []byte("u")) {
continue
}
switch {
case bytes.Equal(c.Qualifier, []byte("play")):
stat.View = v
case bytes.Equal(c.Qualifier, []byte("dm")):
stat.Dm = v
case bytes.Equal(c.Qualifier, []byte("reply")):
stat.Reply = v
case bytes.Equal(c.Qualifier, []byte("fans")):
stat.Fans = v
}
}
return
}
// UpArtStat get up article stat.
func (d *Dao) UpArtStat(c context.Context, mid int64) (stat *model.UpArtStat, err error) {
var (
result *hrpc.Result
ctx, cancel = context.WithTimeout(c, time.Duration(d.c.HBase.ReadTimeout))
key = hbaseMd5Key(mid)
tableName = _hBaseArticleTable
)
defer cancel()
if result, err = d.hbase.GetStr(ctx, tableName, key); err != nil {
log.Error("UpArtStat d.hbase.GetStr tableName(%s)|mid(%d)|key(%v)|error(%v)", tableName, mid, key, err)
return
}
if result == nil {
return
}
stat = &model.UpArtStat{}
for _, c := range result.Cells {
if c == nil {
continue
}
v, _ := strconv.ParseInt(string(c.Value[:]), 10, 64)
if !bytes.Equal(c.Family, []byte("r")) {
continue
}
switch {
case bytes.Equal(c.Qualifier, []byte("view1")):
stat.View = v
case bytes.Equal(c.Qualifier, []byte("reply1")):
stat.Reply = v
case bytes.Equal(c.Qualifier, []byte("coin1")):
stat.Coin = v
case bytes.Equal(c.Qualifier, []byte("like1")):
stat.Like = v
case bytes.Equal(c.Qualifier, []byte("fav1")):
stat.Fav = v
case bytes.Equal(c.Qualifier, []byte("view0")):
stat.PreView = v
case bytes.Equal(c.Qualifier, []byte("reply0")):
stat.PreReply = v
case bytes.Equal(c.Qualifier, []byte("coin0")):
stat.PreCoin = v
case bytes.Equal(c.Qualifier, []byte("like0")):
stat.PreLike = v
case bytes.Equal(c.Qualifier, []byte("fav0")):
stat.PreFav = v
}
}
stat.IncrView = stat.View - stat.PreView
stat.IncrReply = stat.Reply - stat.PreReply
stat.IncrCoin = stat.Coin - stat.PreCoin
stat.IncrLike = stat.Like - stat.PreLike
stat.IncrFav = stat.Fav - stat.PreFav
return
}

View File

@@ -0,0 +1,15 @@
package dao
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_hbaseMd5Key(t *testing.T) {
mid := int64(908085)
convey.Convey("test article stat", t, func() {
res := hbaseMd5Key(mid)
convey.Printf("%s", string(res))
})
}

View File

@@ -0,0 +1,94 @@
package dao
import (
"context"
"database/sql"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_indexOrderKeyFmt = "spc_io_%d"
_indexOrderSQL = `SELECT index_order FROM dede_member_up_settings%d WHERE mid = ?`
_indexOrderAddSQL = `INSERT INTO dede_member_up_settings%d (mid,index_order) VALUES (?,?) ON DUPLICATE KEY UPDATE index_order = ?`
)
func indexOrderHit(mid int64) int64 {
return mid % 10
}
func indexOrderKey(mid int64) string {
return fmt.Sprintf(_indexOrderKeyFmt, mid)
}
// IndexOrder get index order info.
func (d *Dao) IndexOrder(c context.Context, mid int64) (indexOrder string, err error) {
var row = d.db.QueryRow(c, fmt.Sprintf(_indexOrderSQL, indexOrderHit(mid)), mid)
if err = row.Scan(&indexOrder); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("IndexOrder row.Scan() error(%v)", err)
}
}
return
}
// IndexOrderModify index order modify.
func (d *Dao) IndexOrderModify(c context.Context, mid int64, orderStr string) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_indexOrderAddSQL, indexOrderHit(mid)), mid, orderStr, orderStr); err != nil {
log.Error("IndexOrderModify error d.db.Exec(%d,%s) error(%v)", mid, orderStr, err)
}
return
}
// IndexOrderCache get index order cache.
func (d *Dao) IndexOrderCache(c context.Context, mid int64) (data []*model.IndexOrder, err error) {
var (
conn = d.mc.Get(c)
key = indexOrderKey(mid)
)
defer conn.Close()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("IndexOrderCache conn.Get(%v) error(%v)", key, err)
return
}
if err = conn.Scan(reply, &data); err != nil {
log.Error("IndexOrderCache reply.Scan(%s) error(%v)", reply.Value, err)
}
return
}
// SetIndexOrderCache set index order cache.
func (d *Dao) SetIndexOrderCache(c context.Context, mid int64, data []*model.IndexOrder) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: indexOrderKey(mid), Object: data, Flags: memcache.FlagJSON, Expiration: d.mcSettingExpire}
if err = conn.Set(item); err != nil {
log.Error("SetIndexOrderCache conn.Set(%s) error(%v)", indexOrderKey(mid), err)
}
return
}
// DelIndexOrderCache delete index order cache.
func (d *Dao) DelIndexOrderCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := indexOrderKey(mid)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("DelIndexOrderCache conn.Delete(%s) error(%v)", indexOrderKey(mid), err)
}
return
}

View File

@@ -0,0 +1,116 @@
package dao
import (
"context"
"go-common/app/interface/main/space/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoindexOrderHit(t *testing.T) {
convey.Convey("indexOrderHit", t, func(ctx convey.C) {
var (
mid = int64(708)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := indexOrderHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoindexOrderKey(t *testing.T) {
convey.Convey("indexOrderKey", t, func(ctx convey.C) {
var (
mid = int64(708)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := indexOrderKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoIndexOrder(t *testing.T) {
convey.Convey("IndexOrder", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(708)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
indexOrder, err := d.IndexOrder(c, mid)
ctx.Convey("Then err should be nil.indexOrder should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(indexOrder, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoIndexOrderModify(t *testing.T) {
convey.Convey("IndexOrderModify", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(708)
orderStr = `["1","2","8","7","3","4","5","6","21","22","23","24","25"]`
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.IndexOrderModify(c, mid, orderStr)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetIndexOrderCache(t *testing.T) {
convey.Convey("SetIndexOrderCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(708)
data = []*model.IndexOrder{{ID: 1, Name: "我的稿件"}}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.SetIndexOrderCache(c, mid, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoIndexOrderCache(t *testing.T) {
convey.Convey("IndexOrderCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(708)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
data, err := d.IndexOrderCache(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelIndexOrderCache(t *testing.T) {
convey.Convey("DelIndexOrderCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(708)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelIndexOrderCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,75 @@
package dao
import (
"context"
"net/http"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_liveURI = "/room/v1/Room/getRoomInfoOld"
_medalStatusURI = "/fans_medal/v1/medal/get_medal_opened"
)
// Live is space live data.
func (d *Dao) Live(c context.Context, mid int64, platform string) (live *model.Live, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("platform", platform)
var res struct {
Code int `json:"code"`
Data *model.Live `json:"data"`
}
if err = d.httpR.Get(c, d.liveURL, ip, params, &res); err != nil {
return
}
if res.Code != ecode.OK.Code() {
err = errors.Wrap(ecode.Int(res.Code), d.liveURL+"?"+params.Encode())
return
}
live = res.Data
return
}
// LiveMetal get live metal
func (d *Dao) LiveMetal(c context.Context, mid int64) (rs bool, err error) {
var (
req *http.Request
ip = metadata.String(c, metadata.RemoteIP)
)
if req, err = d.httpR.NewRequest(http.MethodGet, d.liveMetalURL, ip, url.Values{}); err != nil {
log.Error("d.httpR.NewRequest(%s) error(%v)", d.liveMetalURL, err)
return
}
req.Header.Set("X-BILILIVE-UID", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
MasterStatus int `json:"master_status"`
} `json:"data"`
}
if err = d.httpR.Do(c, req, &res); err != nil {
log.Error("d.httpR.Do(%s) error(%v)", d.liveMetalURL, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Do(%s) code(%d) error", d.liveMetalURL, res.Code)
err = ecode.Int(res.Code)
return
}
if res.Data.MasterStatus == 1 {
rs = true
}
return
}

View File

@@ -0,0 +1,33 @@
package dao
import (
"context"
"go-common/library/ecode"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDao_Live(t *testing.T) {
convey.Convey("test live", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.liveURL).Reply(200).JSON(`{"code": 0}`)
mid := int64(28272030)
platform := "ios"
data, err := d.Live(context.Background(), mid, platform)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%v", data)
})
}
func TestDao_LiveMetal(t *testing.T) {
convey.Convey("test live metal", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.liveMetalURL).Reply(200).JSON(`{"code": 510002}`)
mid := int64(28272030)
data, err := d.LiveMetal(context.Background(), mid)
convey.So(err, convey.ShouldEqual, ecode.Int(510002))
convey.Printf("%v", data)
})
}

View File

@@ -0,0 +1,78 @@
package dao
import (
"context"
"fmt"
"go-common/app/interface/main/space/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_masterpieceFmt = "spc_mp_%d"
_masterpieceSQL = `SELECT aid,recommend_reason FROM member_masterpiece%d WHERE mid = ?`
_masterpieceAddSQL = `INSERT INTO member_masterpiece%d (mid,aid,recommend_reason) VALUES (?,?,?)`
_masterpieceEditSQL = `UPDATE member_masterpiece%d SET aid = ?,recommend_reason = ? WHERE mid = ? AND aid = ?`
_masterpieceDelSQL = `DELETE FROM member_masterpiece%d WHERE mid = ? AND aid = ?`
)
func masterpieceHit(mid int64) int64 {
return mid % 10
}
func masterpieceKey(mid int64) string {
return fmt.Sprintf(_masterpieceFmt, mid)
}
// RawMasterpiece get masterpiece from db.
func (d *Dao) RawMasterpiece(c context.Context, mid int64) (res *model.AidReasons, err error) {
var (
rows *xsql.Rows
list []*model.AidReason
)
res = new(model.AidReasons)
if rows, err = d.db.Query(c, fmt.Sprintf(_masterpieceSQL, masterpieceHit(mid)), mid); err != nil {
log.Error("RawMasterpiece d.db.Query(%d) error(%v)", mid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.AidReason)
if err = rows.Scan(&r.Aid, &r.Reason); err != nil {
log.Error("RawMasterpiece row.Scan() error(%v)", err)
return
}
list = append(list, r)
}
if err = rows.Err(); err != nil {
log.Error("RawMasterpiece rows.error(%v)", err)
return
}
res.List = list
return
}
// AddMasterpiece add masterpiece data.
func (d *Dao) AddMasterpiece(c context.Context, mid, aid int64, reason string) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_masterpieceAddSQL, masterpieceHit(mid)), mid, aid, reason); err != nil {
log.Error("AddMasterpiece error d.db.Exec(%d,%d,%s) error(%v)", mid, aid, reason, err)
}
return
}
// EditMasterpiece edit masterpiece data.
func (d *Dao) EditMasterpiece(c context.Context, mid, aid, preAid int64, reason string) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_masterpieceEditSQL, masterpieceHit(mid)), aid, reason, mid, preAid); err != nil {
log.Error("EditMasterpiece error d.db.Exec(%d,%d,%s) error(%v)", mid, aid, reason, err)
}
return
}
// DelMasterpiece delete masterpiece.
func (d *Dao) DelMasterpiece(c context.Context, mid, aid int64) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_masterpieceDelSQL, masterpieceHit(mid)), mid, aid); err != nil {
log.Error("DelMasterpiece error d.db.Exec(%d,%d) error(%v)", mid, aid, err)
}
return
}

View File

@@ -0,0 +1,103 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaomasterpieceHit(t *testing.T) {
convey.Convey("masterpieceHit", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := masterpieceHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaomasterpieceKey(t *testing.T) {
convey.Convey("masterpieceKey", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := masterpieceKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRawMasterpiece(t *testing.T) {
convey.Convey("RawMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawMasterpiece(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddMasterpiece(t *testing.T) {
convey.Convey("AddMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
aid = int64(2222)
reason = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddMasterpiece(c, mid, aid, reason)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoEditMasterpiece(t *testing.T) {
convey.Convey("EditMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
aid = int64(2222)
preAid = int64(3333)
reason = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.EditMasterpiece(c, mid, aid, preAid, reason)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelMasterpiece(t *testing.T) {
convey.Convey("DelMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
aid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelMasterpiece(c, mid, aid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,306 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package dao is a generated mc cache package.
It is generated from:
type _mc interface {
// get notice data from mc cache.
// mc: -key=noticeKey
CacheNotice(c context.Context, mid int64) (*model.Notice, error)
// set notice data to mc cache.
// mc: -key=noticeKey -expire=d.mcNoticeExpire -encode=pb
AddCacheNotice(c context.Context, mid int64, data *model.Notice) error
// mc: -key=noticeKey
DelCacheNotice(c context.Context, mid int64) error
// get top archive data from mc cache.
// mc: -key=topArcKey
CacheTopArc(c context.Context, mid int64) (*model.AidReason, error)
// set top archive data to mc cache.
// mc: -key=topArcKey -expire=d.mcTopArcExpire -encode=pb
AddCacheTopArc(c context.Context, mid int64, data *model.AidReason) error
// get top archive data from mc cache.
// mc: -key=masterpieceKey
CacheMasterpiece(c context.Context, mid int64) (*model.AidReasons, error)
// set top archive data to mc cache.
// mc: -key=masterpieceKey -expire=d.mcMpExpire -encode=pb
AddCacheMasterpiece(c context.Context, mid int64, data *model.AidReasons) error
// get theme data from mc cache.
// mc: -key=themeKey
CacheTheme(c context.Context, mid int64) (*model.ThemeDetails, error)
// set theme data to mc cache.
// mc: -key=themeKey -expire=d.mcThemeExpire -encode=pb
AddCacheTheme(c context.Context, mid int64, data *model.ThemeDetails) error
// mc: -key=themeKey
DelCacheTheme(c context.Context, mid int64) error
// get top dynamic id cache.
// mc: -key=topDyKey
CacheTopDynamic(c context.Context, key int64) (int64, error)
// set top dynamic id cache.
// mc: -key=topDyKey -expire=d.mcTopDyExpire -encode=raw
AddCacheTopDynamic(c context.Context, key int64, value int64) error
}
*/
package dao
import (
"context"
"fmt"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheNotice get notice data from mc cache.
func (d *Dao) CacheNotice(c context.Context, id int64) (res *model.Notice, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := noticeKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheNotice")
log.Errorv(c, log.KV("CacheNotice", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.Notice{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheNotice")
log.Errorv(c, log.KV("CacheNotice", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheNotice set notice data to mc cache.
func (d *Dao) AddCacheNotice(c context.Context, id int64, val *model.Notice) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := noticeKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcNoticeExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheNotice")
log.Errorv(c, log.KV("AddCacheNotice", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheNotice delete data from mc
func (d *Dao) DelCacheNotice(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := noticeKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheNotice")
log.Errorv(c, log.KV("DelCacheNotice", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheTopArc get top archive data from mc cache.
func (d *Dao) CacheTopArc(c context.Context, id int64) (res *model.AidReason, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := topArcKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheTopArc")
log.Errorv(c, log.KV("CacheTopArc", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.AidReason{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTopArc")
log.Errorv(c, log.KV("CacheTopArc", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheTopArc set top archive data to mc cache.
func (d *Dao) AddCacheTopArc(c context.Context, id int64, val *model.AidReason) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := topArcKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcTopArcExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheTopArc")
log.Errorv(c, log.KV("AddCacheTopArc", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheMasterpiece get top archive data from mc cache.
func (d *Dao) CacheMasterpiece(c context.Context, id int64) (res *model.AidReasons, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := masterpieceKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheMasterpiece")
log.Errorv(c, log.KV("CacheMasterpiece", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.AidReasons{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheMasterpiece")
log.Errorv(c, log.KV("CacheMasterpiece", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheMasterpiece set top archive data to mc cache.
func (d *Dao) AddCacheMasterpiece(c context.Context, id int64, val *model.AidReasons) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := masterpieceKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcMpExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheMasterpiece")
log.Errorv(c, log.KV("AddCacheMasterpiece", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheTheme get theme data from mc cache.
func (d *Dao) CacheTheme(c context.Context, id int64) (res *model.ThemeDetails, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := themeKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheTheme")
log.Errorv(c, log.KV("CacheTheme", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.ThemeDetails{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTheme")
log.Errorv(c, log.KV("CacheTheme", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheTheme set theme data to mc cache.
func (d *Dao) AddCacheTheme(c context.Context, id int64, val *model.ThemeDetails) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := themeKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.mcThemeExpire, Flags: memcache.FlagProtobuf}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheTheme")
log.Errorv(c, log.KV("AddCacheTheme", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheTheme delete data from mc
func (d *Dao) DelCacheTheme(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := themeKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheTheme")
log.Errorv(c, log.KV("DelCacheTheme", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CacheTopDynamic get top dynamic id cache.
func (d *Dao) CacheTopDynamic(c context.Context, id int64) (res int64, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := topDyKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheTopDynamic")
log.Errorv(c, log.KV("CacheTopDynamic", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
var v string
err = conn.Scan(reply, &v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTopDynamic")
log.Errorv(c, log.KV("CacheTopDynamic", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
r, err := strconv.ParseInt(v, 10, 64)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheTopDynamic")
log.Errorv(c, log.KV("CacheTopDynamic", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = int64(r)
return
}
// AddCacheTopDynamic set top dynamic id cache.
func (d *Dao) AddCacheTopDynamic(c context.Context, id int64, val int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := topDyKey(id)
bs := []byte(strconv.FormatInt(int64(val), 10))
item := &memcache.Item{Key: key, Value: bs, Expiration: d.mcTopDyExpire, Flags: memcache.FlagRAW}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheTopDynamic")
log.Errorv(c, log.KV("AddCacheTopDynamic", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,200 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddCacheNotice(t *testing.T) {
convey.Convey("AddCacheNotice", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
val = &model.Notice{Notice: "2222"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheNotice(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheNotice(t *testing.T) {
convey.Convey("CacheNotice", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheNotice(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCacheNotice(t *testing.T) {
convey.Convey("DelCacheNotice", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelCacheNotice(c, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddCacheTopArc(t *testing.T) {
convey.Convey("AddCacheTopArc", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
val = &model.AidReason{Aid: 2222, Reason: "2222"}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheTopArc(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheTopArc(t *testing.T) {
convey.Convey("CacheTopArc", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheTopArc(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddCacheMasterpiece(t *testing.T) {
convey.Convey("AddCacheMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
val = &model.AidReasons{List: []*model.AidReason{{Aid: 2222, Reason: "2222"}}}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheMasterpiece(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheMasterpiece(t *testing.T) {
convey.Convey("CacheMasterpiece", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheMasterpiece(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddCacheTheme(t *testing.T) {
convey.Convey("AddCacheTheme", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
val = &model.ThemeDetails{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheTheme(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheTheme(t *testing.T) {
convey.Convey("CacheTheme", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheTheme(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCacheTheme(t *testing.T) {
convey.Convey("DelCacheTheme", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelCacheTheme(c, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddCacheTopDynamic(t *testing.T) {
convey.Convey("AddCacheTopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
val = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddCacheTopDynamic(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheTopDynamic(t *testing.T) {
convey.Convey("CacheTopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.CacheTopDynamic(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,229 @@
package dao
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"go-common/app/interface/main/space/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_chSub = 10
_chSQL = "SELECT id,mid,name,intro,modify_time FROM member_channel%d WHERE mid = ? AND id = ? LIMIT 1"
_chListSQL = "SELECT id,mid,name,intro,modify_time FROM member_channel%d WHERE mid = ?"
_chCntSQL = "SELECT COUNT(1) FROM member_channel%d WHERE mid = ? LIMIT 1"
_chAddSQL = "INSERT INTO member_channel%d (mid,name,intro,modify_time) VALUES (?,?,?,?)"
_chEditSQL = "UPDATE member_channel%d SET name = ?,intro = ?,modify_time = ? WHERE mid = ? AND id = ?"
_chDelSQL = "DELETE FROM member_channel%d WHERE mid = ? AND id = ?"
_chArcSQL = "SELECT id,mid,cid,aid,order_num,modify_time FROM member_channel_video%d WHERE mid = ? AND cid = ? ORDER BY order_num"
_chArcCntSQL = "SELECT COUNT(1),IFNULL(aid , 0) FROM member_channel_video%d WHERE mid = ? AND cid = ? ORDER BY order_num DESC LIMIT 1"
_chArcAddSQL = "INSERT INTO member_channel_video%d (mid,cid,aid,order_num,modify_time) VALUES %s"
_chArcDelSQL = "DELETE FROM member_channel_video%d WHERE mid = ? AND cid = ? AND aid = ?"
_chArcsDelSQL = "DELETE FROM member_channel_video%d WHERE mid = ? AND cid = ?"
_chArcsSortDelSQL = "UPDATE member_channel_video%d SET order_num = order_num-1 WHERE mid = ? AND cid = ? AND order_num > ?"
_chArcEditSQL = "UPDATE member_channel_video%d SET order_num = CASE %s END,modify_time = ? WHERE mid = ? AND cid = ? AND aid IN (%s)"
)
func channelHit(mid int64) int64 {
return mid % _chSub
}
// Channel get channel simple info
func (d *Dao) Channel(c context.Context, mid, cid int64) (channel *model.Channel, err error) {
row := d.channelStmt[channelHit(mid)].QueryRow(c, mid, cid)
channel = new(model.Channel)
if err = row.Scan(&channel.Cid, &channel.Mid, &channel.Name, &channel.Intro, &channel.Mtime); err != nil {
if err == sql.ErrNoRows {
channel = nil
err = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// ChannelCnt get channel count by mid
func (d *Dao) ChannelCnt(c context.Context, mid int64) (count int, err error) {
row := d.channelCntStmt[channelHit(mid)].QueryRow(c, mid)
if err = row.Scan(&count); err != nil {
log.Error("row.Scan error(%v)", err)
}
return
}
// ChannelList get channel list by mid
func (d *Dao) ChannelList(c context.Context, mid int64) (res []*model.Channel, err error) {
var rows *xsql.Rows
if rows, err = d.channelListStmt[channelHit(mid)].Query(c, mid); err != nil {
log.Error("d.channelListStmt[%d].Query(%d) error(%v)", channelHit(mid), mid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Channel)
if err = rows.Scan(&r.Cid, &r.Mid, &r.Name, &r.Intro, &r.Mtime); err != nil {
log.Error("row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// ChannelVideos get channel video list
func (d *Dao) ChannelVideos(c context.Context, mid, cid int64, order bool) (res []*model.ChannelArc, err error) {
var (
orderSQL string
rows *xsql.Rows
)
orderSQL = fmt.Sprintf(_chArcSQL, channelHit(mid))
if !order {
orderSQL = orderSQL + " DESC"
}
if rows, err = d.db.Query(c, orderSQL, mid, cid); err != nil {
log.Error("d.channelVideoStmt[%d].Query(%d,%d) error(%v)", channelHit(mid), mid, cid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.ChannelArc)
if err = rows.Scan(&r.ID, &r.Mid, &r.Cid, &r.Aid, &r.OrderNum, &r.Mtime); err != nil {
log.Error("row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// ChannelExtra get channel count and cover aid
func (d *Dao) ChannelExtra(c context.Context, mid, cid int64) (res *model.ChannelExtra, err error) {
row := d.channelArcCntStmt[channelHit(mid)].QueryRow(c, mid, cid)
res = &model.ChannelExtra{Cid: cid}
if err = row.Scan(&res.Count, &res.Aid); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// AddChannel add channel
func (d *Dao) AddChannel(c context.Context, mid int64, name, intro string, ts time.Time) (lastID int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, fmt.Sprintf(_chAddSQL, channelHit(mid)), mid, name, intro, ts.Format("2006-01-02 15:04:05")); err != nil {
log.Error("AddChannel: db.Exec(mid:%d,name:%s,intro:%s) error(%v)", mid, name, intro, err)
return
}
return res.LastInsertId()
}
// EditChannel edit channel name or intro
func (d *Dao) EditChannel(c context.Context, mid, cid int64, name, intro string, ts time.Time) (affected int64, err error) {
var res sql.Result
if res, err = d.db.Exec(c, fmt.Sprintf(_chEditSQL, channelHit(mid)), name, intro, ts.Format("2006-01-02 15:04:05"), mid, cid); err != nil {
log.Error("EditChannel: db.Exec(mid:%d,cid:%d,name:%s,intro:%s) error(%v)", mid, cid, name, intro, err)
return
}
return res.RowsAffected()
}
// DelChannel delete channel
func (d *Dao) DelChannel(c context.Context, mid, cid int64) (affected int64, err error) {
var (
res sql.Result
tx *xsql.Tx
)
if tx, err = d.db.Begin(c); err != nil {
log.Error("d.db.Begin error(%v)", err)
return
}
if res, err = tx.Exec(fmt.Sprintf(_chDelSQL, channelHit(mid)), mid, cid); err != nil {
tx.Rollback()
log.Error("DelChannel: db.Exec(mid:%d,cid:%d) error(%v)", mid, cid, err)
return
}
if _, err = tx.Exec(fmt.Sprintf(_chArcsDelSQL, channelHit(mid)), mid, cid); err != nil {
tx.Rollback()
log.Error("DelChannelArcs: db.Exec(mid:%d,cid:%d) error(%v)", mid, cid, err)
return
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit error(%v)", err)
return
}
return res.RowsAffected()
}
// AddChannelArc add archives to channel
func (d *Dao) AddChannelArc(c context.Context, mid, cid int64, ts time.Time, chs []*model.ChannelArcSort) (lastID int64, err error) {
var (
res sql.Result
values []string
)
for _, v := range chs {
values = append(values, fmt.Sprintf("(%d,%d,%d,%d,'%s')", mid, cid, v.Aid, v.OrderNum, ts.Format("2006-01-02 15:04:05")))
}
if res, err = d.db.Exec(c, fmt.Sprintf(_chArcAddSQL, channelHit(mid), strings.Join(values, ","))); err != nil {
log.Error("AddChannelArc: db.Exec(%d,%d) error(%v)", mid, cid, err)
return
}
return res.LastInsertId()
}
// DelChannelArc delete channel archives
func (d *Dao) DelChannelArc(c context.Context, mid, cid, aid int64, orderNum int) (affected int64, err error) {
var (
res sql.Result
tx *xsql.Tx
)
if tx, err = d.db.Begin(c); err != nil {
log.Error("d.db.Begin error(%v)", err)
return
}
if res, err = d.db.Exec(c, fmt.Sprintf(_chArcDelSQL, channelHit(mid)), mid, cid, aid); err != nil {
tx.Rollback()
log.Error("DelChannelArc: db.Exec(mid:%d,cid:%d,aid:%d) error (%v)", mid, cid, aid, err)
return
}
if _, err = tx.Exec(fmt.Sprintf(_chArcsSortDelSQL, channelHit(mid)), mid, cid, orderNum); err != nil {
tx.Rollback()
log.Error("DelChannelArcs: db.Exec(mid:%d,cid:%d) error(%v)", mid, cid, err)
return
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit error(%v)", err)
return
}
return res.RowsAffected()
}
// EditChannelArc edit channel archive order num
func (d *Dao) EditChannelArc(c context.Context, mid, cid int64, ts time.Time, chSort []*model.ChannelArcSort) (affected int64, err error) {
var (
caseStr string
aids []int64
res sql.Result
)
for _, v := range chSort {
caseStr = fmt.Sprintf("%s WHEN aid = %d THEN %d", caseStr, v.Aid, v.OrderNum)
aids = append(aids, v.Aid)
}
if res, err = d.db.Exec(c, fmt.Sprintf(_chArcEditSQL, channelHit(mid), caseStr, xstr.JoinInts(aids)), ts.Format("2006-01-02 15:04:05"), mid, cid); err != nil {
log.Error("EditChannel: db.Exec(mid:%d,cid:%d,%s) error(%v)", mid, cid, caseStr, err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,73 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_Channel(t *testing.T) {
convey.Convey("test channel", t, func(ctx convey.C) {
mid := int64(27515260)
cid := int64(38)
res, err := d.Channel(context.Background(), mid, cid)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldHaveSameTypeAs, &model.Channel{})
})
}
func TestDao_ChannelCnt(t *testing.T) {
convey.Convey("test channel cnt", t, func(ctx convey.C) {
mid := int64(27515260)
res, err := d.ChannelCnt(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestDao_ChannelExtra(t *testing.T) {
convey.Convey("test channel extra", t, func(ctx convey.C) {
mid := int64(27515260)
cid := int64(38)
res, err := d.ChannelExtra(context.Background(), mid, cid)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldHaveSameTypeAs, &model.ChannelExtra{})
})
}
func TestDao_EditChannelArc(t *testing.T) {
convey.Convey("test edit channel arc", t, func(ctx convey.C) {
mid := int64(27515260)
cid := int64(37)
sort := []*model.ChannelArcSort{{Aid: 5462035, OrderNum: 4}, {Aid: 5461964, OrderNum: 3}}
res, err := d.EditChannelArc(context.Background(), mid, cid, time.Now(), sort)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", res)
})
}
func TestDao_ChannelList(t *testing.T) {
convey.Convey("test channel list", t, func(ctx convey.C) {
mid := int64(27515260)
res, err := d.ChannelList(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", res)
})
}
func TestDao_ChannelVideos(t *testing.T) {
convey.Convey("test channel video", t, func(ctx convey.C) {
mid := int64(27515260)
cid := int64(37)
res1, err1 := d.ChannelVideos(context.Background(), mid, cid, true)
convey.So(err1, convey.ShouldBeNil)
convey.Printf("%+v", res1)
res2, err2 := d.ChannelVideos(context.Background(), mid, cid, false)
convey.So(err2, convey.ShouldBeNil)
convey.Printf("%+v", res2)
})
}

View File

@@ -0,0 +1,46 @@
package dao
import (
"context"
"database/sql"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/log"
)
const (
_noticeKeyFmt = "spc_nt_%d"
_noticeSQL = `SELECT notice,is_forbid FROM member_up_notice%d WHERE mid = ?`
_noticeSetSQL = `INSERT INTO member_up_notice%d (mid,notice) VALUES (?,?) ON DUPLICATE KEY UPDATE notice = ?`
)
func noticeHit(mid int64) int64 {
return mid % 10
}
func noticeKey(mid int64) string {
return fmt.Sprintf(_noticeKeyFmt, mid)
}
// RawNotice get notice from db.
func (d *Dao) RawNotice(c context.Context, mid int64) (res *model.Notice, err error) {
row := d.db.QueryRow(c, fmt.Sprintf(_noticeSQL, noticeHit(mid)), mid)
res = new(model.Notice)
if err = row.Scan(&res.Notice, &res.IsForbid); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("Notice row.Scan() error(%v)", err)
}
}
return
}
// SetNotice change notice.
func (d *Dao) SetNotice(c context.Context, mid int64, notice string) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_noticeSetSQL, noticeHit(mid)), mid, notice, notice); err != nil {
log.Error("SetNotice error d.db.Exec(%d,%s) error(%v)", mid, notice, err)
}
return
}

View File

@@ -0,0 +1,68 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaonoticeHit(t *testing.T) {
convey.Convey("noticeHit", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := noticeHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaonoticeKey(t *testing.T) {
convey.Convey("noticeKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := noticeKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRawNotice(t *testing.T) {
convey.Convey("RawNotice", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.RawNotice(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetNotice(t *testing.T) {
convey.Convey("SetNotice", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
notice = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetNotice(c, mid, notice)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,115 @@
package dao
import (
"context"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/cache/memcache"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_privacyKey = "spc_pcy_%d"
_privacySQL = `SELECT privacy,status FROM member_privacy%d WHERE mid = ?`
_privacyModifySQL = `UPDATE member_privacy%d SET status=? WHERE mid = ? AND privacy = ?`
_privacyAddSQL = `INSERT INTO member_privacy%d (mid,privacy,status) VALUES (?,?,?)`
)
func privacyHit(mid int64) int64 {
return mid % 10
}
func privacyKey(mid int64) string {
return fmt.Sprintf(_privacyKey, mid)
}
// Privacy get privacy data.
func (d *Dao) Privacy(c context.Context, mid int64) (data map[string]int, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_privacySQL, privacyHit(mid)), mid); err != nil {
log.Error("d.Privacy.Query(%d) error(%v)", mid, err)
return
}
defer rows.Close()
data = make(map[string]int)
for rows.Next() {
r := new(model.Privacy)
if err = rows.Scan(&r.Privacy, &r.Status); err != nil {
log.Error("row.Scan() error(%v)", err)
return
}
data[r.Privacy] = r.Status
}
return
}
// PrivacyModify modify privacy.
func (d *Dao) PrivacyModify(c context.Context, mid int64, field string, value int) (err error) {
var privacy map[string]int
if privacy, err = d.Privacy(c, mid); err != nil {
return
}
if _, ok := privacy[field]; ok {
_, err = d.db.Exec(c, fmt.Sprintf(_privacyModifySQL, privacyHit(mid)), value, mid, field)
if err != nil {
log.Error("Privacy Update error d.db.Exec(%d,%s,%d) error(%v)", mid, field, value, err)
}
} else {
_, err = d.db.Exec(c, fmt.Sprintf(_privacyAddSQL, privacyHit(mid)), mid, field, value)
if err != nil {
log.Error("Privacy Add error d.db.Exec(%d,%s,%d) error(%v)", mid, field, value, err)
}
}
return
}
// PrivacyCache get privacy cache.
func (d *Dao) PrivacyCache(c context.Context, mid int64) (data map[string]int, err error) {
var (
conn = d.mc.Get(c)
key = privacyKey(mid)
)
defer conn.Close()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("conn.Get(%v) error(%v)", key, err)
return
}
if err = conn.Scan(reply, &data); err != nil {
log.Error("reply.Scan(%s) error(%v)", reply.Value, err)
}
return
}
// SetPrivacyCache set privacy cache.
func (d *Dao) SetPrivacyCache(c context.Context, mid int64, data map[string]int) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: privacyKey(mid), Object: data, Flags: memcache.FlagJSON, Expiration: d.mcSettingExpire}
if err = conn.Set(item); err != nil {
log.Error("conn.Store(%s) error(%v)", privacyKey(mid), err)
return
}
return
}
// DelPrivacyCache delete privacy cache.
func (d *Dao) DelPrivacyCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := privacyKey(mid)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("DelPrivacyCache conn.Delete(%s) error(%v)", privacyKey(mid), err)
}
return
}

View File

@@ -0,0 +1,118 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoprivacyHit(t *testing.T) {
convey.Convey("privacyHit", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := privacyHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoprivacyKey(t *testing.T) {
convey.Convey("privacyKey", t, func(ctx convey.C) {
var (
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := privacyKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPrivacy(t *testing.T) {
convey.Convey("Privacy", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.Privacy(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPrivacyModify(t *testing.T) {
convey.Convey("PrivacyModify", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
field = "bangumi"
value = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.PrivacyModify(c, mid, field, value)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetPrivacyCache(t *testing.T) {
convey.Convey("SetPrivacyCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
data = model.DefaultPrivacy
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetPrivacyCache(c, mid, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoPrivacyCache(t *testing.T) {
convey.Convey("PrivacyCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.PrivacyCache(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelPrivacyCache(t *testing.T) {
convey.Convey("DelPrivacyCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelPrivacyCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,119 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
func keyUpArt(mid int64) string {
return fmt.Sprintf("%s_%d", "uat", mid)
}
func keyUpArc(mid int64) string {
return fmt.Sprintf("%s_%d", "uar", mid)
}
// UpArtCache get up article cache.
func (d *Dao) UpArtCache(c context.Context, mid int64) (data *model.UpArtStat, err error) {
var (
value []byte
key = keyUpArt(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
data = new(model.UpArtStat)
if err = json.Unmarshal(value, &data); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetUpArtCache set up article cache.
func (d *Dao) SetUpArtCache(c context.Context, mid int64, data *model.UpArtStat) (err error) {
var (
bs []byte
key = keyUpArt(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(data); err != nil {
log.Error("json.Marshal(%v) error (%v)", data, err)
return
}
err = setKvCache(conn, key, bs, d.upArtExpire)
return
}
// UpArcCache get up archive cache.
func (d *Dao) UpArcCache(c context.Context, mid int64) (data *model.UpArcStat, err error) {
var (
value []byte
key = keyUpArc(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(GET, %s) error(%v)", key, err)
}
return
}
data = new(model.UpArcStat)
if err = json.Unmarshal(value, &data); err != nil {
log.Error("json.Unmarshal(%v) error(%v)", value, err)
}
return
}
// SetUpArcCache set up archive cache.
func (d *Dao) SetUpArcCache(c context.Context, mid int64, data *model.UpArcStat) (err error) {
var (
bs []byte
key = keyUpArc(mid)
conn = d.redis.Get(c)
)
defer conn.Close()
if bs, err = json.Marshal(data); err != nil {
log.Error("json.Marshal(%v) error (%v)", data, err)
return
}
err = setKvCache(conn, key, bs, d.upArcExpire)
return
}
func setKvCache(conn redis.Conn, key string, value []byte, expire int32) (err error) {
if err = conn.Send("SET", key, value); err != nil {
log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(value), err)
return
}
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}

View File

@@ -0,0 +1,120 @@
package dao
import (
"context"
"testing"
"go-common/app/interface/main/space/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyUpArt(t *testing.T) {
convey.Convey("keyUpArt", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyUpArt(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaokeyUpArc(t *testing.T) {
convey.Convey("keyUpArc", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyUpArc(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetUpArtCache(t *testing.T) {
convey.Convey("SetUpArtCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
data = &model.UpArtStat{View: 2222, Reply: 2222}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUpArtCache(c, mid, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpArtCache(t *testing.T) {
convey.Convey("UpArtCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.UpArtCache(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetUpArcCache(t *testing.T) {
convey.Convey("SetUpArcCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
data = &model.UpArcStat{View: 2222, Reply: 2222}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUpArcCache(c, mid, data)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpArcCache(t *testing.T) {
convey.Convey("UpArcCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2222)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
data, err := d.UpArcCache(c, mid)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaosetKvCache(t *testing.T) {
convey.Convey("setKvCache", t, func(ctx convey.C) {
var (
conn = d.redis.Get(context.Background())
key = ""
value = []byte("")
expire = int32(0)
)
defer conn.Close()
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := setKvCache(conn, key, value, expire)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,62 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_shopURI = "/mall-shop/merchant/enter/service/shop/info"
_shopLinkURI = "/mall-shop/merchant/enter/service/shop/get"
)
// ShopInfo get shop info data for pc.
func (d *Dao) ShopInfo(c context.Context, mid int64) (data *model.ShopInfo, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
Shop *model.ShopInfo `json:"shop"`
} `json:"data"`
}
if err = d.httpR.Get(c, d.shopURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("ShopInfo(%s) mid(%d) error(%v)", d.shopURL+params.Encode(), mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("ShopInfo(%s) mid(%d) code(%d) error", d.shopURL+params.Encode(), mid, res.Code)
err = ecode.SpaceNoShop
return
}
data = res.Data.Shop
return
}
// ShopLink only get simply data for h5.
func (d *Dao) ShopLink(c context.Context, mid int64, platform int) (data *model.ShopLinkInfo, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("type", strconv.Itoa(platform))
var res struct {
Code int `json:"code"`
Data *model.ShopLinkInfo `json:"data"`
}
if err = d.httpR.Get(c, d.shopLinkURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("ShopLink(%s) mid(%d) error(%v)", d.shopLinkURL+params.Encode(), mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("ShopLink(%s) mid(%d) code(%d) error", d.shopLinkURL+params.Encode(), mid, res.Code)
err = ecode.SpaceNoShop
return
}
data = res.Data
return
}

View File

@@ -0,0 +1,31 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDao_ShopInfo(t *testing.T) {
convey.Convey("test get shop info", t, func(ctx convey.C) {
mid := int64(27515399)
defer gock.OffAll()
httpMock("GET", d.shopURL).Reply(200).JSON(`{"code":0,"data":{"shop":{"id":111}}}`)
data, err := d.ShopInfo(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}
func TestDao_ShopLink(t *testing.T) {
convey.Convey("test shop link", t, func(ctx convey.C) {
mid := int64(27515399)
plat := 1
data, err := d.ShopLink(context.Background(), mid, plat)
convey.So(err, convey.ShouldBeNil)
convey.So(data, convey.ShouldNotBeNil)
convey.Printf("%+v", data)
})
}

View File

@@ -0,0 +1,90 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_tagSubURI = "/x/internal/tag/subscribe/add"
_tagCancelSubURI = "/x/internal/tag/subscribe/cancel"
_subTagListURI = "/x/internal/tag/subscribe/tags"
)
// TagSub subscribe tag.
func (d *Dao) TagSub(c context.Context, mid, tid int64) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("tag_id", strconv.FormatInt(tid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.tagSubURL, ip, params, &res); err != nil {
log.Error("tag: d.httpW.Post url(%s) mid(%d) tag_id(%d) error(%v)", d.tagSubURL, mid, tid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("tag: d.http.Do code error(%d)", res.Code)
err = ecode.Int(res.Code)
}
return
}
// TagCancelSub cancel subscribe tag.
func (d *Dao) TagCancelSub(c context.Context, mid, tid int64) (err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("tag_id", strconv.FormatInt(tid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.httpW.Post(c, d.tagCancelSubURL, ip, params, &res); err != nil {
log.Error("tag: d.httpW.Post url(%s) mid(%d) tag_id(%d) error(%v)", d.tagCancelSubURL, mid, tid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("tag: d.http.Do code error(%d)", res.Code)
err = ecode.Int(res.Code)
}
return
}
// TagSubList get tag subscribe list by mid.
func (d *Dao) TagSubList(c context.Context, mid int64, pn, ps int) (rs []*model.Tag, total int, err error) {
var (
params = url.Values{}
ip = metadata.String(c, metadata.RemoteIP)
)
params.Set("vmid", strconv.FormatInt(mid, 10))
params.Set("pn", strconv.Itoa(pn))
params.Set("ps", strconv.Itoa(ps))
var res struct {
Code int `json:"code"`
Total int `json:"total"`
Data []*model.Tag `json:"data"`
}
if err = d.httpR.Get(c, d.tagSubListURL, ip, params, &res); err != nil {
log.Error("d.http.Get(%s,%d) error(%v)", d.tagSubListURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.http.Get(%s,%d) error(%v)", d.tagSubListURL, mid, err)
err = ecode.Int(res.Code)
return
}
rs = res.Data
total = res.Total
return
}

View File

@@ -0,0 +1,37 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_TagSub(t *testing.T) {
convey.Convey("test tag sub", t, func(ctx convey.C) {
mid := int64(2089809)
tid := int64(600)
err := d.TagSub(context.Background(), mid, tid)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDao_TagCancelSub(t *testing.T) {
convey.Convey("test cancel tag cancel sub", t, func(ctx convey.C) {
mid := int64(2089809)
tid := int64(600)
err := d.TagCancelSub(context.Background(), mid, tid)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDao_TagSubList(t *testing.T) {
convey.Convey("test tag sub list", t, func(ctx convey.C) {
vmid := int64(88889018)
pn := 1
ps := 15
data, count, err := d.TagSubList(context.Background(), vmid, pn, ps)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v,%d", data, count)
})
}

View File

@@ -0,0 +1,123 @@
package dao
import (
"context"
"database/sql"
"fmt"
"time"
"go-common/app/interface/main/space/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_themeKeyFmt = `spc_them_%d`
_themeSQL = `SELECT sid,is_activated FROM dede_member_skin%d WHERE mid = ? AND expire > ?`
_themeInfoSQL = `SELECT id,name,img_path,toutu,bgimg FROM dede_skin_mall WHERE is_disable = 0 AND id IN (%s)`
_themeEditSQL = `UPDATE dede_member_skin%d SET is_activated = 1 WHERE mid = ? AND sid = ?`
_themeUnSQL = `UPDATE dede_member_skin%d SET is_activated = 0 WHERE mid = ?`
)
func themeHit(mid int64) int64 {
return mid % 10
}
func themeKey(mid int64) string {
return fmt.Sprintf(_themeKeyFmt, mid)
}
// ThemeInfoByMid get theme info by mid.
func (d *Dao) ThemeInfoByMid(c context.Context, mid int64) (res []*model.ThemeInfo, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_themeSQL, themeHit(mid)), mid, time.Now()); err != nil {
log.Error("ThemeInfoByMid d.db.Query(%d) error(%v)", mid, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.ThemeInfo)
if err = rows.Scan(&r.SID, &r.IsActivated); err != nil {
log.Error("ThemeInfoByMid row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
return
}
// ThemeDetail get theme details.
func (d *Dao) ThemeDetail(c context.Context, themeIDs []int64) (res []*model.ThemeDetail, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_themeInfoSQL, xstr.JoinInts(themeIDs))); err != nil {
log.Error("ThemeDetail d.db.Query(%v) error(%v)", themeIDs, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.ThemeDetail)
if err = rows.Scan(&r.ID, &r.Name, &r.Icon, &r.TopPhoto, &r.BgImg); err != nil {
log.Error("ThemeDetail row.Scan() error(%v)", err)
return
}
res = append(res, r)
}
return
}
// RawTheme get themes by mid.
func (d *Dao) RawTheme(c context.Context, mid int64) (res *model.ThemeDetails, err error) {
var (
themeInfo []*model.ThemeInfo
themeIDs []int64
list []*model.ThemeDetail
)
res = new(model.ThemeDetails)
if themeInfo, err = d.ThemeInfoByMid(c, mid); err != nil || len(themeInfo) == 0 {
return
}
themeInfoMap := make(map[int64]*model.ThemeInfo, len(themeInfo))
for _, v := range themeInfo {
themeIDs = append(themeIDs, v.SID)
themeInfoMap[v.SID] = v
}
if list, err = d.ThemeDetail(c, themeIDs); err != nil {
return
}
for _, v := range list {
if theme, ok := themeInfoMap[v.ID]; ok && theme != nil {
v.IsActivated = theme.IsActivated
}
}
res.List = list
return
}
// ThemeActive active theme.
func (d *Dao) ThemeActive(c context.Context, mid, themeID int64) (err error) {
var (
res sql.Result
tx *xsql.Tx
)
if tx, err = d.db.Begin(c); err != nil {
log.Error("ThemeActive: d.db.Begin error(%v)", err)
return
}
if res, err = tx.Exec(fmt.Sprintf(_themeUnSQL, themeHit(mid)), mid); err != nil {
tx.Rollback()
log.Error("ThemeActive: db.Exec(%d) error(%v)", mid, err)
return
}
if _, err = tx.Exec(fmt.Sprintf(_themeEditSQL, themeHit(mid)), mid, themeID); err != nil {
tx.Rollback()
log.Error("ThemeActive: db.Exec(%d,%d) error(%v)", mid, themeID, err)
return
}
if err = tx.Commit(); err != nil {
log.Error("ThemeActive: tx.Commit error(%v)", err)
return
}
_, err = res.RowsAffected()
return
}

View File

@@ -0,0 +1,39 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDao_ThemeInfoByMid(t *testing.T) {
convey.Convey("test theme info by mid", t, func(ctx convey.C) {
mid := int64(545840)
data, err := d.ThemeInfoByMid(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
for _, v := range data {
convey.Printf("%+v", v)
}
})
}
func TestDao_RawTheme(t *testing.T) {
convey.Convey("test theme", t, func(ctx convey.C) {
mid := int64(545840)
data, err := d.RawTheme(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
for _, v := range data.List {
convey.Printf("%+v", v)
}
})
}
func TestDao_ThemeActive(t *testing.T) {
convey.Convey("test theme active", t, func(ctx convey.C) {
mid := int64(27515256)
themeID := int64(11)
err := d.ThemeActive(context.Background(), mid, themeID)
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,56 @@
package dao
import (
"context"
"database/sql"
"fmt"
"go-common/app/interface/main/space/model"
"go-common/library/log"
)
const (
_topArcFmt = "spc_ta_%d"
_topArcSQL = `SELECT aid,recommend_reason FROM member_top%d WHERE mid = ? LIMIT 1`
_topArcAddSQL = `INSERT INTO member_top%d(mid,aid,recommend_reason) VALUES (?,?,?) ON DUPLICATE KEY UPDATE aid = ?,recommend_reason = ?`
_topArcDelSQL = `DELETE FROM member_top%d WHERE mid = ?`
)
func topArcHit(mid int64) int64 {
return mid % 10
}
func topArcKey(mid int64) string {
return fmt.Sprintf(_topArcFmt, mid)
}
// RawTopArc get top aid from db.
func (d *Dao) RawTopArc(c context.Context, mid int64) (res *model.AidReason, err error) {
var row = d.db.QueryRow(c, fmt.Sprintf(_topArcSQL, topArcHit(mid)), mid)
res = new(model.AidReason)
if err = row.Scan(&res.Aid, &res.Reason); err != nil {
if err == sql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("RawTopArc row.Scan() error(%v)", err)
}
}
return
}
// AddTopArc add top archive.
func (d *Dao) AddTopArc(c context.Context, mid, aid int64, reason string) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_topArcAddSQL, topArcHit(mid)), mid, aid, reason, aid, reason); err != nil {
log.Error("AddTopArc error d.db.Exec(%d,%d,%s) error(%v)", mid, aid, reason, err)
}
return
}
// DelTopArc delete top archive.
func (d *Dao) DelTopArc(c context.Context, mid int64) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_topArcDelSQL, topArcHit(mid)), mid); err != nil {
log.Error("DelTopArc error d.db.Exec(%d) error(%v)", mid, err)
}
return
}

View File

@@ -0,0 +1,84 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaotopArcHit(t *testing.T) {
convey.Convey("topArcHit", t, func(ctx convey.C) {
var (
mid = int64(5551)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := topArcHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaotopArcKey(t *testing.T) {
convey.Convey("topArcKey", t, func(ctx convey.C) {
var (
mid = int64(5551)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := topArcKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRawTopArc(t *testing.T) {
convey.Convey("RawTopArc", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(2089809)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.RawTopArc(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddTopArc(t *testing.T) {
convey.Convey("AddTopArc", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(5551)
aid = int64(170001)
reason = "aaaa"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddTopArc(c, mid, aid, reason)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelTopArc(t *testing.T) {
convey.Convey("DelTopArc", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(5551)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelTopArc(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
"database/sql"
"fmt"
"time"
"go-common/library/log"
)
const (
_topDyKeyFmt = "spc_td_%d"
_topDySQL = `SELECT dy_id FROM top_dynamic_%d WHERE deleted_time = 0 AND mid = ?`
_topDyAddSQL = `INSERT INTO top_dynamic_%d(mid,dy_id) VALUES (?,?) ON DUPLICATE KEY UPDATE dy_id = ?`
_topDyDelSQL = `UPDATE top_dynamic_%d set deleted_time = ? WHERE mid = ?`
)
func topDyHit(mid int64) int64 {
return mid % 10
}
func topDyKey(mid int64) string {
return fmt.Sprintf(_topDyKeyFmt, mid)
}
// RawTopDynamic get top dynamic data from mysql.
func (d *Dao) RawTopDynamic(c context.Context, mid int64) (dyID int64, err error) {
var row = d.db.QueryRow(c, fmt.Sprintf(_topDySQL, topDyHit(mid)), mid)
if err = row.Scan(&dyID); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("RawTopDynamic row.Scan() error(%v)", err)
}
}
return
}
// AddTopDynamic add top archive.
func (d *Dao) AddTopDynamic(c context.Context, mid, dyID int64) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_topDyAddSQL, topDyHit(mid)), mid, dyID, dyID); err != nil {
log.Error("AddTopDynamic error d.db.Exec(%d,%d) error(%v)", mid, dyID, err)
}
return
}
// DelTopDynamic delete top archive.
func (d *Dao) DelTopDynamic(c context.Context, mid int64, now time.Time) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_topDyDelSQL, topDyHit(mid)), now, mid); err != nil {
log.Error("DelTopDynamic error d.db.Exec(%d) error(%v)", mid, err)
}
return
}

View File

@@ -0,0 +1,85 @@
package dao
import (
"context"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaotopDyHit(t *testing.T) {
convey.Convey("topDyHit", t, func(ctx convey.C) {
var (
mid = int64(666)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := topDyHit(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaotopDyKey(t *testing.T) {
convey.Convey("topDyKey", t, func(ctx convey.C) {
var (
mid = int64(666)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := topDyKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRawTopDynamic(t *testing.T) {
convey.Convey("RawTopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(666)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
dyID, err := d.RawTopDynamic(c, mid)
ctx.Convey("Then err should be nil.dyID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(dyID, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddTopDynamic(t *testing.T) {
convey.Convey("AddTopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(666)
dyID = int64(1111111111)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddTopDynamic(c, mid, dyID)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelTopDynamic(t *testing.T) {
convey.Convey("DelTopDynamic", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(666)
now = time.Now()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelTopDynamic(c, mid, now)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,75 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_webTopPhotoURI = "/api/member/getTopPhoto"
_topPhotoURI = "/api/member/getUploadTopPhoto"
)
// WebTopPhoto getTopPhoto from space
func (d *Dao) WebTopPhoto(c context.Context, mid int64) (space *model.TopPhoto, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
model.TopPhoto
}
if err = d.httpR.Get(c, d.webTopPhotoURL, remoteIP, params, &res); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.webTopPhotoURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) code error(%d)", d.webTopPhotoURL, mid, res.Code)
err = ecode.Int(res.Code)
return
}
space = &res.TopPhoto
return
}
// TopPhoto getTopPhoto from space php.
func (d *Dao) TopPhoto(c context.Context, mid, vmid int64, platform, device string) (imgURL string, err error) {
var (
params = url.Values{}
remoteIP = metadata.String(c, metadata.RemoteIP)
)
if mid > 0 {
params.Set("mid", strconv.FormatInt(mid, 10))
}
params.Set("vmid", strconv.FormatInt(vmid, 10))
params.Set("platform", platform)
if device != "" {
params.Set("device", device)
}
var res struct {
Code int `json:"code"`
Data struct {
ImgURL string `json:"imgUrl"`
}
}
if err = d.httpR.Get(c, d.topPhotoURL, remoteIP, params, &res); err != nil {
log.Error("d.httpR.Get(%s,%d) error(%v)", d.topPhotoURL, mid, err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.httpR.Get(%s,%d) code error(%d)", d.topPhotoURL, mid, res.Code)
err = ecode.Int(res.Code)
return
}
imgURL = res.Data.ImgURL
return
}

View File

@@ -0,0 +1,34 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDao_WebTopPhoto(t *testing.T) {
convey.Convey("test get web top photo", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.webTopPhotoURL).Reply(200).JSON(`{"code": 0, "s_img":"test_url", "l_img":"test_url"}`)
mid := int64(282994)
data, err := d.WebTopPhoto(context.Background(), mid)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}
func TestDao_TopPhoto(t *testing.T) {
convey.Convey("test get top photo", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.topPhotoURL).Reply(200).JSON(`{"code": 0,"message": "ok","data": {"image_url":"test_url"}}`)
mid := int64(908085)
vmid := int64(908085)
platform := "ios"
device := "" // pad
data, err := d.TopPhoto(context.Background(), mid, vmid, platform, device)
convey.So(err, convey.ShouldBeNil)
convey.Printf("%+v", data)
})
}

View File

@@ -0,0 +1,65 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"album.go",
"app.go",
"archive.go",
"article.go",
"assist.go",
"bangumi.go",
"blacklist.go",
"channel.go",
"coin.go",
"dynamic.go",
"fav.go",
"http.go",
"setting.go",
"shop.go",
"tag.go",
"web.go",
],
importpath = "go-common/app/interface/main/space/http",
tags = ["automanaged"],
deps = [
"//app/interface/main/space/conf:go_default_library",
"//app/interface/main/space/model:go_default_library",
"//app/interface/main/space/service:go_default_library",
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/assist/model/assist:go_default_library",
"//library/conf/env:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/supervisor:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/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"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)

View File

@@ -0,0 +1,178 @@
package http
import (
"strconv"
"strings"
"go-common/app/interface/main/space/conf"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func navNum(c *bm.Context) {
var (
vmid, mid int64
err error
)
midStr := c.Request.Form.Get("mid")
if vmid, err = strconv.ParseInt(midStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.NavNum(c, mid, vmid), nil)
}
func upStat(c *bm.Context) {
var (
mid int64
err error
)
midStr := c.Request.Form.Get("mid")
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil || mid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(spcSvc.UpStat(c, mid))
}
func myInfo(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(spcSvc.MyInfo(c, mid))
}
func notice(c *bm.Context) {
v := new(struct {
Mid int64 `form:"mid" validate:"gt=0"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(spcSvc.Notice(c, v.Mid))
}
func setNotice(c *bm.Context) {
v := new(struct {
Notice string `form:"notice" validate:"required"`
})
if err := c.Bind(v); err != nil {
return
}
notice := strings.Trim(v.Notice, " ")
if len([]rune(notice)) > conf.Conf.Rule.MaxNoticeLen {
c.JSON(nil, ecode.RequestErr)
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.SetNotice(c, mid, notice))
}
func accTags(c *bm.Context) {
v := new(struct {
Mid int64 `form:"mid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(spcSvc.AccTags(c, v.Mid))
}
func setAccTags(c *bm.Context) {
v := new(struct {
Tags string `form:"tags" validate:"required"`
})
if err := c.Bind(v); err != nil {
return
}
tags := strings.Split(v.Tags, ",")
var addTags []string
for _, v := range tags {
if tag := strings.TrimSpace(v); tag != "" {
addTags = append(addTags, tag)
}
}
if len(addTags) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.SetAccTags(c, strings.Join(addTags, ","), c.Request.Header.Get("Cookie")))
}
func accInfo(c *bm.Context) {
var (
mid, vmid int64
err error
)
vmidStr := c.Request.Form.Get("mid")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.AccInfo(c, mid, vmid))
}
func lastPlayGame(c *bm.Context) {
var (
mid, vmid int64
err error
)
vmidStr := c.Request.Form.Get("mid")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.LastPlayGame(c, mid, vmid))
}
func themeList(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(spcSvc.ThemeList(c, mid))
}
func themeActive(c *bm.Context) {
var (
themeID int64
err error
)
midStr, _ := c.Get("mid")
mid := midStr.(int64)
themeIDStr := c.Request.Form.Get("theme_id")
if themeID, err = strconv.ParseInt(themeIDStr, 10, 64); err != nil || themeID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.ThemeActive(c, mid, themeID))
}
func relation(c *bm.Context) {
v := new(struct {
Vmid int64 `form:"mid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(spcSvc.Relation(c, mid, v.Vmid), nil)
}
func clearCache(c *bm.Context) {
v := new(struct {
Msg string `form:"msg" validate:"required"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, spcSvc.ClearCache(c, v.Msg))
}

View File

@@ -0,0 +1,16 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func albumIndex(c *bm.Context) {
v := new(struct {
Mid int64 `form:"mid" validate:"min=1"`
Ps int `form:"ps" default:"8" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(spcSvc.AlbumIndex(c, v.Mid, v.Ps))
}

View File

@@ -0,0 +1,71 @@
package http
import (
"go-common/app/interface/main/space/model"
bm "go-common/library/net/http/blademaster"
)
func appIndex(c *bm.Context) {
v := new(model.AppIndexArg)
if err := c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
v.Mid = midInter.(int64)
}
c.JSON(spcSvc.AppIndex(c, v))
}
func appPlayedGame(c *bm.Context) {
var (
mid int64
list []*model.AppGame
count int
err error
)
v := new(struct {
VMid int64 `form:"mid" validate:"min=1"`
Platform string `form:"platform" default:"android" validate:"required"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"20" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
list, count, err = spcSvc.AppPlayedGame(c, mid, v.VMid, v.Platform, v.Pn, v.Ps)
if err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"pn": v.Pn,
"ps": v.Ps,
"count": count,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func appTopPhoto(c *bm.Context) {
var mid int64
v := new(struct {
Vmid int64 `form:"mid" validate:"min=1"`
Platform string `form:"platform" default:"android"`
Device string `form:"device"`
})
if err := c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
imgURL := spcSvc.AppTopPhoto(c, mid, v.Vmid, v.Platform, v.Device)
c.JSON(&struct {
ImgURL string `json:"img_url"`
}{ImgURL: imgURL}, nil)
}

View File

@@ -0,0 +1,183 @@
package http
import (
"strconv"
"go-common/app/interface/main/space/conf"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"strings"
)
func topArc(c *bm.Context) {
var (
mid, vmid int64
err error
)
vmidStr := c.Request.Form.Get("vmid")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.TopArc(c, mid, vmid))
}
func setTopArc(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
Reason string `form:"reason"`
})
if err := c.Bind(v); err != nil {
return
}
reason := strings.TrimSpace(v.Reason)
if len([]rune(reason)) > conf.Conf.Rule.MaxTopReasonLen {
c.JSON(nil, ecode.TopReasonLong)
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.SetTopArc(c, mid, v.Aid, reason))
}
func cancelTopArc(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.DelTopArc(c, mid))
}
func masterpiece(c *bm.Context) {
var (
mid, vmid int64
err error
)
vmidStr := c.Request.Form.Get("vmid")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.Masterpiece(c, mid, vmid))
}
func addMasterpiece(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
Reason string `form:"reason"`
})
if err := c.Bind(v); err != nil {
return
}
reason := strings.TrimSpace(v.Reason)
if len([]rune(reason)) > conf.Conf.Rule.MaxMpReasonLen {
c.JSON(nil, ecode.TopReasonLong)
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.AddMasterpiece(c, mid, v.Aid, reason))
}
func editMasterpiece(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
PreAid int64 `form:"pre_aid" validate:"min=1"`
Reason string `form:"reason"`
})
if err := c.Bind(v); err != nil {
return
}
reason := strings.TrimSpace(v.Reason)
if len([]rune(reason)) > conf.Conf.Rule.MaxMpReasonLen {
c.JSON(nil, ecode.TopReasonLong)
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.EditMasterpiece(c, mid, v.Aid, v.PreAid, reason))
}
func cancelMasterpiece(c *bm.Context) {
v := new(struct {
Aid int64 `form:"aid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.CancelMasterpiece(c, mid, v.Aid))
}
func arcSearch(c *bm.Context) {
var (
res *model.SearchRes
total int
mid int64
err error
v = new(model.SearchArg)
)
if err = c.Bind(v); err != nil {
return
}
if v.CheckType != "" {
if _, ok := model.ArcCheckType[v.CheckType]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
if v.CheckID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if res, total, err = spcSvc.ArcSearch(c, mid, v); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"pn": v.Pn,
"ps": v.Ps,
"count": total,
}
data["page"] = page
data["list"] = res
c.JSON(data, nil)
}
func arcList(c *bm.Context) {
var (
rs *model.UpArc
err error
)
v := new(struct {
Mid int64 `form:"mid" validate:"min=1"`
Pn int32 `form:"pn" default:"1" validate:"min=1"`
Ps int32 `form:"ps" default:"20" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if rs, err = spcSvc.UpArcs(c, v.Mid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"pn": int64(v.Pn),
"ps": int64(v.Ps),
"count": rs.Count,
}
data["page"] = page
data["archives"] = rs.List
c.JSON(data, nil)
}

View File

@@ -0,0 +1,44 @@
package http
import (
"strconv"
"go-common/app/interface/main/space/conf"
"go-common/app/interface/main/space/model"
artmdl "go-common/app/interface/openplatform/article/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func article(c *bm.Context) {
var (
mid int64
pn, ps, sort int
ok bool
err error
)
params := c.Request.Form
midStr := params.Get("mid")
pnStr := params.Get("pn")
psStr := params.Get("ps")
sortStr := params.Get("sort")
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil || mid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Rule.MaxArticlePs {
ps = conf.Conf.Rule.MaxArticlePs
}
if sortStr != "" {
if sort, ok = model.ArticleSortType[sortStr]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
} else {
sort = artmdl.FieldDefault
}
c.JSON(spcSvc.Article(c, mid, pn, ps, sort))
}

View File

@@ -0,0 +1,61 @@
package http
import (
"strconv"
"go-common/app/interface/main/space/conf"
"go-common/app/service/main/assist/model/assist"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func riderList(c *bm.Context) {
var (
mid int64
pn, ps int
rider *assist.AssistUpsPager
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
pnStr := params.Get("pn")
psStr := params.Get("ps")
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Rule.MaxRiderPs {
ps = conf.Conf.Rule.MaxRiderPs
}
if rider, err = spcSvc.RiderList(c, mid, pn, ps); err != nil {
log.Error("spcSvc.RiderList(%d,%d,%d) error(%v)", mid, pn, ps, err)
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"pn": pn,
"ps": ps,
"count": int(rider.Pager.Total),
}
data["page"] = page
data["list"] = rider.Data
c.JSON(data, nil)
}
func exitRider(c *bm.Context) {
var (
mid, upMid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
upMidStr := params.Get("up_mid")
if upMid, err = strconv.ParseInt(upMidStr, 10, 64); err != nil || upMid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.ExitRider(c, mid, upMid))
}

View File

@@ -0,0 +1,59 @@
package http
import (
"go-common/app/interface/main/space/model"
bm "go-common/library/net/http/blademaster"
)
func bangumiList(c *bm.Context) {
var (
mid int64
list []*model.Bangumi
count int
err error
)
v := new(struct {
Vmid int64 `form:"vmid" validate:"min=1"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"15" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if list, count, err = spcSvc.BangumiList(c, mid, v.Vmid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
type data struct {
List []*model.Bangumi `json:"list"`
*model.Page
}
c.JSON(&data{List: list, Page: &model.Page{Pn: v.Pn, Ps: v.Ps, Total: count}}, nil)
}
func bangumiConcern(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
v := new(struct {
SeasonID int64 `form:"season_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, spcSvc.BangumiConcern(c, mid, v.SeasonID))
}
func bangumiUnConcern(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
v := new(struct {
SeasonID int64 `form:"season_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, spcSvc.BangumiUnConcern(c, mid, v.SeasonID))
}

View File

@@ -0,0 +1,22 @@
package http
import (
"go-common/library/conf/env"
bm "go-common/library/net/http/blademaster"
)
var (
_EmptyBlacklistValue = make(map[int64]struct{})
)
func blacklist(c *bm.Context) {
black := spcSvc.BlacklistValue
if env.DeployEnv == env.DeployEnvProd {
if len(black) == 0 {
black = _EmptyBlacklistValue
}
} else {
black = _EmptyBlacklistValue
}
c.JSON(black, nil)
}

View File

@@ -0,0 +1,343 @@
package http
import (
"strconv"
"go-common/app/interface/main/space/conf"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func channel(c *bm.Context) {
var (
vmid, mid, cid int64
isGuest bool
err error
)
params := c.Request.Form
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
vmidStr := params.Get("mid")
cidStr := params.Get("cid")
guestStr := params.Get("guest")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || (vmid <= 0 && mid <= 0) {
c.JSON(nil, ecode.RequestErr)
return
}
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if guestStr != "" {
if isGuest, err = strconv.ParseBool(guestStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if !isGuest && vmid > 0 && mid != vmid {
mid = vmid
}
c.JSON(spcSvc.Channel(c, mid, cid))
}
func channelIndex(c *bm.Context) {
var (
vmid, mid int64
isGuest bool
err error
)
params := c.Request.Form
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
vmidStr := params.Get("mid")
guestStr := params.Get("guest")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || (vmid <= 0 && mid <= 0) {
c.JSON(nil, ecode.RequestErr)
return
}
if guestStr != "" {
if isGuest, err = strconv.ParseBool(guestStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if !isGuest && vmid > 0 && mid != vmid {
isGuest = true
mid = vmid
}
c.JSON(spcSvc.ChannelIndex(c, mid, isGuest))
}
func channelList(c *bm.Context) {
var (
vmid, mid int64
channels []*model.Channel
isGuest bool
err error
)
params := c.Request.Form
vmidStr := params.Get("mid")
guestStr := params.Get("guest")
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || (vmid <= 0 && mid <= 0) {
c.JSON(nil, ecode.RequestErr)
return
}
if guestStr != "" {
if isGuest, err = strconv.ParseBool(guestStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if !isGuest && vmid > 0 && mid != vmid {
isGuest = true
mid = vmid
}
if channels, err = spcSvc.ChannelList(c, mid, isGuest); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
data["count"] = len(channels)
data["list"] = channels
c.JSON(data, nil)
}
func addChannel(c *bm.Context) {
var (
mid, cid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
name := params.Get("name")
intro := params.Get("intro")
if name == "" || len([]rune(name)) > conf.Conf.Rule.MaxChNameLen {
c.JSON(nil, ecode.ChNameToLong)
return
}
if intro != "" && len([]rune(intro)) > conf.Conf.Rule.MaxChIntroLen {
c.JSON(nil, ecode.ChIntroToLong)
return
}
if cid, err = spcSvc.AddChannel(c, mid, name, intro); err != nil {
c.JSON(nil, err)
return
}
c.JSON(struct {
Cid int64 `json:"cid"`
}{Cid: cid}, nil)
}
func editChannel(c *bm.Context) {
var (
mid, cid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := params.Get("cid")
name := params.Get("name")
intro := params.Get("intro")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if name == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if len([]rune(name)) > conf.Conf.Rule.MaxChNameLen {
c.JSON(nil, ecode.ChNameToLong)
return
}
if intro != "" && len([]rune(intro)) > conf.Conf.Rule.MaxChIntroLen {
c.JSON(nil, ecode.ChIntroToLong)
return
}
c.JSON(nil, spcSvc.EditChannel(c, mid, cid, name, intro))
}
func delChannel(c *bm.Context) {
var (
mid, cid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := params.Get("cid")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.DelChannel(c, mid, cid))
}
func channelVideo(c *bm.Context) {
var (
vmid, mid, cid int64
pn, ps int
isGuest, order bool
channelDetail *model.ChannelDetail
err error
)
params := c.Request.Form
vmidStr := params.Get("mid")
cidStr := params.Get("cid")
pnStr := params.Get("pn")
psStr := params.Get("ps")
guestStr := params.Get("guest")
orderStr := params.Get("order")
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || (vmid <= 0 && mid <= 0) {
c.JSON(nil, ecode.RequestErr)
return
}
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if pn, err = strconv.Atoi(pnStr); err != nil || pn < 1 {
pn = 1
}
if ps, err = strconv.Atoi(psStr); err != nil || ps < 1 || ps > conf.Conf.Rule.MaxChArcsPs {
ps = conf.Conf.Rule.MaxChArcsPs
}
if guestStr != "" {
if isGuest, err = strconv.ParseBool(guestStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if !isGuest && vmid > 0 && mid != vmid {
isGuest = true
mid = vmid
}
if orderStr != "" {
if order, err = strconv.ParseBool(orderStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
}
if channelDetail, err = spcSvc.ChannelVideos(c, mid, cid, pn, ps, isGuest, order); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"num": pn,
"size": ps,
"count": channelDetail.Count,
}
data["page"] = page
data["list"] = channelDetail
c.JSON(data, nil)
}
func addChannelVideo(c *bm.Context) {
var (
mid, cid int64
aids []int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := params.Get("cid")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
aidStr := params.Get("aids")
if aidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if aids, err = xstr.SplitInts(aidStr); err != nil || len(aids) == 0 || len(aids) > conf.Conf.Rule.MaxChArcAddLimit {
c.JSON(nil, ecode.RequestErr)
return
}
aidMap := make(map[int64]int64, len(aids))
for _, aid := range aids {
aidMap[aid] = aid
}
if len(aidMap) < len(aids) {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(spcSvc.AddChannelArc(c, mid, cid, aids))
}
func delChannelVideo(c *bm.Context) {
var (
mid, cid, aid int64
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := params.Get("cid")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
aidStr := params.Get("aid")
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.DelChannelArc(c, mid, cid, aid))
}
func sortChannelVideo(c *bm.Context) {
var (
mid, cid, aid int64
orderNum int
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := params.Get("cid")
aidStr := params.Get("aid")
toStr := params.Get("to")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if orderNum, err = strconv.Atoi(toStr); err != nil || orderNum < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.SortChannelArc(c, mid, cid, aid, orderNum))
}
func checkChannelVideo(c *bm.Context) {
var (
mid, cid int64
err error
)
midStr, _ := c.Get("mid")
mid = midStr.(int64)
cidStr := c.Request.Form.Get("cid")
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil || cid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.CheckChannelVideo(c, mid, cid))
}

View File

@@ -0,0 +1,24 @@
package http
import (
"strconv"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func coinVideo(c *bm.Context) {
var (
mid, vmid int64
err error
)
vmidStr := c.Request.Form.Get("vmid")
if vmid, err = strconv.ParseInt(vmidStr, 10, 64); err != nil || vmid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.CoinVideo(c, mid, vmid))
}

View File

@@ -0,0 +1,42 @@
package http
import (
"time"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func setTopDynamic(c *bm.Context) {
v := new(struct {
DyID int64 `form:"dy_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.SetTopDynamic(c, mid, v.DyID))
}
func cancelTopDynamic(c *bm.Context) {
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.CancelTopDynamic(c, mid, time.Now()))
}
func dynamicList(c *bm.Context) {
v := new(model.DyListArg)
if err := c.Bind(v); err != nil {
return
}
if v.Pn > 1 && v.LastTime == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if midInter, ok := c.Get("mid"); ok {
v.Mid = midInter.(int64)
}
c.JSON(spcSvc.DynamicList(c, v))
}

View File

@@ -0,0 +1,32 @@
package http
import (
"go-common/app/interface/main/space/model"
bm "go-common/library/net/http/blademaster"
)
func favNav(c *bm.Context) {
var mid int64
v := new(struct {
VMid int64 `form:"mid" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.FavNav(c, mid, v.VMid))
}
func favArc(c *bm.Context) {
var mid int64
v := new(model.FavArcArg)
if err := c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.FavArchive(c, mid, v))
}

View File

@@ -0,0 +1,164 @@
package http
import (
"net/http"
"go-common/app/interface/main/space/conf"
"go-common/app/interface/main/space/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/supervisor"
"go-common/library/net/http/blademaster/middleware/verify"
)
var (
authSvr *auth.Auth
spcSvc *service.Service
spvSvc *supervisor.Supervisor
vfySvc *verify.Verify
)
// Init init http server
func Init(c *conf.Config, s *service.Service) {
authSvr = auth.New(c.Auth)
spvSvc = supervisor.New(c.Supervisor)
vfySvc = verify.New(c.Verify)
spcSvc = s
// init http server
engine := bm.DefaultServer(c.HTTPServer)
outerRouter(engine)
internalRouter(engine)
// init Outer serve
if err := engine.Start(); err != nil {
log.Error("engine.Start error(%v)", err)
panic(err)
}
}
func outerRouter(e *bm.Engine) {
e.GET("/monitor/ping", ping)
group := e.Group("/x/space", bm.CORS())
{
chGroup := group.Group("/channel")
{
chGroup.GET("", authSvr.Guest, channel)
chGroup.GET("/index", authSvr.Guest, channelIndex)
chGroup.GET("/list", authSvr.Guest, channelList)
chGroup.POST("/add", spvSvc.ServeHTTP, authSvr.User, addChannel)
chGroup.POST("/del", authSvr.User, delChannel)
chGroup.POST("/edit", spvSvc.ServeHTTP, authSvr.User, editChannel)
}
chvGroup := group.Group("/channel/video")
{
chvGroup.GET("", authSvr.Guest, channelVideo)
chvGroup.POST("/add", authSvr.User, addChannelVideo)
chvGroup.POST("/del", authSvr.User, delChannelVideo)
chvGroup.POST("/sort", authSvr.User, sortChannelVideo)
chvGroup.GET("/check", authSvr.User, checkChannelVideo)
}
riderGroup := group.Group("/rider")
{
riderGroup.GET("/list", authSvr.User, riderList)
riderGroup.POST("/exit", authSvr.User, exitRider)
}
tagGroup := group.Group("/tag")
{
tagGroup.POST("/sub", authSvr.User, tagSub)
tagGroup.POST("/sub/cancel", authSvr.User, tagCancelSub)
tagGroup.GET("/sub/list", authSvr.Guest, tagSubList)
}
bgmGroup := group.Group("/bangumi")
{
bgmGroup.POST("/concern", authSvr.User, bangumiConcern)
bgmGroup.POST("/unconcern", authSvr.User, bangumiUnConcern)
bgmGroup.GET("/concern/list", authSvr.Guest, bangumiList)
}
topGroup := group.Group("/top")
{
topGroup.GET("/arc", authSvr.Guest, topArc)
topGroup.POST("/arc/set", authSvr.User, setTopArc)
topGroup.POST("/arc/cancel", authSvr.User, cancelTopArc)
topGroup.POST("/dynamic/set", authSvr.User, setTopDynamic)
topGroup.POST("/dynamic/cancel", authSvr.User, cancelTopDynamic)
}
mpGroup := group.Group("/masterpiece")
{
mpGroup.GET("", authSvr.Guest, masterpiece)
mpGroup.POST("/add", authSvr.User, addMasterpiece)
mpGroup.POST("/edit", authSvr.User, editMasterpiece)
mpGroup.POST("/cancel", authSvr.User, cancelMasterpiece)
}
noticeGroup := group.Group("/notice")
{
noticeGroup.GET("", notice)
noticeGroup.POST("/set", authSvr.User, setNotice)
}
accGroup := group.Group("/acc")
{
accGroup.GET("/info", authSvr.Guest, accInfo)
accGroup.GET("/tags", accTags)
accGroup.POST("/tags/set", authSvr.User, setAccTags)
accGroup.GET("/relation", authSvr.User, relation)
}
themeGroup := group.Group("theme")
{
themeGroup.GET("/list", authSvr.User, themeList)
themeGroup.POST("/active", authSvr.User, themeActive)
}
appGroup := group.Group("/app")
{
appGroup.GET("/index", authSvr.Guest, appIndex)
appGroup.GET("/dynamic/list", authSvr.Guest, dynamicList)
appGroup.GET("/played/game", authSvr.Guest, appPlayedGame)
appGroup.GET("/top/photo", authSvr.Guest, appTopPhoto)
}
arcGroup := group.Group("/arc")
{
arcGroup.GET("/search", arcSearch)
arcGroup.GET("/list", arcList)
}
group.GET("/setting", settingInfo)
group.GET("/article", article)
group.GET("/navnum", authSvr.Guest, navNum)
group.GET("/upstat", upStat)
group.GET("/shop", authSvr.User, shopInfo)
group.GET("/album/index", albumIndex)
group.GET("/fav/nav", authSvr.Guest, favNav)
group.GET("/fav/arc", authSvr.Guest, favArc)
group.GET("/coin/video", authSvr.Guest, coinVideo)
group.GET("/myinfo", authSvr.User, myInfo)
group.GET("/lastplaygame", authSvr.Guest, lastPlayGame)
group.POST("/privacy/modify", authSvr.User, privacyModify)
group.POST("/index/order/modify", authSvr.User, indexOrderModify)
}
}
func internalRouter(e *bm.Engine) {
group := e.Group("/x/internal/space")
{
group.GET("/setting", vfySvc.Verify, settingInfo)
group.GET("/myinfo", vfySvc.Verify, authSvr.User, myInfo)
group.POST("/privacy/modify", authSvr.User, privacyModify)
group.POST("/privacy/batch/modify", authSvr.User, privacyBatchModify)
group.POST("/index/order/modify", authSvr.User, indexOrderModify)
accGroup := group.Group("/acc")
{
accGroup.GET("/info", vfySvc.Verify, authSvr.Guest, accInfo)
}
appGroup := group.Group("/app")
{
appGroup.GET("/index", vfySvc.Verify, authSvr.Guest, appIndex)
}
group.GET("/web/index", vfySvc.Verify, authSvr.Guest, webIndex)
group.POST("/cache/clear", clearCache)
group.GET("/blacklist", vfySvc.Verify, blacklist)
}
}
func ping(c *bm.Context) {
if err := spcSvc.Ping(c); err != nil {
log.Error("space-interface ping error(%v)", err)
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,104 @@
package http
import (
"strconv"
"strings"
"go-common/app/interface/main/space/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func settingInfo(c *bm.Context) {
var (
mid int64
err error
)
midStr := c.Request.Form.Get("mid")
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil || mid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(spcSvc.SettingInfo(c, mid))
}
func privacyModify(c *bm.Context) {
var (
mid int64
field string
value int
fieldCheck bool
err error
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
if field = params.Get("field"); field == "" {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range model.PrivacyFields {
if v == field {
fieldCheck = true
break
}
}
if !fieldCheck {
c.JSON(nil, ecode.RequestErr)
return
}
valueStr := params.Get("value")
if value, err = strconv.Atoi(valueStr); err != nil || (value != 0 && value != 1) {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.PrivacyModify(c, mid, field, value))
}
func privacyBatchModify(c *bm.Context) {
params := c.Request.Form
midStr, _ := c.Get("mid")
mid := midStr.(int64)
batch := make(map[string]int)
for _, v := range model.PrivacyFields {
if valueStr := params.Get(v); valueStr != "" {
if value, err := strconv.Atoi(params.Get(v)); err == nil && (value == 0 || value == 1) {
batch[v] = value
}
}
}
c.JSON(nil, spcSvc.PrivacyBatchModify(c, mid, batch))
}
func indexOrderModify(c *bm.Context) {
var (
mid int64
indexOrderStr string
indexOrder []string
)
params := c.Request.Form
midStr, _ := c.Get("mid")
mid = midStr.(int64)
if indexOrderStr = params.Get("index_order"); indexOrderStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
indexOrders := strings.Split(indexOrderStr, ",")
for _, v := range indexOrders {
i, err := strconv.Atoi(v)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if _, ok := model.IndexOrderMap[i]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
indexOrder = append(indexOrder, v)
}
if len(indexOrder) != len(model.DefaultIndexOrder) {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, spcSvc.IndexOrderModify(c, mid, indexOrder))
}

View File

@@ -0,0 +1,14 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func shopInfo(c *bm.Context) {
var (
mid int64
)
midStr, _ := c.Get("mid")
mid = midStr.(int64)
c.JSON(spcSvc.ShopInfo(c, mid))
}

View File

@@ -0,0 +1,59 @@
package http
import (
"go-common/app/interface/main/space/model"
bm "go-common/library/net/http/blademaster"
)
func tagSub(c *bm.Context) {
v := new(struct {
TagID int64 `form:"tag_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.TagSub(c, mid, v.TagID))
}
func tagCancelSub(c *bm.Context) {
v := new(struct {
TagID int64 `form:"tag_id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
midStr, _ := c.Get("mid")
mid := midStr.(int64)
c.JSON(nil, spcSvc.TagCancelSub(c, mid, v.TagID))
}
func tagSubList(c *bm.Context) {
var (
mid int64
tags []*model.Tag
total int
err error
)
v := new(struct {
Vmid int64 `form:"vmid" validate:"min=1"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"100" validate:"min=1"`
})
if err = c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
if tags, total, err = spcSvc.TagSubList(c, mid, v.Vmid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
type data struct {
Tags []*model.Tag `json:"tags"`
*model.Page
}
c.JSON(&data{Tags: tags, Page: &model.Page{Pn: v.Pn, Ps: v.Ps, Total: total}}, nil)
}

View File

@@ -0,0 +1,19 @@
package http
import bm "go-common/library/net/http/blademaster"
func webIndex(c *bm.Context) {
var mid int64
v := new(struct {
VMid int64 `form:"mid" validate:"min=1"`
Pn int32 `form:"pn" default:"1" validate:"min=1"`
Ps int32 `form:"ps" default:"20" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
if midInter, ok := c.Get("mid"); ok {
mid = midInter.(int64)
}
c.JSON(spcSvc.WebIndex(c, mid, v.VMid, v.Pn, v.Ps))
}

View File

@@ -0,0 +1,84 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"album.go",
"app.go",
"archive.go",
"article.go",
"audio.go",
"bangumi.go",
"channel.go",
"coin.go",
"dynamic.go",
"elec.go",
"fav.go",
"game.go",
"live.go",
"setting.go",
"shop.go",
"tag.go",
"theme.go",
"web.go",
],
embed = [":model_go_proto"],
importpath = "go-common/app/interface/main/space/model",
tags = ["automanaged"],
deps = [
"//app/interface/openplatform/article/model:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/account/model:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//app/service/main/favorite/model:go_default_library",
"//library/time:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_golang_protobuf//proto: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"],
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
proto_library(
name = "model_proto",
srcs = ["proto.proto"],
tags = ["automanaged"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "model_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_proto"],
importpath = "go-common/app/interface/main/space/model",
proto = ":model_proto",
tags = ["automanaged"],
deps = ["@com_github_gogo_protobuf//gogoproto:go_default_library"],
)

View File

@@ -0,0 +1,112 @@
package model
import (
accmdl "go-common/app/service/main/account/api"
)
// NavNum nav num struct.
type NavNum struct {
Video int64 `json:"video"`
Bangumi int `json:"bangumi"`
Channel *Num `json:"channel"`
Favourite *Num `json:"favourite"`
Tag int `json:"tag"`
Article int `json:"article"`
Playlist int `json:"playlist"`
Album int64 `json:"album"`
Audio int `json:"audio"`
}
// Num num struct.
type Num struct {
Master int `json:"master"`
Guest int `json:"guest"`
}
// UpStat up stat struct.
type UpStat struct {
Archive struct {
View int64 `json:"view"`
} `json:"archive"`
Article struct {
View int64 `json:"view"`
} `json:"article"`
}
// AccInfo account info.
type AccInfo struct {
Mid int64 `json:"mid"`
Name string `json:"name"`
Sex string `json:"sex"`
Face string `json:"face"`
Sign string `json:"sign"`
Rank int32 `json:"rank"`
Level int32 `json:"level"`
JoinTime int32 `json:"jointime"`
Moral int32 `json:"moral"`
Silence int32 `json:"silence"`
Birthday string `json:"birthday"`
Coins float64 `json:"coins"`
FansBadge bool `json:"fans_badge"`
Official accmdl.OfficialInfo `json:"official"`
Vip struct {
Type int32 `json:"type"`
Status int32 `json:"status"`
} `json:"vip"`
IsFollowed bool `json:"is_followed"`
TopPhoto string `json:"top_photo"`
Theme interface{} `json:"theme"`
}
// AccBlock acc block
type AccBlock struct {
Status int `json:"status"`
IsDue int `json:"is_due"`
IsAnswered int `json:"is_answered"`
}
// TopPhoto top photo struct.
type TopPhoto struct {
SImg string `json:"s_img"`
LImg string `json:"l_img"`
}
// Relation .
type Relation struct {
Relation interface{} `json:"relation"`
BeRelation interface{} `json:"be_relation"`
}
// FromCard from account card.
func (ai *AccInfo) FromCard(c *accmdl.ProfileStatReply) {
ai.Mid = c.Profile.Mid
ai.Name = c.Profile.Name
ai.Rank = c.Profile.Rank
ai.Face = c.Profile.Face
ai.Sex = c.Profile.Sex
ai.JoinTime = c.Profile.JoinTime
ai.Silence = c.Profile.Silence
ai.Birthday = c.Profile.Birthday.Time().Format("01-02")
ai.Sign = c.Profile.Sign
ai.Level = c.Profile.Level
ai.Official = c.Profile.Official
ai.Vip.Type = c.Profile.Vip.Type
ai.Vip.Status = c.Profile.Vip.Status
ai.Coins = c.Coins
}
var (
// DefaultProfileStat .
DefaultProfileStat = &accmdl.ProfileStatReply{
Profile: DefaultProfile,
LevelInfo: accmdl.LevelInfo{},
}
// DefaultProfile .
DefaultProfile = &accmdl.Profile{
Name: "bilibili",
Sex: "保密",
Face: "https://static.hdslb.com/images/member/noface.gif",
Sign: "哔哩哔哩 (゜-゜)つロ 干杯~-bilibili",
Rank: 5000,
}
)

View File

@@ -0,0 +1,32 @@
package model
import "go-common/library/time"
// AlbumCount album count struct.
type AlbumCount struct {
AllCount int64 `json:"all_count"`
DrawCount int64 `json:"draw_count"`
PhotoCount int64 `json:"photo_count"`
DailyCount int64 `json:"daily_count"`
}
// Album album struct.
type Album struct {
DocID int64 `json:"doc_id"`
PosterUID int64 `json:"poster_uid"`
Title string `json:"title"`
Description string `json:"description"`
Pictures []*PicItem `json:"pictures"`
Count int64 `json:"count"`
Ctime time.Time `json:"ctime"`
View int64 `json:"view"`
Like int64 `json:"like"`
}
// PicItem picture item struct.
type PicItem struct {
ImgSrc string `json:"img_src"`
ImgWidth int `json:"img_width"`
ImgHeight int `json:"img_height"`
ImgSize int `json:"img_size"`
}

View File

@@ -0,0 +1,100 @@
package model
import (
accwar "go-common/app/service/main/account/api"
"go-common/app/service/main/account/model"
)
// AppAccInfo app acc info struct.
type AppAccInfo struct {
Mid int64 `json:"mid"`
Name string `json:"name"`
Sex string `json:"sex"`
Face string `json:"face"`
Sign string `json:"sign"`
Rank int32 `json:"rank"`
Level int32 `json:"level"`
LevelInfo accwar.LevelInfo `json:"level_info"`
Pendant model.PendantInfo `json:"pendant"`
Silence int32 `json:"silence"`
Vip struct {
Type int32 `json:"vipType"`
VipStatus int32 `json:"vipStatus"`
} `json:"vip"`
OfficialInfo struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"official_info"`
Following int64 `json:"following"`
Follower int64 `json:"follower"`
Relation interface{} `json:"relation"`
BeRelation interface{} `json:"be_relation"`
FansGroup int `json:"fans_group"`
Audio int `json:"audio"`
Shop interface{} `json:"shop"`
Elec interface{} `json:"elec"`
Live interface{} `json:"live"`
FansBadge bool `json:"fans_badge"`
TopPhoto string `json:"top_photo"`
Block *AccBlock `json:"block,omitempty"`
}
// FromProfile from account profile.
func (ai *AppAccInfo) FromProfile(p *accwar.ProfileStatReply) {
ai.Mid = p.Profile.Mid
ai.Name = p.Profile.Name
ai.Sex = p.Profile.Sex
ai.Face = p.Profile.Face
ai.Sign = p.Profile.Sign
ai.Rank = p.Profile.Rank
ai.Face = p.Profile.Face
ai.Level = p.Profile.Level
ai.Silence = p.Profile.Silence
ai.Vip.Type = p.Profile.Vip.Type
ai.Vip.VipStatus = p.Profile.Vip.Status
ai.Pendant = p.Profile.Pendant
if p.Profile.Official.Role == 0 {
ai.OfficialInfo.Type = -1
} else {
if p.Profile.Official.Role <= 2 {
ai.OfficialInfo.Type = 0
ai.OfficialInfo.Desc = p.Profile.Official.Title
} else {
ai.OfficialInfo.Type = 1
ai.OfficialInfo.Desc = p.Profile.Official.Title
}
}
ai.Following = p.Following
ai.Follower = p.Follower
}
// AppTab tab if show.
type AppTab struct {
Dynamic bool `json:"dynamic"`
Shop bool `json:"shop"`
Archive bool `json:"video"`
Article bool `json:"article"`
Audio bool `json:"audio"`
Album bool `json:"album"`
Favorite bool `json:"favorite"`
Bangumi bool `json:"bangumi"`
Game bool `json:"game"`
}
// AppIndex app index data.
type AppIndex struct {
Info *AppAccInfo `json:"info"`
Tab *AppTab `json:"tab"`
Dynamic *DyTotal `json:"dynamic"`
Archive *UpArc `json:"archive"`
}
// AppIndexArg .
type AppIndexArg struct {
Mid int64
Vmid int64 `form:"mid" validate:"min=1"`
Qn int `form:"qn" default:"16" validate:"min=1"`
Platform string `form:"platform" default:"android"`
Ps int32 `form:"ps" default:"16" validate:"min=1"`
Device string `form:"device"`
}

View File

@@ -0,0 +1,107 @@
package model
import (
v1 "go-common/app/service/main/archive/api"
"go-common/library/time"
)
// UpArcStat up archives stat struct.
type UpArcStat struct {
View int64 `json:"view"`
Reply int64 `json:"reply"`
Dm int64 `json:"dm"`
Fans int64 `json:"fans"`
}
// ArchiveReason archive with reason struct.
type ArchiveReason struct {
*v1.Arc
Reason string `json:"reason"`
}
// SearchRes search res data.
type SearchRes struct {
TList map[string]*SearchTList `json:"tlist"`
VList []*SearchVList `json:"vlist"`
}
// SearchTList search cate list.
type SearchTList struct {
Tid int64 `json:"tid"`
Count int64 `json:"count"`
Name string `json:"name"`
}
// SearchVList video list.
type SearchVList struct {
Comment int64 `json:"comment"`
TypeID int64 `json:"typeid"`
Play interface{} `json:"play"`
Pic string `json:"pic"`
SubTitle string `json:"subtitle"`
Description string `json:"description"`
Copyright string `json:"copyright"`
Title string `json:"title"`
Review int64 `json:"review"`
Author string `json:"author"`
Mid int64 `json:"mid"`
Created string `json:"created"`
Length string `json:"length"`
VideoReview int64 `json:"video_review"`
Aid int64 `json:"aid"`
HideClick bool `json:"hide_click"`
IsPay int `json:"is_pay"`
IsUnionVideo int `json:"is_union_video"`
}
// UpArc up archive struct
type UpArc struct {
Count int64 `json:"count"`
List []*ArcItem `json:"list"`
}
// ArcItem space archive item.
type ArcItem struct {
Aid int64 `json:"aid"`
Pic string `json:"pic"`
Title string `json:"title"`
Duration int64 `json:"duration"`
Author struct {
Mid int64 `json:"mid"`
Name string `json:"name"`
Face string `json:"face"`
} `json:"author"`
Stat struct {
View interface{} `json:"view"`
Danmaku int32 `json:"danmaku"`
Reply int32 `json:"reply"`
Fav int32 `json:"favorite"`
Coin int32 `json:"coin"`
Share int32 `json:"share"`
Like int32 `json:"like"`
} `json:"stat"`
Rights v1.Rights `json:"rights"`
Pubdate time.Time `json:"pubdate"`
}
// FromArc from archive to space act item.
func (ac *ArcItem) FromArc(arc *v1.Arc) {
ac.Aid = arc.Aid
ac.Pic = arc.Pic
ac.Title = arc.Title
ac.Duration = arc.Duration
ac.Author.Mid = arc.Author.Mid
ac.Author.Name = arc.Author.Name
ac.Author.Face = arc.Author.Face
ac.Stat.View = arc.Stat.View
if arc.Access >= 10000 {
ac.Stat.View = "--"
}
ac.Stat.Danmaku = arc.Stat.Danmaku
ac.Stat.Reply = arc.Stat.Reply
ac.Stat.Fav = arc.Stat.Fav
ac.Stat.Share = arc.Stat.Share
ac.Stat.Like = arc.Stat.Like
ac.Pubdate = arc.PubDate
ac.Rights = arc.Rights
}

View File

@@ -0,0 +1,20 @@
package model
// UpArtStat struct.
type UpArtStat struct {
View int64 `json:"view"`
Reply int64 `json:"reply"`
Like int64 `json:"like"`
Coin int64 `json:"coin"`
Fav int64 `json:"fav"`
PreView int64 `json:"-"`
PreReply int64 `json:"-"`
PreLike int64 `json:"-"`
PreCoin int64 `json:"-"`
PreFav int64 `json:"-"`
IncrView int64 `json:"incr_view"`
IncrReply int64 `json:"incr_reply"`
IncrLike int64 `json:"incr_like"`
IncrCoin int64 `json:"incr_coin"`
IncrFav int64 `json:"incr_fav"`
}

View File

@@ -0,0 +1,29 @@
package model
// AudioCard .
type AudioCard struct {
Type int `json:"type"`
Status int `json:"status"`
}
// AudioUpperCert .
type AudioUpperCert struct {
Cert *struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"cert"`
}
// Audio .
type Audio struct {
MenuID int64 `json:"menu_id"`
Title string `json:"title"`
CoverURL string `json:"cover_url"`
PlayNum int `json:"play_num"`
RecordNum int `json:"record_num"`
Ctgs []*struct {
ItemID int64 `json:"item_id"`
ItemVal string `json:"item_val"`
} `json:"ctgs"`
Type int `json:"type"`
}

View File

@@ -0,0 +1,16 @@
package model
// Bangumi bangumi struct.
type Bangumi struct {
SeasonID string `json:"season_id"`
ShareURL string `json:"share_url"`
Title string `json:"title"`
IsFinish string `json:"is_finish"`
Favorites string `json:"favorites"`
NewestEpIndex string `json:"newest_ep_index"`
LastEpIndex string `json:"last_ep_index"`
TotalCount string `json:"total_count"`
Cover string `json:"cover"`
Evaluate string `json:"evaluate"`
Brief string `json:"brief"`
}

View File

@@ -0,0 +1,47 @@
package model
import (
v1 "go-common/app/service/main/archive/api"
xtime "go-common/library/time"
)
// Channel channel struct
type Channel struct {
Cid int64 `json:"cid"`
Mid int64 `json:"mid"`
Name string `json:"name"`
Intro string `json:"intro"`
Mtime xtime.Time `json:"mtime"`
Count int `json:"count"`
Cover string `json:"cover"`
}
// ChannelExtra channel extra fields
type ChannelExtra struct {
Aid int64
Cid int64
Count int
Cover string
}
// ChannelDetail channel detail info
type ChannelDetail struct {
*Channel
Archives []*v1.Arc `json:"archives"`
}
// ChannelArc channel video struct
type ChannelArc struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Cid int64 `json:"cid"`
Aid int64 `json:"aid"`
OrderNum int `json:"order_num"`
Mtime xtime.Time `json:"mtime"`
}
// ChannelArcSort channel archive sort struct
type ChannelArcSort struct {
Aid int64 `json:"aid"`
OrderNum int `json:"order_num"`
}

View File

@@ -0,0 +1,13 @@
package model
import (
v1 "go-common/app/service/main/archive/api"
)
// CoinArc coin archive.
type CoinArc struct {
*v1.Arc
Coins int64 `json:"coins"`
Time int64 `json:"time"`
IP string `json:"ip"`
}

View File

@@ -0,0 +1,200 @@
package model
import (
"encoding/json"
"strconv"
v1 "go-common/app/service/main/archive/api"
)
// DyCard dynamic data.
type DyCard struct {
Card json.RawMessage `json:"card"`
Desc struct {
UID int64 `json:"uid"`
Type int `json:"type"`
ACL int `json:"acl"`
Rid int64 `json:"rid"`
View int32 `json:"view"`
Repost int32 `json:"repost"`
Comment int32 `json:"comment"`
Like int32 `json:"like"`
IsLiked int32 `json:"is_liked"`
DynamicID int64 `json:"dynamic_id"`
CommentID int64 `json:"comment_id"`
Timestamp int64 `json:"timestamp"`
PreDyID int64 `json:"pre_dy_id"`
OrigDyID int64 `json:"orig_dy_id"`
OrigType int `json:"orig_type"`
RType int `json:"r_type"`
InnerID int64 `json:"inner_id"`
UserProfile *UserProfile `json:"user_profile,omitempty"`
} `json:"desc"`
Extension *DyExtension `json:"extension,omitempty"`
}
// DyResult dynamic result
type DyResult struct {
Card json.RawMessage `json:"card"`
Desc struct {
UID int64 `json:"uid"`
Type int `json:"type"`
ACL int `json:"acl"`
Rid int64 `json:"rid"`
View int32 `json:"view"`
Repost int32 `json:"repost"`
Comment int32 `json:"comment"`
Like int32 `json:"like"`
IsLiked int32 `json:"is_liked"`
DynamicID string `json:"dynamic_id"`
CommentID int64 `json:"comment_id"`
Timestamp int64 `json:"timestamp"`
PreDyID string `json:"pre_dy_id"`
OrigDyID string `json:"orig_dy_id"`
OrigType int `json:"orig_type"`
RType int `json:"r_type"`
InnerID int64 `json:"inner_id"`
UserProfile *UserProfile `json:"user_profile,omitempty"`
} `json:"desc"`
Extension *DyExtension `json:"extension,omitempty"`
}
// DyExtension .
type DyExtension struct {
VoteCfg *struct {
VoteID int64 `json:"vote_id"`
Desc string `json:"desc"`
JoinNum int64 `json:"join_num"`
} `json:"vote_cfg,omitempty"`
}
// DyTotal out dynamic total.
type DyTotal struct {
HasMore bool `json:"has_more"`
List []*DyItem `json:"list"`
}
// DyItem out dynamic item.
type DyItem struct {
Type int `json:"type"`
Top bool `json:"top"`
Card *DyResult `json:"card,omitempty"`
Archive *VideoItem `json:"video,omitempty"`
Fold []*DyItem `json:"fold,omitempty"`
Ctime int64 `json:"ctime"`
Privacy bool `json:"privacy"`
}
// UserProfile dynamic item user profile.
type UserProfile struct {
Pendant struct {
Pid int64 `json:"pid"`
Name string `json:"name"`
Image string `json:"image"`
Expire int64 `json:"expire"`
} `json:"pendant,omitempty"`
DecorateCard struct {
Mid int64 `json:"mid"`
ID int64 `json:"id"`
CardURL string `json:"card_url"`
CardType int `json:"card_type"`
Name string `json:"name"`
ExpireTime int64 `json:"expire_time"`
CardTypeName string `json:"card_type_name"`
UID int64 `json:"uid"`
} `json:"decorate_card,omitempty"`
}
// FromCard format dynamic card.
func (d *DyResult) FromCard(c *DyCard) {
d.Card = c.Card
d.Desc.UID = c.Desc.UID
d.Desc.Type = c.Desc.Type
d.Desc.ACL = c.Desc.ACL
d.Desc.Rid = c.Desc.Rid
d.Desc.View = c.Desc.View
d.Desc.Repost = c.Desc.Repost
d.Desc.Comment = c.Desc.Comment
d.Desc.Like = c.Desc.Like
d.Desc.IsLiked = c.Desc.IsLiked
d.Desc.DynamicID = strconv.FormatInt(c.Desc.DynamicID, 10)
d.Desc.CommentID = c.Desc.CommentID
d.Desc.Timestamp = c.Desc.Timestamp
d.Desc.PreDyID = strconv.FormatInt(c.Desc.PreDyID, 10)
d.Desc.OrigDyID = strconv.FormatInt(c.Desc.OrigDyID, 10)
d.Desc.OrigType = c.Desc.OrigType
d.Desc.RType = c.Desc.RType
d.Desc.InnerID = c.Desc.InnerID
if c.Extension != nil && c.Extension.VoteCfg != nil {
d.Extension = c.Extension
}
if c.Desc.UserProfile != nil {
d.Desc.UserProfile = c.Desc.UserProfile
}
}
// DyList dynamic list.
type DyList struct {
HasMore int `json:"has_more"`
Cards []*DyCard `json:"cards"`
}
// DyActItem dynamic other action items.
type DyActItem struct {
Aid int64 `json:"aid"`
Type int `json:"type"`
ActionTime int64 `json:"action_time"`
Privacy bool `json:"privacy"`
}
// VideoItem user action video item.
type VideoItem struct {
Aid int64 `json:"aid"`
Pic string `json:"pic"`
Title string `json:"title"`
Duration int64 `json:"duration"`
Author struct {
Mid int64 `json:"mid"`
Name string `json:"name"`
Face string `json:"face"`
}
Stat struct {
View int32 `json:"view"`
Danmaku int32 `json:"danmaku"`
Reply int32 `json:"reply"`
Fav int32 `json:"favorite"`
Coin int32 `json:"coin"`
Share int32 `json:"share"`
Like int32 `json:"like"`
}
Rights v1.Rights `json:"rights"`
ActionTime int64 `json:"action_time"`
}
// DyListArg .
type DyListArg struct {
Mid int64 `form:"-"`
Vmid int64 `form:"mid" validate:"min=1"`
DyID int64 `form:"dy_id"`
Qn int `form:"qn" default:"16" validate:"min=1"`
Pn int `form:"pn" default:"1" validate:"min=1"`
LastTime int64 `form:"last_time"`
}
// FromArchive from archive to video item.
func (v *VideoItem) FromArchive(arc *v1.Arc) {
v.Aid = arc.Aid
v.Pic = arc.Pic
v.Title = arc.Title
v.Duration = arc.Duration
v.Author.Mid = arc.Author.Mid
v.Author.Name = arc.Author.Name
v.Author.Face = arc.Author.Face
v.Stat.View = arc.Stat.View
v.Stat.Danmaku = arc.Stat.Danmaku
v.Stat.Reply = arc.Stat.Reply
v.Stat.Fav = arc.Stat.Fav
v.Stat.Share = arc.Stat.Share
v.Stat.Like = arc.Stat.Like
v.Rights = arc.Rights
}

View File

@@ -0,0 +1,15 @@
package model
import "encoding/json"
// ElecInfo elec info.
type ElecInfo struct {
Start int64 `json:"start"`
Show bool `json:"show"`
Total int `json:"total"`
Count int `json:"count"`
State int `json:"state"`
List json.RawMessage `json:"list,omitempty"`
User json.RawMessage `json:"user,omitempty"`
ElecSet json.RawMessage `json:"elec_set,omitempty"`
}

View File

@@ -0,0 +1,24 @@
package model
import "go-common/app/service/main/favorite/model"
// FavNav fav nav struct.
type FavNav struct {
Archive []*model.VideoFolder `json:"archive"`
Playlist int `json:"playlist"`
Topic int `json:"topic"`
Article int `json:"article"`
Album int `json:"album"`
Movie int `json:"movie"`
}
// FavArcArg .
type FavArcArg struct {
Vmid int64 `form:"vmid" validate:"min=1"`
Fid int64 `form:"fid" validate:"min=-1"`
Tid int64 `form:"tid"`
Keyword string `form:"keyword"`
Order string `form:"order"`
Pn int `form:"pn" default:"1" validate:"min=1"`
Ps int `form:"ps" default:"30" validate:"min=1"`
}

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