1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-30 11:53:25 +00:00

Compare commits

..

45 Commits

Author SHA1 Message Date
69a187ddd7 Merge branch 'dev' into database-support
# Conflicts:
#	main.go
2021-10-10 22:35:48 +08:00
560bd5a0cf fix(coolq): fix btree cache for get_image 2021-10-10 11:21:44 +08:00
0b04ec9adb feat(cache): implement Delete 2021-10-08 21:41:47 +08:00
446f624a37 feat(http): accept onebot v12 style endpoint
disabled currently, enabled in v1.1.0
2021-10-06 16:13:40 +08:00
19fd331c46 rf(server): use sync.Once 2021-10-06 15:53:50 +08:00
cd5c6c6a72 clean: clean cache.Init 2021-10-05 22:20:24 +08:00
b8c7941dc8 Merge pull request #1085 from purerosefallen/patch-2
add `ffmpeg` into Dockerfile
2021-10-04 23:44:41 +08:00
41e33fdb3d style: make linter happy 2021-10-03 22:34:08 +08:00
63e950bb83 feat(internal/btree): use md5 key instead of sha1
image/video cache uses md5 key, this commit will reduce 4 used bytes in db
2021-10-03 22:32:11 +08:00
ce944539c1 feat: split out server register
we can add server with less dependency
2021-10-02 23:42:47 +08:00
4b99f64b56 style: move help resetWorkingDir to internal/base 2021-10-02 23:14:36 +08:00
ce6b65ddb5 feat: read cache with disk btree backend 2021-09-29 21:40:25 +08:00
7c4be95c19 feat: store cache with disk btree backend 2021-09-28 22:23:33 +08:00
4da6584f10 feat: unified writing/reading table
These changes table reading/writing to single read/write operation,
and layout to machine byteorder, so db file will be unsupported with
wrong byteorder.
2021-09-28 16:44:45 +08:00
d620fce1ae style: nolint on (*btree.Btree).insertTopLevel 2021-09-28 15:58:30 +08:00
83b4206b15 fix: wrong sha1 cmp
reported by staticcheck.
2021-09-28 15:51:35 +08:00
d464236573 fix: make linter happy
add db into skip-dirs
2021-09-28 15:46:14 +08:00
2927c2214f feat: optimize btree reading/writing 2021-09-28 15:33:33 +08:00
4625c785dd fix: make linter happy in internal/btree 2021-09-28 10:48:19 +08:00
f767213681 feat: init disk-based btree impl 2021-09-27 22:44:45 +08:00
c4d34fa14f Merge branch 'dev' into database-support
# Conflicts:
#	coolq/bot.go
#	modules/config/config.go
2021-09-26 19:49:48 +08:00
1337d3f1f3 style: move internal/config to modules/config
config should not be internal, maybe some module need it.
2021-09-26 19:41:03 +08:00
c2166699e4 feat: multi database support - mongodb. 2021-09-26 19:11:07 +08:00
ddd51e6ca3 style: move global/config to internal/config 2021-09-26 13:32:40 +08:00
a691ee8115 Merge branch 'dev' into dev.db
# Conflicts:
#	coolq/bot.go
2021-09-25 21:21:28 +08:00
35b7b8909e style: make linter happy 2021-09-25 21:13:26 +08:00
cf21e81016 style: move flag parse to internal/base 2021-09-25 21:09:50 +08:00
cd141d7d37 fix: build failed on nosilk platform 2021-09-25 13:28:23 +08:00
1a195278cf add ffmpeg into Dockerfile 2021-09-25 13:25:52 +08:00
5acb01c1a3 refactor: new package modules
move silk, mime to modules
2021-09-25 13:24:33 +08:00
883fca089d style: move global/update to internal/selfupdate
also move checkUpdate to internal/selfupdate
2021-09-25 10:58:54 +08:00
110982651d style: make linter happy 2021-09-25 00:17:36 +08:00
2cf136d031 style: move flag variable into internal/base 2021-09-25 00:12:31 +08:00
f2ed46d6ce style: move coolq.Version into internal/base 2021-09-24 23:28:09 +08:00
87754111ce fix: make golangci-lint happy 2021-09-23 21:11:20 +08:00
1db219fce0 feat: replace gout with net/http.
This significantly reduces binary size:
old 16.5MB
new 15.5MB
on windows/amd64
2021-09-23 21:03:46 +08:00
5cafaea082 fix: token login error under special cases 2021-09-22 17:01:16 +08:00
f629eee7f2 fix typo. 2021-09-22 16:48:59 +08:00
a56e70d07c feat: multi database support - multi db wrapper. 2021-09-22 16:43:27 +08:00
28078d9c8e fix typo. 2021-09-22 14:49:16 +08:00
66266f0d5e feat: multi database support - leveldb. 2021-09-22 14:43:48 +08:00
60d5f4d386 feat: hide key in command line. (#1076)
* feat: hide key in command line.

* Update go.mod

* Update go.sum

* Update main.go

* Update go.mod

* Update go.sum
2021-09-19 23:14:38 +08:00
efdd6bd16a style: move coolq.MSG to global package 2021-09-17 19:08:05 +08:00
6d19f07eb4 fix: incorrect unsafe usage in upstream lib
Updates #1070
2021-09-17 15:37:09 +08:00
760bb175c7 fix: incorrect del friend argument
Fixes #1070
2021-09-17 14:47:00 +08:00
51 changed files with 3148 additions and 1453 deletions

View File

@ -78,7 +78,9 @@ run:
# concurrency: 4 # explicitly omit this value to fully utilize available resources. # concurrency: 4 # explicitly omit this value to fully utilize available resources.
deadline: 5m deadline: 5m
issues-exit-code: 1 issues-exit-code: 1
tests: false skip-dirs:
- db
tests: true
# output configuration options # output configuration options
output: output:
@ -92,4 +94,4 @@ issues:
fix: true fix: true
exclude-use-default: false exclude-use-default: false
exclude: exclude:
- "Error return value of .((os.)?std(out|err)..*|.*Close|.*Flush|os.Remove(All)?|.*print(f|ln)?|os.(Un)?Setenv). is not check" - "Error return value of .((os.)?std(out|err)..*|.*Close|.*Seek|.*Flush|os.Remove(All)?|.*print(f|ln)?|os.(Un)?Setenv). is not check"

View File

@ -27,7 +27,7 @@ builds:
flags: flags:
- -trimpath - -trimpath
ldflags: ldflags:
- -s -w -X github.com/Mrs4s/go-cqhttp/coolq.Version=v{{.Version}} - -s -w -X github.com/Mrs4s/go-cqhttp/internal/base.Version=v{{.Version}}
- id: win - id: win
env: env:
- CGO_ENABLED=0 - CGO_ENABLED=0

View File

@ -14,6 +14,8 @@ RUN set -ex \
FROM alpine:latest FROM alpine:latest
RUN apk add --no-cache ffmpeg
COPY --from=builder /build/cqhttp /usr/bin/cqhttp COPY --from=builder /build/cqhttp /usr/bin/cqhttp
RUN chmod +x /usr/bin/cqhttp RUN chmod +x /usr/bin/cqhttp

View File

@ -10,11 +10,13 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"runtime/debug"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/go-cqhttp/internal/cache"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
@ -23,34 +25,23 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
// Version go-cqhttp的版本信息在编译时使用ldflags进行覆盖
var Version = "unknown"
func init() {
if Version != "unknown" {
return
}
info, ok := debug.ReadBuildInfo()
if ok {
Version = info.Main.Version
}
}
// CQGetLoginInfo 获取登录号信息 // CQGetLoginInfo 获取登录号信息
// //
// https://git.io/Jtz1I // https://git.io/Jtz1I
func (bot *CQBot) CQGetLoginInfo() MSG { func (bot *CQBot) CQGetLoginInfo() global.MSG {
return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname}) return OK(global.MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
} }
// CQGetQiDianAccountInfo 获取企点账号信息 // CQGetQiDianAccountInfo 获取企点账号信息
func (bot *CQBot) CQGetQiDianAccountInfo() MSG { func (bot *CQBot) CQGetQiDianAccountInfo() global.MSG {
if bot.Client.QiDian == nil { if bot.Client.QiDian == nil {
return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议") return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议")
} }
return OK(MSG{ return OK(global.MSG{
"master_id": bot.Client.QiDian.MasterUin, "master_id": bot.Client.QiDian.MasterUin,
"ext_name": bot.Client.QiDian.ExtName, "ext_name": bot.Client.QiDian.ExtName,
"create_time": bot.Client.QiDian.CreateTime, "create_time": bot.Client.QiDian.CreateTime,
@ -60,10 +51,10 @@ func (bot *CQBot) CQGetQiDianAccountInfo() MSG {
// CQGetFriendList 获取好友列表 // CQGetFriendList 获取好友列表
// //
// https://git.io/Jtz1L // https://git.io/Jtz1L
func (bot *CQBot) CQGetFriendList() MSG { func (bot *CQBot) CQGetFriendList() global.MSG {
fs := make([]MSG, 0, len(bot.Client.FriendList)) fs := make([]global.MSG, 0, len(bot.Client.FriendList))
for _, f := range bot.Client.FriendList { for _, f := range bot.Client.FriendList {
fs = append(fs, MSG{ fs = append(fs, global.MSG{
"nickname": f.Nickname, "nickname": f.Nickname,
"remark": f.Remark, "remark": f.Remark,
"user_id": f.Uin, "user_id": f.Uin,
@ -75,15 +66,15 @@ func (bot *CQBot) CQGetFriendList() MSG {
// CQGetUnidirectionalFriendList 获取单向好友列表 // CQGetUnidirectionalFriendList 获取单向好友列表
// //
// //
func (bot *CQBot) CQGetUnidirectionalFriendList() MSG { func (bot *CQBot) CQGetUnidirectionalFriendList() global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList() list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil { if err != nil {
log.Errorf("获取单向好友列表时出现错误: %v", err) log.Errorf("获取单向好友列表时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error()) return Failed(100, "API_ERROR", err.Error())
} }
fs := make([]MSG, 0, len(list)) fs := make([]global.MSG, 0, len(list))
for _, f := range list { for _, f := range list {
fs = append(fs, MSG{ fs = append(fs, global.MSG{
"nickname": f.Nickname, "nickname": f.Nickname,
"user_id": f.Uin, "user_id": f.Uin,
"source": f.Source, "source": f.Source,
@ -95,7 +86,7 @@ func (bot *CQBot) CQGetUnidirectionalFriendList() MSG {
// CQDeleteUnidirectionalFriend 删除单向好友 // CQDeleteUnidirectionalFriend 删除单向好友
// //
// //
func (bot *CQBot) CQDeleteUnidirectionalFriend(uin int64) MSG { func (bot *CQBot) CQDeleteUnidirectionalFriend(uin int64) global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList() list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil { if err != nil {
log.Errorf("获取单向好友列表时出现错误: %v", err) log.Errorf("获取单向好友列表时出现错误: %v", err)
@ -116,7 +107,7 @@ func (bot *CQBot) CQDeleteUnidirectionalFriend(uin int64) MSG {
// CQDeleteFriend 删除好友 // CQDeleteFriend 删除好友
// //
// //
func (bot *CQBot) CQDeleteFriend(uin int64) MSG { func (bot *CQBot) CQDeleteFriend(uin int64) global.MSG {
if bot.Client.FindFriend(uin) == nil { if bot.Client.FindFriend(uin) == nil {
return Failed(100, "FRIEND_NOT_FOUND", "好友不存在") return Failed(100, "FRIEND_NOT_FOUND", "好友不存在")
} }
@ -130,13 +121,13 @@ func (bot *CQBot) CQDeleteFriend(uin int64) MSG {
// CQGetGroupList 获取群列表 // CQGetGroupList 获取群列表
// //
// https://git.io/Jtz1t // https://git.io/Jtz1t
func (bot *CQBot) CQGetGroupList(noCache bool) MSG { func (bot *CQBot) CQGetGroupList(noCache bool) global.MSG {
gs := make([]MSG, 0, len(bot.Client.GroupList)) gs := make([]global.MSG, 0, len(bot.Client.GroupList))
if noCache { if noCache {
_ = bot.Client.ReloadGroupList() _ = bot.Client.ReloadGroupList()
} }
for _, g := range bot.Client.GroupList { for _, g := range bot.Client.GroupList {
gs = append(gs, MSG{ gs = append(gs, global.MSG{
"group_id": g.Code, "group_id": g.Code,
"group_name": g.Name, "group_name": g.Name,
"group_memo": g.Memo, "group_memo": g.Memo,
@ -152,7 +143,7 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
// CQGetGroupInfo 获取群信息 // CQGetGroupInfo 获取群信息
// //
// https://git.io/Jtz1O // https://git.io/Jtz1O
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil || noCache { if group == nil || noCache {
group, _ = bot.Client.GetGroupInfo(groupID) group, _ = bot.Client.GetGroupInfo(groupID)
@ -165,7 +156,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
} }
for _, g := range info { for _, g := range info {
if g.Code == groupID { if g.Code == groupID {
return OK(MSG{ return OK(global.MSG{
"group_id": g.Code, "group_id": g.Code,
"group_name": g.Name, "group_name": g.Name,
"group_memo": g.Memo, "group_memo": g.Memo,
@ -177,7 +168,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
} }
} }
} else { } else {
return OK(MSG{ return OK(global.MSG{
"group_id": group.Code, "group_id": group.Code,
"group_name": group.Name, "group_name": group.Name,
"group_memo": group.Memo, "group_memo": group.Memo,
@ -193,7 +184,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
// CQGetGroupMemberList 获取群成员列表 // CQGetGroupMemberList 获取群成员列表
// //
// https://git.io/Jtz13 // https://git.io/Jtz13
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -206,7 +197,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
} }
group.Members = t group.Members = t
} }
members := make([]MSG, 0, len(group.Members)) members := make([]global.MSG, 0, len(group.Members))
for _, m := range group.Members { for _, m := range group.Members {
members = append(members, convertGroupMemberInfo(groupID, m)) members = append(members, convertGroupMemberInfo(groupID, m))
} }
@ -216,7 +207,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
// CQGetGroupMemberInfo 获取群成员信息 // CQGetGroupMemberInfo 获取群成员信息
// //
// https://git.io/Jtz1s // https://git.io/Jtz1s
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -241,7 +232,7 @@ func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG
// CQGetGroupFileSystemInfo 扩展API-获取群文件系统信息 // CQGetGroupFileSystemInfo 扩展API-获取群文件系统信息
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) MSG { func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -253,7 +244,7 @@ func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) MSG {
// CQGetGroupRootFiles 扩展API-获取群根目录文件列表 // CQGetGroupRootFiles 扩展API-获取群根目录文件列表
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG { func (bot *CQBot) CQGetGroupRootFiles(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -264,7 +255,7 @@ func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err) log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error()) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"files": files, "files": files,
"folders": folders, "folders": folders,
}) })
@ -273,7 +264,7 @@ func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
// CQGetGroupFilesByFolderID 扩展API-获取群子目录文件列表 // CQGetGroupFilesByFolderID 扩展API-获取群子目录文件列表
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG { func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -284,7 +275,7 @@ func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupID, folderID, err) log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupID, folderID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error()) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"files": files, "files": files,
"folders": folders, "folders": folders,
}) })
@ -293,12 +284,12 @@ func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG
// CQGetGroupFileURL 扩展API-获取群文件资源链接 // CQGetGroupFileURL 扩展API-获取群文件资源链接
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5
func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) MSG { func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) global.MSG {
url := bot.Client.GetGroupFileUrl(groupID, fileID, busID) url := bot.Client.GetGroupFileUrl(groupID, fileID, busID)
if url == "" { if url == "" {
return Failed(100, "FILE_SYSTEM_API_ERROR") return Failed(100, "FILE_SYSTEM_API_ERROR")
} }
return OK(MSG{ return OK(global.MSG{
"url": url, "url": url,
}) })
} }
@ -306,7 +297,7 @@ func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) M
// CQUploadGroupFile 扩展API-上传群文件 // CQUploadGroupFile 扩展API-上传群文件
// //
// https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6 // https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6
func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) MSG { func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) global.MSG {
if !global.PathExists(file) { if !global.PathExists(file) {
log.Errorf("上传群文件 %v 失败: 文件不存在", file) log.Errorf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在") return Failed(100, "FILE_NOT_FOUND", "文件不存在")
@ -329,7 +320,7 @@ func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) MS
// CQGroupFileCreateFolder 拓展API-创建群文件文件夹 // CQGroupFileCreateFolder 拓展API-创建群文件文件夹
// //
// //
func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) MSG { func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -345,7 +336,7 @@ func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string)
// CQGroupFileDeleteFolder 拓展API-删除群文件文件夹 // CQGroupFileDeleteFolder 拓展API-删除群文件文件夹
// //
// //
func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) MSG { func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -361,7 +352,7 @@ func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) MSG {
// CQGroupFileDeleteFile 拓展API-删除群文件 // CQGroupFileDeleteFile 拓展API-删除群文件
// //
// //
func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) MSG { func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID) fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
@ -377,7 +368,7 @@ func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) M
// CQGetWordSlices 隐藏API-获取中文分词 // CQGetWordSlices 隐藏API-获取中文分词
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D-%E9%9A%90%E8%97%8F-api // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D-%E9%9A%90%E8%97%8F-api
func (bot *CQBot) CQGetWordSlices(content string) MSG { func (bot *CQBot) CQGetWordSlices(content string) global.MSG {
slices, err := bot.Client.GetWordSegmentation(content) slices, err := bot.Client.GetWordSegmentation(content)
if err != nil { if err != nil {
return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error()) return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error())
@ -385,13 +376,13 @@ func (bot *CQBot) CQGetWordSlices(content string) MSG {
for i := 0; i < len(slices); i++ { for i := 0; i < len(slices); i++ {
slices[i] = strings.ReplaceAll(slices[i], "\u0000", "") slices[i] = strings.ReplaceAll(slices[i], "\u0000", "")
} }
return OK(MSG{"slices": slices}) return OK(global.MSG{"slices": slices})
} }
// CQSendGroupMessage 发送群消息 // CQSendGroupMessage 发送群消息
// //
// https://git.io/Jtz1c // https://git.io/Jtz1c
func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape bool) MSG { func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil { if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -430,13 +421,13 @@ func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape b
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(m.String()), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(global.MSG{"message_id": mid})
} }
// CQSendGroupForwardMessage 扩展API-发送合并转发(群) // CQSendGroupForwardMessage 扩展API-发送合并转发(群)
// //
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E7%BE%A4 // https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E7%BE%A4
func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG { func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) global.MSG {
if m.Type != gjson.JSON { if m.Type != gjson.JSON {
return Failed(100) return Failed(100)
} }
@ -474,20 +465,19 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
ts.Add(time.Second) ts.Add(time.Second)
if e.Get("data.id").Exists() { if e.Get("data.id").Exists() {
i := e.Get("data.id").Int() i := e.Get("data.id").Int()
m := bot.GetMessage(int32(i)) m, _ := bot.db.GetGroupMessageByGlobalID(int32(i))
if m != nil { if m != nil {
sender := m["sender"].(message.Sender)
return &message.ForwardNode{ return &message.ForwardNode{
SenderId: sender.Uin, SenderId: m.Attribute.SenderUin,
SenderName: (&sender).DisplayName(), SenderName: m.Attribute.SenderName,
Time: func() int32 { Time: func() int32 {
msgTime := m["time"].(int32) msgTime := m.Attribute.Timestamp
if hasCustom && msgTime == 0 { if hasCustom && msgTime == 0 {
return int32(ts.Unix()) return int32(ts.Unix())
} }
return msgTime return int32(msgTime)
}(), }(),
Message: resolveElement(bot.ConvertStringMessage(m["message"].(string), true)), Message: resolveElement(bot.ConvertContentMessage(m.Content, true)),
} }
} }
log.Warnf("警告: 引用消息 %v 错误或数据库未开启.", e.Get("data.id").Str) log.Warnf("警告: 引用消息 %v 错误或数据库未开启.", e.Get("data.id").Str)
@ -558,7 +548,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
log.Warnf("合并转发(群)消息发送失败: 账号可能被风控.") log.Warnf("合并转发(群)消息发送失败: 账号可能被风控.")
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
return OK(MSG{ return OK(global.MSG{
"message_id": bot.InsertGroupMessage(ret), "message_id": bot.InsertGroupMessage(ret),
}) })
} }
@ -568,7 +558,7 @@ func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
// CQSendPrivateMessage 发送私聊消息 // CQSendPrivateMessage 发送私聊消息
// //
// https://git.io/Jtz1l // https://git.io/Jtz1l
func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, m gjson.Result, autoEscape bool) MSG { func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, m gjson.Result, autoEscape bool) global.MSG {
var elem []message.IMessageElement var elem []message.IMessageElement
if m.Type == gjson.JSON { if m.Type == gjson.JSON {
elem = bot.ConvertObjectMessage(m, false) elem = bot.ConvertObjectMessage(m, false)
@ -588,13 +578,13 @@ func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, m gjson.Resu
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出") return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
} }
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(m.String()), mid) log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(global.MSG{"message_id": mid})
} }
// CQSetGroupCard 设置群名片(群备注) // CQSetGroupCard 设置群名片(群备注)
// //
// https://git.io/Jtz1B // https://git.io/Jtz1B
func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG { func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
m.EditCard(card) m.EditCard(card)
@ -607,7 +597,7 @@ func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG {
// CQSetGroupSpecialTitle 设置群组专属头衔 // CQSetGroupSpecialTitle 设置群组专属头衔
// //
// https://git.io/Jtz10 // https://git.io/Jtz10
func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MSG { func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
m.EditSpecialTitle(title) m.EditSpecialTitle(title)
@ -620,7 +610,7 @@ func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MS
// CQSetGroupName 设置群名 // CQSetGroupName 设置群名
// //
// https://git.io/Jtz12 // https://git.io/Jtz12
func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG { func (bot *CQBot) CQSetGroupName(groupID int64, name string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.UpdateName(name) g.UpdateName(name)
return OK(nil) return OK(nil)
@ -631,7 +621,7 @@ func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG {
// CQSetGroupMemo 扩展API-发送群公告 // CQSetGroupMemo 扩展API-发送群公告
// //
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%BE%A4%E5%85%AC%E5%91%8A // https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%BE%A4%E5%85%AC%E5%91%8A
func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) MSG { func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if g.SelfPermission() == client.Member { if g.SelfPermission() == client.Member {
return Failed(100, "PERMISSION_DENIED", "权限不足") return Failed(100, "PERMISSION_DENIED", "权限不足")
@ -659,7 +649,7 @@ func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) MSG {
// CQSetGroupKick 群组踢人 // CQSetGroupKick 群组踢人
// //
// https://git.io/Jtz1V // https://git.io/Jtz1V
func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) MSG { func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
err := m.Kick(msg, block) err := m.Kick(msg, block)
@ -675,7 +665,7 @@ func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool)
// CQSetGroupBan 群组单人禁言 // CQSetGroupBan 群组单人禁言
// //
// https://git.io/Jtz1w // https://git.io/Jtz1w
func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG { func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil { if m := g.FindMember(userID); m != nil {
err := m.Mute(duration) err := m.Mute(duration)
@ -694,7 +684,7 @@ func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG {
// CQSetGroupWholeBan 群组全员禁言 // CQSetGroupWholeBan 群组全员禁言
// //
// https://git.io/Jtz1o // https://git.io/Jtz1o
func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG { func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.MuteAll(enable) g.MuteAll(enable)
return OK(nil) return OK(nil)
@ -705,7 +695,7 @@ func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG {
// CQSetGroupLeave 退出群组 // CQSetGroupLeave 退出群组
// //
// https://git.io/Jtz1K // https://git.io/Jtz1K
func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG { func (bot *CQBot) CQSetGroupLeave(groupID int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
g.Quit() g.Quit()
return OK(nil) return OK(nil)
@ -716,7 +706,7 @@ func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG {
// CQGetAtAllRemain 扩展API-获取群 @全体成员 剩余次数 // CQGetAtAllRemain 扩展API-获取群 @全体成员 剩余次数
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4-%E5%85%A8%E4%BD%93%E6%88%90%E5%91%98-%E5%89%A9%E4%BD%99%E6%AC%A1%E6%95%B0 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4-%E5%85%A8%E4%BD%93%E6%88%90%E5%91%98-%E5%89%A9%E4%BD%99%E6%AC%A1%E6%95%B0
func (bot *CQBot) CQGetAtAllRemain(groupID int64) MSG { func (bot *CQBot) CQGetAtAllRemain(groupID int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
i, err := bot.Client.GetAtAllRemain(groupID) i, err := bot.Client.GetAtAllRemain(groupID)
if err != nil { if err != nil {
@ -730,7 +720,7 @@ func (bot *CQBot) CQGetAtAllRemain(groupID int64) MSG {
// CQProcessFriendRequest 处理加好友请求 // CQProcessFriendRequest 处理加好友请求
// //
// https://git.io/Jtz11 // https://git.io/Jtz11
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG { func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) global.MSG {
req, ok := bot.friendReqCache.Load(flag) req, ok := bot.friendReqCache.Load(flag)
if !ok { if !ok {
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在") return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
@ -746,7 +736,7 @@ func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
// CQProcessGroupRequest 处理加群请求/邀请 // CQProcessGroupRequest 处理加群请求/邀请
// //
// https://git.io/Jtz1D // https://git.io/Jtz1D
func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) MSG { func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) global.MSG {
msgs, err := bot.Client.GetGroupSystemMessages() msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Errorf("获取群系统消息失败: %v", err) log.Errorf("获取群系统消息失败: %v", err)
@ -790,30 +780,29 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
// CQDeleteMessage 撤回消息 // CQDeleteMessage 撤回消息
// //
// https:// git.io/Jtz1y // https:// git.io/Jtz1y
func (bot *CQBot) CQDeleteMessage(messageID int32) MSG { func (bot *CQBot) CQDeleteMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg, err := bot.db.GetMessageByGlobalID(messageID)
if msg == nil { if err != nil {
log.Warnf("撤回消息时出现错误: %v", err)
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
} }
if _, ok := msg["group"]; ok { switch o := msg.(type) {
if msg["internal-id"] == nil { case *db.StoredGroupMessage:
// TODO 撤回临时对话消息 if err = bot.Client.RecallGroupMessage(o.GroupCode, o.Attribute.MessageSeq, o.Attribute.InternalID); err != nil {
log.Warnf("撤回 %v 失败: 无法撤回临时对话消息", messageID)
return Failed(100, "CANNOT_RECALL_TEMP_MSG", "无法撤回临时对话消息")
}
if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageID, err) log.Warnf("撤回 %v 失败: %v", messageID, err)
return Failed(100, "RECALL_API_ERROR", err.Error()) return Failed(100, "RECALL_API_ERROR", err.Error())
} }
} else { case *db.StoredPrivateMessage:
if msg["sender"].(message.Sender).Uin != bot.Client.Uin { if o.Attribute.SenderUin != bot.Client.Uin {
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageID) log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageID)
return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息") return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息")
} }
if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil { if err = bot.Client.RecallPrivateMessage(o.TargetUin, o.Attribute.Timestamp, o.Attribute.MessageSeq, o.Attribute.InternalID); err != nil {
log.Warnf("撤回 %v 失败: %v", messageID, err) log.Warnf("撤回 %v 失败: %v", messageID, err)
return Failed(100, "RECALL_API_ERROR", err.Error()) return Failed(100, "RECALL_API_ERROR", err.Error())
} }
default:
return Failed(100, "UNKNOWN_ERROR")
} }
return OK(nil) return OK(nil)
} }
@ -821,7 +810,7 @@ func (bot *CQBot) CQDeleteMessage(messageID int32) MSG {
// CQSetGroupAdmin 群组设置管理员 // CQSetGroupAdmin 群组设置管理员
// //
// https://git.io/Jtz1S // https://git.io/Jtz1S
func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG { func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) global.MSG {
group := bot.Client.FindGroup(groupID) group := bot.Client.FindGroup(groupID)
if group == nil || group.OwnerUin != bot.Client.Uin { if group == nil || group.OwnerUin != bot.Client.Uin {
return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足") return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
@ -843,12 +832,12 @@ func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG {
// CQGetVipInfo 扩展API-获取VIP信息 // CQGetVipInfo 扩展API-获取VIP信息
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96vip%E4%BF%A1%E6%81%AF // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96vip%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetVipInfo(userID int64) MSG { func (bot *CQBot) CQGetVipInfo(userID int64) global.MSG {
vip, err := bot.Client.GetVipInfo(userID) vip, err := bot.Client.GetVipInfo(userID)
if err != nil { if err != nil {
return Failed(100, "VIP_API_ERROR", err.Error()) return Failed(100, "VIP_API_ERROR", err.Error())
} }
msg := MSG{ msg := global.MSG{
"user_id": vip.Uin, "user_id": vip.Uin,
"nickname": vip.Name, "nickname": vip.Name,
"level": vip.Level, "level": vip.Level,
@ -863,11 +852,11 @@ func (bot *CQBot) CQGetVipInfo(userID int64) MSG {
// CQGetGroupHonorInfo 获取群荣誉信息 // CQGetGroupHonorInfo 获取群荣誉信息
// //
// https://git.io/Jtz1H // https://git.io/Jtz1H
func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG { func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) global.MSG {
msg := MSG{"group_id": groupID} msg := global.MSG{"group_id": groupID}
convertMem := func(memList []client.HonorMemberInfo) (ret []MSG) { convertMem := func(memList []client.HonorMemberInfo) (ret []global.MSG) {
for _, mem := range memList { for _, mem := range memList {
ret = append(ret, MSG{ ret = append(ret, global.MSG{
"user_id": mem.Uin, "user_id": mem.Uin,
"nickname": mem.Name, "nickname": mem.Name,
"avatar": mem.Avatar, "avatar": mem.Avatar,
@ -879,7 +868,7 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
if t == "talkative" || t == "all" { if t == "talkative" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Talkative); err == nil { if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Talkative); err == nil {
if honor.CurrentTalkative.Uin != 0 { if honor.CurrentTalkative.Uin != 0 {
msg["current_talkative"] = MSG{ msg["current_talkative"] = global.MSG{
"user_id": honor.CurrentTalkative.Uin, "user_id": honor.CurrentTalkative.Uin,
"nickname": honor.CurrentTalkative.Name, "nickname": honor.CurrentTalkative.Name,
"avatar": honor.CurrentTalkative.Avatar, "avatar": honor.CurrentTalkative.Avatar,
@ -920,12 +909,12 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
// CQGetStrangerInfo 获取陌生人信息 // CQGetStrangerInfo 获取陌生人信息
// //
// https://git.io/Jtz17 // https://git.io/Jtz17
func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG { func (bot *CQBot) CQGetStrangerInfo(userID int64) global.MSG {
info, err := bot.Client.GetSummaryInfo(userID) info, err := bot.Client.GetSummaryInfo(userID)
if err != nil { if err != nil {
return Failed(100, "SUMMARY_API_ERROR", err.Error()) return Failed(100, "SUMMARY_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(global.MSG{
"user_id": info.Uin, "user_id": info.Uin,
"nickname": info.Nickname, "nickname": info.Nickname,
"qid": info.Qid, "qid": info.Qid,
@ -947,7 +936,7 @@ func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG {
// CQHandleQuickOperation 隐藏API-对事件执行快速操作 // CQHandleQuickOperation 隐藏API-对事件执行快速操作
// //
// https://git.io/Jtz15 // https://git.io/Jtz15
func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG { func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) global.MSG {
postType := context.Get("post_type").Str postType := context.Get("post_type").Str
switch postType { switch postType {
@ -958,15 +947,15 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
reply := operation.Get("reply") reply := operation.Get("reply")
if reply.Exists() { if reply.Exists() {
autoEscape := global.EnsureBool(operation.Get("auto_escape"), false) autoEscape := param.EnsureBool(operation.Get("auto_escape"), false)
at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group" at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group"
if at && reply.IsArray() { if at && reply.IsArray() {
// 在 reply 数组头部插入CQ码 // 在 reply 数组头部插入CQ码
replySegments := make([]MSG, 0) replySegments := make([]global.MSG, 0)
segments := make([]MSG, 0) segments := make([]global.MSG, 0)
segments = append(segments, MSG{ segments = append(segments, global.MSG{
"type": "at", "type": "at",
"data": MSG{ "data": global.MSG{
"qq": context.Get("sender.user_id").Int(), "qq": context.Get("sender.user_id").Int(),
}, },
}) })
@ -1036,15 +1025,26 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
// CQGetImage 获取图片(修改自OneBot) // CQGetImage 获取图片(修改自OneBot)
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%9B%BE%E7%89%87%E4%BF%A1%E6%81%AF // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%9B%BE%E7%89%87%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetImage(file string) MSG { func (bot *CQBot) CQGetImage(file string) global.MSG {
if !global.PathExists(path.Join(global.ImagePath, file)) { var b []byte
return Failed(100) var err error
if cache.EnableCacheDB && strings.HasSuffix(file, ".image") {
var f []byte
f, err = hex.DecodeString(strings.TrimSuffix(file, ".image"))
b = cache.Image.Get(f)
} }
b, err := os.ReadFile(path.Join(global.ImagePath, file))
if b == nil {
if !global.PathExists(path.Join(global.ImagePath, file)) {
return Failed(100)
}
b, err = os.ReadFile(path.Join(global.ImagePath, file))
}
if err == nil { if err == nil {
r := binary.NewReader(b) r := binary.NewReader(b)
r.ReadBytes(16) r.ReadBytes(16)
msg := MSG{ msg := global.MSG{
"size": r.ReadInt32(), "size": r.ReadInt32(),
"filename": r.ReadString(), "filename": r.ReadString(),
"url": r.ReadString(), "url": r.ReadString(),
@ -1067,7 +1067,7 @@ func (bot *CQBot) CQGetImage(file string) MSG {
// CQDownloadFile 扩展API-下载文件到缓存目录 // CQDownloadFile 扩展API-下载文件到缓存目录
// //
// https://docs.go-cqhttp.org/api/#%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6%E5%88%B0%E7%BC%93%E5%AD%98%E7%9B%AE%E5%BD%95 // https://docs.go-cqhttp.org/api/#%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6%E5%88%B0%E7%BC%93%E5%AD%98%E7%9B%AE%E5%BD%95
func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCount int) MSG { func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCount int) global.MSG {
hash := md5.Sum([]byte(url)) hash := md5.Sum([]byte(url))
file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache") file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache")
if global.PathExists(file) { if global.PathExists(file) {
@ -1081,7 +1081,7 @@ func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCo
return Failed(100, "DOWNLOAD_FILE_ERROR", err.Error()) return Failed(100, "DOWNLOAD_FILE_ERROR", err.Error())
} }
abs, _ := filepath.Abs(file) abs, _ := filepath.Abs(file)
return OK(MSG{ return OK(global.MSG{
"file": abs, "file": abs,
}) })
} }
@ -1089,16 +1089,16 @@ func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCo
// CQGetForwardMessage 获取合并转发消息 // CQGetForwardMessage 获取合并转发消息
// //
// https://git.io/Jtz1F // https://git.io/Jtz1F
func (bot *CQBot) CQGetForwardMessage(resID string) MSG { func (bot *CQBot) CQGetForwardMessage(resID string) global.MSG {
m := bot.Client.GetForwardMessage(resID) m := bot.Client.GetForwardMessage(resID)
if m == nil { if m == nil {
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
r := make([]MSG, 0, len(m.Nodes)) r := make([]global.MSG, 0, len(m.Nodes))
for _, n := range m.Nodes { for _, n := range m.Nodes {
bot.checkMedia(n.Message) bot.checkMedia(n.Message)
r = append(r, MSG{ r = append(r, global.MSG{
"sender": MSG{ "sender": global.MSG{
"user_id": n.SenderId, "user_id": n.SenderId,
"nickname": n.SenderName, "nickname": n.SenderName,
}, },
@ -1106,7 +1106,7 @@ func (bot *CQBot) CQGetForwardMessage(resID string) MSG {
"content": ToFormattedMessage(n.Message, 0, false), "content": ToFormattedMessage(n.Message, 0, false),
}) })
} }
return OK(MSG{ return OK(global.MSG{
"messages": r, "messages": r,
}) })
} }
@ -1114,45 +1114,39 @@ func (bot *CQBot) CQGetForwardMessage(resID string) MSG {
// CQGetMessage 获取消息 // CQGetMessage 获取消息
// //
// https://git.io/Jtz1b // https://git.io/Jtz1b
func (bot *CQBot) CQGetMessage(messageID int32) MSG { func (bot *CQBot) CQGetMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg, err := bot.db.GetMessageByGlobalID(messageID)
if msg == nil { if err != nil {
log.Warnf("获取消息时出现错误: %v", err)
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
sender := msg["sender"].(message.Sender) m := global.MSG{
gid, isGroup := msg["group"] "message_id": msg.GetGlobalID(),
raw := msg["message"].(string) "message_id_v2": msg.GetID(),
return OK(MSG{ "message_type": msg.GetType(),
"message_id": messageID, "real_id": msg.GetAttribute().MessageSeq,
"real_id": msg["message-id"], "message_seq": msg.GetAttribute().MessageSeq,
"message_seq": msg["message-id"], "group": msg.GetType() == "group",
"group": isGroup, "sender": global.MSG{
"group_id": gid, "user_id": msg.GetAttribute().SenderUin,
"message_type": func() string { "nickname": msg.GetAttribute().SenderName,
if isGroup {
return "group"
}
return "private"
}(),
"sender": MSG{
"user_id": sender.Uin,
"nickname": sender.Nickname,
}, },
"time": msg["time"], "time": msg.GetAttribute().Timestamp,
"raw_message": raw, }
"message": ToFormattedMessage(bot.ConvertStringMessage(raw, isGroup), func() int64 { switch o := msg.(type) {
if isGroup { case *db.StoredGroupMessage:
return gid.(int64) m["group_id"] = o.GroupCode
} m["message"] = ToFormattedMessage(bot.ConvertContentMessage(o.Content, true), o.GroupCode, false)
return 0 case *db.StoredPrivateMessage:
}(), false), m["message"] = ToFormattedMessage(bot.ConvertContentMessage(o.Content, false), 0, false)
}) }
return OK(m)
} }
// CQGetGroupSystemMessages 扩展API-获取群文件系统消息 // CQGetGroupSystemMessages 扩展API-获取群文件系统消息
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E7%B3%BB%E7%BB%9F%E6%B6%88%E6%81%AF // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E7%B3%BB%E7%BB%9F%E6%B6%88%E6%81%AF
func (bot *CQBot) CQGetGroupSystemMessages() MSG { func (bot *CQBot) CQGetGroupSystemMessages() global.MSG {
msg, err := bot.Client.GetGroupSystemMessages() msg, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Warnf("获取群系统消息失败: %v", err) log.Warnf("获取群系统消息失败: %v", err)
@ -1164,7 +1158,7 @@ func (bot *CQBot) CQGetGroupSystemMessages() MSG {
// CQGetGroupMessageHistory 获取群消息历史记录 // CQGetGroupMessageHistory 获取群消息历史记录
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%B6%88%E6%81%AF%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%B6%88%E6%81%AF%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95
func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG { func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) global.MSG {
if g := bot.Client.FindGroup(groupID); g == nil { if g := bot.Client.FindGroup(groupID); g == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
@ -1180,7 +1174,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
log.Warnf("获取群历史消息失败: %v", err) log.Warnf("获取群历史消息失败: %v", err)
return Failed(100, "MESSAGES_API_ERROR", err.Error()) return Failed(100, "MESSAGES_API_ERROR", err.Error())
} }
ms := make([]MSG, 0, len(msg)) ms := make([]global.MSG, 0, len(msg))
for _, m := range msg { for _, m := range msg {
id := m.Id id := m.Id
bot.checkMedia(m.Elements) bot.checkMedia(m.Elements)
@ -1191,7 +1185,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
t["message_id"] = id t["message_id"] = id
ms = append(ms, t) ms = append(ms, t)
} }
return OK(MSG{ return OK(global.MSG{
"messages": ms, "messages": ms,
}) })
} }
@ -1199,22 +1193,22 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupID int64, seq int64) MSG {
// CQGetOnlineClients 扩展API-获取当前账号在线客户端列表 // CQGetOnlineClients 扩展API-获取当前账号在线客户端列表
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E8%B4%A6%E5%8F%B7%E5%9C%A8%E7%BA%BF%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%88%97%E8%A1%A8 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E8%B4%A6%E5%8F%B7%E5%9C%A8%E7%BA%BF%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG { func (bot *CQBot) CQGetOnlineClients(noCache bool) global.MSG {
if noCache { if noCache {
if err := bot.Client.RefreshStatus(); err != nil { if err := bot.Client.RefreshStatus(); err != nil {
log.Warnf("刷新客户端状态时出现问题 %v", err) log.Warnf("刷新客户端状态时出现问题 %v", err)
return Failed(100, "REFRESH_STATUS_ERROR", err.Error()) return Failed(100, "REFRESH_STATUS_ERROR", err.Error())
} }
} }
d := make([]MSG, 0, len(bot.Client.OnlineClients)) d := make([]global.MSG, 0, len(bot.Client.OnlineClients))
for _, oc := range bot.Client.OnlineClients { for _, oc := range bot.Client.OnlineClients {
d = append(d, MSG{ d = append(d, global.MSG{
"app_id": oc.AppId, "app_id": oc.AppId,
"device_name": oc.DeviceName, "device_name": oc.DeviceName,
"device_kind": oc.DeviceKind, "device_kind": oc.DeviceKind,
}) })
} }
return OK(MSG{ return OK(global.MSG{
"clients": d, "clients": d,
}) })
} }
@ -1222,21 +1216,21 @@ func (bot *CQBot) CQGetOnlineClients(noCache bool) MSG {
// CQCanSendImage 检查是否可以发送图片(此处永远返回true) // CQCanSendImage 检查是否可以发送图片(此处永远返回true)
// //
// https://git.io/Jtz1N // https://git.io/Jtz1N
func (bot *CQBot) CQCanSendImage() MSG { func (bot *CQBot) CQCanSendImage() global.MSG {
return OK(MSG{"yes": true}) return OK(global.MSG{"yes": true})
} }
// CQCanSendRecord 检查是否可以发送语音(此处永远返回true) // CQCanSendRecord 检查是否可以发送语音(此处永远返回true)
// //
// https://git.io/Jtz1x // https://git.io/Jtz1x
func (bot *CQBot) CQCanSendRecord() MSG { func (bot *CQBot) CQCanSendRecord() global.MSG {
return OK(MSG{"yes": true}) return OK(global.MSG{"yes": true})
} }
// CQOcrImage 扩展API-图片OCR // CQOcrImage 扩展API-图片OCR
// //
// https://docs.go-cqhttp.org/api/#%E5%9B%BE%E7%89%87-ocr // https://docs.go-cqhttp.org/api/#%E5%9B%BE%E7%89%87-ocr
func (bot *CQBot) CQOcrImage(imageID string) MSG { func (bot *CQBot) CQOcrImage(imageID string) global.MSG {
img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageID}, false, true) img, err := bot.makeImageOrVideoElem(map[string]string{"file": imageID}, false, true)
if err != nil { if err != nil {
log.Warnf("load image error: %v", err) log.Warnf("load image error: %v", err)
@ -1253,7 +1247,7 @@ func (bot *CQBot) CQOcrImage(imageID string) MSG {
// CQSetGroupPortrait 扩展API-设置群头像 // CQSetGroupPortrait 扩展API-设置群头像
// //
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F // https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F
func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) MSG { func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) global.MSG {
if g := bot.Client.FindGroup(groupID); g != nil { if g := bot.Client.FindGroup(groupID); g != nil {
img, err := global.FindFile(file, cache, global.ImagePath) img, err := global.FindFile(file, cache, global.ImagePath)
if err != nil { if err != nil {
@ -1269,7 +1263,7 @@ func (bot *CQBot) CQSetGroupPortrait(groupID int64, file, cache string) MSG {
// CQSetGroupAnonymousBan 群组匿名用户禁言 // CQSetGroupAnonymousBan 群组匿名用户禁言
// //
// https://git.io/Jtz1p // https://git.io/Jtz1p
func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration int32) MSG { func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration int32) global.MSG {
if flag == "" { if flag == "" {
return Failed(100, "INVALID_FLAG", "无效的flag") return Failed(100, "INVALID_FLAG", "无效的flag")
} }
@ -1292,8 +1286,8 @@ func (bot *CQBot) CQSetGroupAnonymousBan(groupID int64, flag string, duration in
// CQGetStatus 获取运行状态 // CQGetStatus 获取运行状态
// //
// https://git.io/JtzMe // https://git.io/JtzMe
func (bot *CQBot) CQGetStatus() MSG { func (bot *CQBot) CQGetStatus() global.MSG {
return OK(MSG{ return OK(global.MSG{
"app_initialized": true, "app_initialized": true,
"app_enabled": true, "app_enabled": true,
"plugins_good": nil, "plugins_good": nil,
@ -1307,19 +1301,14 @@ func (bot *CQBot) CQGetStatus() MSG {
// CQSetEssenceMessage 扩展API-设置精华消息 // CQSetEssenceMessage 扩展API-设置精华消息
// //
// https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF // https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF
func (bot *CQBot) CQSetEssenceMessage(messageID int32) MSG { func (bot *CQBot) CQSetEssenceMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg, err := bot.db.GetGroupMessageByGlobalID(messageID)
if msg == nil { if err != nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
} }
if _, ok := msg["group"]; ok { if err := bot.Client.SetEssenceMessage(msg.GroupCode, msg.Attribute.MessageSeq, msg.Attribute.InternalID); err != nil {
if err := bot.Client.SetEssenceMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil { log.Warnf("设置精华消息 %v 失败: %v", messageID, err)
log.Warnf("设置精华消息 %v 失败: %v", messageID, err) return Failed(100, "SET_ESSENCE_MSG_ERROR", err.Error())
return Failed(100, "SET_ESSENCE_MSG_ERROR", err.Error())
}
} else {
log.Warnf("设置精华消息 %v 失败: 非群聊", messageID)
return Failed(100, "SET_ESSENCE_MSG_ERROR", "非群聊")
} }
return OK(nil) return OK(nil)
} }
@ -1327,19 +1316,14 @@ func (bot *CQBot) CQSetEssenceMessage(messageID int32) MSG {
// CQDeleteEssenceMessage 扩展API-移出精华消息 // CQDeleteEssenceMessage 扩展API-移出精华消息
// //
// https://docs.go-cqhttp.org/api/#%E7%A7%BB%E5%87%BA%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF // https://docs.go-cqhttp.org/api/#%E7%A7%BB%E5%87%BA%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF
func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) MSG { func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) global.MSG {
msg := bot.GetMessage(messageID) msg, err := bot.db.GetGroupMessageByGlobalID(messageID)
if msg == nil { if err != nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在") return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
} }
if _, ok := msg["group"]; ok { if err := bot.Client.DeleteEssenceMessage(msg.GroupCode, msg.Attribute.MessageSeq, msg.Attribute.InternalID); err != nil {
if err := bot.Client.DeleteEssenceMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil { log.Warnf("删除精华消息 %v 失败: %v", messageID, err)
log.Warnf("移出精华消息 %v 失败: %v", messageID, err) return Failed(100, "SET_ESSENCE_MSG_ERROR", err.Error())
return Failed(100, "DEL_ESSENCE_MSG_ERROR", err.Error())
}
} else {
log.Warnf("移出精华消息 %v 失败: 非群聊", messageID)
return Failed(100, "DEL_ESSENCE_MSG_ERROR", "非群聊")
} }
return OK(nil) return OK(nil)
} }
@ -1347,7 +1331,7 @@ func (bot *CQBot) CQDeleteEssenceMessage(messageID int32) MSG {
// CQGetEssenceMessageList 扩展API-获取精华消息列表 // CQGetEssenceMessageList 扩展API-获取精华消息列表
// //
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF%E5%88%97%E8%A1%A8 // https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%B2%BE%E5%8D%8E%E6%B6%88%E6%81%AF%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG { func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) global.MSG {
g := bot.Client.FindGroup(groupCode) g := bot.Client.FindGroup(groupCode)
if g == nil { if g == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在") return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
@ -1356,9 +1340,9 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
if err != nil { if err != nil {
return Failed(100, "GET_ESSENCE_LIST_FOUND", err.Error()) return Failed(100, "GET_ESSENCE_LIST_FOUND", err.Error())
} }
list := make([]MSG, 0, len(msgList)) list := make([]global.MSG, 0, len(msgList))
for _, m := range msgList { for _, m := range msgList {
msg := MSG{ msg := global.MSG{
"sender_nick": m.SenderNick, "sender_nick": m.SenderNick,
"sender_time": m.SenderTime, "sender_time": m.SenderTime,
"operator_time": m.AddDigestTime, "operator_time": m.AddDigestTime,
@ -1366,7 +1350,7 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
"sender_id": m.SenderUin, "sender_id": m.SenderUin,
"operator_id": m.AddDigestUin, "operator_id": m.AddDigestUin,
} }
msg["message_id"] = toGlobalID(groupCode, int32(m.MessageID)) msg["message_id"] = db.ToGlobalID(groupCode, int32(m.MessageID))
list = append(list, msg) list = append(list, msg)
} }
return OK(list) return OK(list)
@ -1375,8 +1359,8 @@ func (bot *CQBot) CQGetEssenceMessageList(groupCode int64) MSG {
// CQCheckURLSafely 扩展API-检查链接安全性 // CQCheckURLSafely 扩展API-检查链接安全性
// //
// https://docs.go-cqhttp.org/api/#%E6%A3%80%E6%9F%A5%E9%93%BE%E6%8E%A5%E5%AE%89%E5%85%A8%E6%80%A7 // https://docs.go-cqhttp.org/api/#%E6%A3%80%E6%9F%A5%E9%93%BE%E6%8E%A5%E5%AE%89%E5%85%A8%E6%80%A7
func (bot *CQBot) CQCheckURLSafely(url string) MSG { func (bot *CQBot) CQCheckURLSafely(url string) global.MSG {
return OK(MSG{ return OK(global.MSG{
"level": bot.Client.CheckUrlSafely(url), "level": bot.Client.CheckUrlSafely(url),
}) })
} }
@ -1384,12 +1368,12 @@ func (bot *CQBot) CQCheckURLSafely(url string) MSG {
// CQGetVersionInfo 获取版本信息 // CQGetVersionInfo 获取版本信息
// //
// https://git.io/JtwUs // https://git.io/JtwUs
func (bot *CQBot) CQGetVersionInfo() MSG { func (bot *CQBot) CQGetVersionInfo() global.MSG {
wd, _ := os.Getwd() wd, _ := os.Getwd()
return OK(MSG{ return OK(global.MSG{
"app_name": "go-cqhttp", "app_name": "go-cqhttp",
"app_version": Version, "app_version": base.Version,
"app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", Version, runtime.GOOS, runtime.GOARCH, runtime.Version()), "app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", base.Version, runtime.GOOS, runtime.GOARCH, runtime.Version()),
"protocol_version": "v11", "protocol_version": "v11",
"coolq_directory": wd, "coolq_directory": wd,
"coolq_edition": "pro", "coolq_edition": "pro",
@ -1399,7 +1383,7 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
"plugin_build_configuration": "release", "plugin_build_configuration": "release",
"runtime_version": runtime.Version(), "runtime_version": runtime.Version(),
"runtime_os": runtime.GOOS, "runtime_os": runtime.GOOS,
"version": Version, "version": base.Version,
"protocol": func() int { "protocol": func() int {
switch client.SystemDeviceInfo.Protocol { switch client.SystemDeviceInfo.Protocol {
case client.IPad: case client.IPad:
@ -1422,19 +1406,19 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
// CQGetModelShow 获取在线机型 // CQGetModelShow 获取在线机型
// //
// https://club.vip.qq.com/onlinestatus/set // https://club.vip.qq.com/onlinestatus/set
func (bot *CQBot) CQGetModelShow(modelName string) MSG { func (bot *CQBot) CQGetModelShow(modelName string) global.MSG {
variants, err := bot.Client.GetModelShow(modelName) variants, err := bot.Client.GetModelShow(modelName)
if err != nil { if err != nil {
return Failed(100, "GET_MODEL_SHOW_API_ERROR", "无法获取在线机型") return Failed(100, "GET_MODEL_SHOW_API_ERROR", "无法获取在线机型")
} }
a := make([]MSG, 0, len(variants)) a := make([]global.MSG, 0, len(variants))
for _, v := range variants { for _, v := range variants {
a = append(a, MSG{ a = append(a, global.MSG{
"model_show": v.ModelShow, "model_show": v.ModelShow,
"need_pay": v.NeedPay, "need_pay": v.NeedPay,
}) })
} }
return OK(MSG{ return OK(global.MSG{
"variants": a, "variants": a,
}) })
} }
@ -1442,7 +1426,7 @@ func (bot *CQBot) CQGetModelShow(modelName string) MSG {
// CQSetModelShow 设置在线机型 // CQSetModelShow 设置在线机型
// //
// https://club.vip.qq.com/onlinestatus/set // https://club.vip.qq.com/onlinestatus/set
func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) MSG { func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) global.MSG {
err := bot.Client.SetModelShow(modelName, modelShow) err := bot.Client.SetModelShow(modelName, modelShow)
if err != nil { if err != nil {
return Failed(100, "SET_MODEL_SHOW_API_ERROR", "无法设置在线机型") return Failed(100, "SET_MODEL_SHOW_API_ERROR", "无法设置在线机型")
@ -1451,29 +1435,28 @@ func (bot *CQBot) CQSetModelShow(modelName string, modelShow string) MSG {
} }
// CQMarkMessageAsRead 标记消息已读 // CQMarkMessageAsRead 标记消息已读
func (bot *CQBot) CQMarkMessageAsRead(msgID int32) MSG { func (bot *CQBot) CQMarkMessageAsRead(msgID int32) global.MSG {
m := bot.GetMessage(msgID) m, err := bot.db.GetMessageByGlobalID(msgID)
if m == nil { if err != nil {
return Failed(100, "MSG_NOT_FOUND", "消息不存在") return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
if _, ok := m["group"]; ok { switch o := m.(type) {
bot.Client.MarkGroupMessageReaded(m["group"].(int64), int64(m["message-id"].(int32))) case *db.StoredGroupMessage:
bot.Client.MarkGroupMessageReaded(o.GroupCode, int64(o.Attribute.MessageSeq))
return OK(nil) return OK(nil)
case *db.StoredPrivateMessage:
bot.Client.MarkPrivateMessageReaded(o.SessionUin, o.Attribute.Timestamp)
} }
if _, ok := m["from-group"]; ok {
return Failed(100, "MSG_TYPE_ERROR", "不支持标记临时会话")
}
bot.Client.MarkPrivateMessageReaded(m["sender"].(message.Sender).Uin, int64(m["time"].(int32)))
return OK(nil) return OK(nil)
} }
// OK 生成成功返回值 // OK 生成成功返回值
func OK(data interface{}) MSG { func OK(data interface{}) global.MSG {
return MSG{"data": data, "retcode": 0, "status": "ok"} return global.MSG{"data": data, "retcode": 0, "status": "ok"}
} }
// Failed 生成失败返回值 // Failed 生成失败返回值
func Failed(code int, msg ...string) MSG { func Failed(code int, msg ...string) global.MSG {
m := "" m := ""
w := "" w := ""
if len(msg) > 0 { if len(msg) > 0 {
@ -1482,11 +1465,11 @@ func Failed(code int, msg ...string) MSG {
if len(msg) > 1 { if len(msg) > 1 {
w = msg[1] w = msg[1]
} }
return MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"} return global.MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"}
} }
func convertGroupMemberInfo(groupID int64, m *client.GroupMemberInfo) MSG { func convertGroupMemberInfo(groupID int64, m *client.GroupMemberInfo) global.MSG {
return MSG{ return global.MSG{
"group_id": groupID, "group_id": groupID,
"user_id": m.Uin, "user_id": m.Uin,
"nickname": m.Nickname, "nickname": m.Nickname,

View File

@ -2,11 +2,9 @@ package coolq
import ( import (
"bytes" "bytes"
"encoding/gob"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"hash/crc32"
"io" "io"
"os" "os"
"path" "path"
@ -14,7 +12,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/gabriel-vasile/mimetype" "github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
@ -22,11 +20,10 @@ import (
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/pkg/errors" "github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
// CQBot CQBot结构体,存储Bot实例相关配置 // CQBot CQBot结构体,存储Bot实例相关配置
@ -36,17 +33,14 @@ type CQBot struct {
lock sync.RWMutex lock sync.RWMutex
events []func(*Event) events []func(*Event)
db *leveldb.DB db db.IDatabase
friendReqCache sync.Map friendReqCache sync.Map
tempSessionCache sync.Map tempSessionCache sync.Map
} }
// MSG 消息Map
type MSG map[string]interface{}
// Event 事件 // Event 事件
type Event struct { type Event struct {
RawMsg MSG RawMsg global.MSG
once sync.Once once sync.Once
buffer *bytes.Buffer buffer *bytes.Buffer
@ -72,64 +66,38 @@ func (e *Event) JSONString() string {
return utils.B2S(e.buffer.Bytes()) return utils.B2S(e.buffer.Bytes())
} }
// ForceFragmented 是否启用强制分片
var ForceFragmented = false
// SkipMimeScan 是否跳过Mime扫描
var SkipMimeScan bool
// keep sync with /docs/file.md#MINE
var lawfulImageTypes = [...]string{
"image/bmp",
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
}
var lawfulAudioTypes = [...]string{
"audio/aac",
"audio/aiff",
"audio/amr",
"audio/ape",
"audio/flac",
"audio/midi",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/x-m4a",
}
// NewQQBot 初始化一个QQBot实例 // NewQQBot 初始化一个QQBot实例
func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot { func NewQQBot(cli *client.QQClient) *CQBot {
bot := &CQBot{ bot := &CQBot{
Client: cli, Client: cli,
} }
enableLevelDB := false levelNode, levelDB := base.Database["leveldb"]
node, ok := conf.Database["leveldb"] mongoNode, mongoDB := base.Database["mongodb"]
if ok { multiDB := db.NewMultiDatabase()
if levelDB {
lconf := new(config.LevelDBConfig) lconf := new(config.LevelDBConfig)
_ = node.Decode(lconf) _ = levelNode.Decode(lconf)
enableLevelDB = lconf.Enable if lconf.Enable {
} multiDB.UseDB(db.UseLevelDB())
if enableLevelDB {
p := path.Join("data", "leveldb")
db, err := leveldb.OpenFile(p, &opt.Options{
WriteBuffer: 128 * opt.KiB,
})
if err != nil {
log.Fatalf("打开数据库失败, 如果频繁遇到此问题请清理 data/leveldb 文件夹或关闭数据库功能。")
} }
bot.db = db
gob.Register(message.Sender{})
log.Info("信息数据库初始化完成.")
} else {
log.Warn("警告: 信息数据库已关闭,将无法使用 [回复/撤回] 等功能。")
} }
if mongoDB {
lconf := new(config.MongoDBConfig)
_ = mongoNode.Decode(lconf)
if lconf.Database == "" {
lconf.Database = "gocq-database"
}
if lconf.Enable {
multiDB.UseDB(db.UseMongoDB(lconf.URI, lconf.Database))
}
}
if err := multiDB.Open(); err != nil {
log.Fatalf("打开数据库失败: %v", err)
}
bot.db = multiDB
bot.Client.OnPrivateMessage(bot.privateMessageEvent) bot.Client.OnPrivateMessage(bot.privateMessageEvent)
bot.Client.OnGroupMessage(bot.groupMessageEvent) bot.Client.OnGroupMessage(bot.groupMessageEvent)
if conf.Message.ReportSelfMessage { if base.ReportSelfMessage {
bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent) bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent)
bot.Client.OnSelfGroupMessage(bot.groupMessageEvent) bot.Client.OnSelfGroupMessage(bot.groupMessageEvent)
} }
@ -154,24 +122,20 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent) bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent)
bot.Client.OnGroupDigest(bot.groupEssenceMsg) bot.Client.OnGroupDigest(bot.groupEssenceMsg)
go func() { go func() {
i := conf.Heartbeat.Interval if base.HeartbeatInterval == 0 {
if i < 0 || conf.Heartbeat.Disabled {
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。") log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
return return
} }
if i == 0 { t := time.NewTicker(base.HeartbeatInterval)
i = 5
}
t := time.NewTicker(time.Second * time.Duration(i))
for { for {
<-t.C <-t.C
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"time": time.Now().Unix(), "time": time.Now().Unix(),
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"post_type": "meta_event", "post_type": "meta_event",
"meta_event_type": "heartbeat", "meta_event_type": "heartbeat",
"status": bot.CQGetStatus()["data"], "status": bot.CQGetStatus()["data"],
"interval": 1000 * i, "interval": base.HeartbeatInterval.Milliseconds(),
}) })
} }
}() }()
@ -185,22 +149,6 @@ func (bot *CQBot) OnEventPush(f func(e *Event)) {
bot.lock.Unlock() bot.lock.Unlock()
} }
// GetMessage 获取给定消息id对应的消息
func (bot *CQBot) GetMessage(mid int32) MSG {
if bot.db != nil {
m := MSG{}
data, err := bot.db.Get(binary.ToBytes(mid), nil)
if err == nil {
err = gob.NewDecoder(bytes.NewReader(data)).Decode(&m)
if err == nil {
return m
}
}
log.Warnf("获取信息时出现错误: %v id: %v", err, mid)
}
return nil
}
// UploadLocalImageAsGroup 上传本地图片至群聊 // UploadLocalImageAsGroup 上传本地图片至群聊
func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElement) (i *message.GroupImageElement, err error) { func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElement) (i *message.GroupImageElement, err error) {
if img.File != "" { if img.File != "" {
@ -211,7 +159,7 @@ func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElemen
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
img.Stream = f img.Stream = f
} }
if lawful, mime := IsLawfulImage(img.Stream); !lawful { if lawful, mime := base.IsLawfulImage(img.Stream); !lawful {
return nil, errors.New("image type error: " + mime) return nil, errors.New("image type error: " + mime)
} }
i, err = bot.Client.UploadGroupImage(groupCode, img.Stream) i, err = bot.Client.UploadGroupImage(groupCode, img.Stream)
@ -246,7 +194,7 @@ func (bot *CQBot) UploadLocalImageAsPrivate(userID int64, img *LocalImageElement
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
img.Stream = f img.Stream = f
} }
if lawful, mime := IsLawfulImage(img.Stream); !lawful { if lawful, mime := base.IsLawfulImage(img.Stream); !lawful {
return nil, errors.New("image type error: " + mime) return nil, errors.New("image type error: " + mime)
} }
i, err = bot.Client.UploadPrivateImage(userID, img.Stream) i, err = bot.Client.UploadPrivateImage(userID, img.Stream)
@ -299,7 +247,7 @@ func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int
} }
m.Elements = newElem m.Elements = newElem
bot.checkMedia(newElem) bot.checkMedia(newElem)
ret := bot.Client.SendGroupMessage(groupID, m, ForceFragmented) ret := bot.Client.SendGroupMessage(groupID, m, base.ForceFragmented)
if ret == nil || ret.Id == -1 { if ret == nil || ret.Id == -1 {
log.Warnf("群消息发送失败: 账号可能被风控.") log.Warnf("群消息发送失败: 账号可能被风控.")
return -1 return -1
@ -369,8 +317,9 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
default: default:
if session == nil && groupID != 0 { if session == nil && groupID != 0 {
msg := bot.Client.SendGroupTempMessage(groupID, target, m) msg := bot.Client.SendGroupTempMessage(groupID, target, m)
if msg != nil { if msg != nil { // nolint
id = bot.InsertTempMessage(target, msg) // todo(Mrs4s)
// id = bot.InsertTempMessage(target, msg)
} }
break break
} }
@ -379,8 +328,9 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
log.Errorf("发送临时会话消息失败: %v", err) log.Errorf("发送临时会话消息失败: %v", err)
break break
} }
if msg != nil { if msg != nil { // nolint
id = bot.InsertTempMessage(target, msg) // todo(Mrs4s)
// id = bot.InsertTempMessage(target, msg)
} }
} }
case unidirectionalFriendExists(): // 单向好友 case unidirectionalFriendExists(): // 单向好友
@ -400,60 +350,94 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
// InsertGroupMessage 群聊消息入数据库 // InsertGroupMessage 群聊消息入数据库
func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 { func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
val := MSG{ t := &message.SendingMessage{Elements: m.Elements}
"message-id": m.Id, replyElem := t.FirstOrNil(func(e message.IMessageElement) bool {
"internal-id": m.InternalId, _, ok := e.(*message.ReplyElement)
"group": m.GroupCode, return ok
"group-name": m.GroupName, })
"sender": m.Sender, msg := &db.StoredGroupMessage{
"time": m.Time, ID: encodeMessageID(m.GroupCode, m.Id),
"message": ToStringMessage(m.Elements, m.GroupCode, true), GlobalID: db.ToGlobalID(m.GroupCode, m.Id),
SubType: "normal",
Attribute: &db.StoredMessageAttribute{
MessageSeq: m.Id,
InternalID: m.InternalId,
SenderUin: m.Sender.Uin,
SenderName: m.Sender.DisplayName(),
Timestamp: int64(m.Time),
},
GroupCode: m.GroupCode,
AnonymousID: func() string {
if m.Sender.IsAnonymous() {
return m.Sender.AnonymousInfo.AnonymousId
}
return ""
}(),
Content: ToMessageContent(m.Elements),
} }
id := toGlobalID(m.GroupCode, m.Id) if replyElem != nil {
if bot.db != nil { reply := replyElem.(*message.ReplyElement)
buf := global.NewBuffer() msg.SubType = "quote"
defer global.PutBuffer(buf) msg.QuotedInfo = &db.QuotedInfo{
if err := gob.NewEncoder(buf).Encode(val); err != nil { PrevID: encodeMessageID(m.GroupCode, reply.ReplySeq),
log.Warnf("记录聊天数据时出现错误: %v", err) PrevGlobalID: db.ToGlobalID(m.GroupCode, reply.ReplySeq),
return -1 QuotedContent: ToMessageContent(reply.Elements),
}
if err := bot.db.Put(binary.ToBytes(id), buf.Bytes(), nil); err != nil {
log.Warnf("记录聊天数据时出现错误: %v", err)
return -1
} }
} }
return id if err := bot.db.InsertGroupMessage(msg); err != nil {
log.Warnf("记录聊天数据时出现错误: %v", err)
return -1
}
return msg.GlobalID
} }
// InsertPrivateMessage 私聊消息入数据库 // InsertPrivateMessage 私聊消息入数据库
func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 { func (bot *CQBot) InsertPrivateMessage(m *message.PrivateMessage) int32 {
val := MSG{ t := &message.SendingMessage{Elements: m.Elements}
"message-id": m.Id, replyElem := t.FirstOrNil(func(e message.IMessageElement) bool {
"internal-id": m.InternalId, _, ok := e.(*message.ReplyElement)
"target": m.Target, return ok
"sender": m.Sender, })
"time": m.Time, msg := &db.StoredPrivateMessage{
"message": ToStringMessage(m.Elements, 0, true), ID: encodeMessageID(m.Sender.Uin, m.Id),
GlobalID: db.ToGlobalID(m.Sender.Uin, m.Id),
SubType: "normal",
Attribute: &db.StoredMessageAttribute{
MessageSeq: m.Id,
InternalID: m.InternalId,
SenderUin: m.Sender.Uin,
SenderName: m.Sender.DisplayName(),
Timestamp: int64(m.Time),
},
SessionUin: func() int64 {
if m.Sender.Uin == m.Self {
return m.Target
}
return m.Sender.Uin
}(),
TargetUin: m.Target,
Content: ToMessageContent(m.Elements),
} }
id := toGlobalID(m.Sender.Uin, m.Id) if replyElem != nil {
if bot.db != nil { reply := replyElem.(*message.ReplyElement)
buf := global.NewBuffer() msg.SubType = "quote"
defer global.PutBuffer(buf) msg.QuotedInfo = &db.QuotedInfo{
if err := gob.NewEncoder(buf).Encode(val); err != nil { PrevID: encodeMessageID(reply.Sender, reply.ReplySeq),
log.Warnf("记录聊天数据时出现错误: %v", err) PrevGlobalID: db.ToGlobalID(reply.Sender, reply.ReplySeq),
return -1 QuotedContent: ToMessageContent(m.Elements),
}
if err := bot.db.Put(binary.ToBytes(id), buf.Bytes(), nil); err != nil {
log.Warnf("记录聊天数据时出现错误: %v", err)
return -1
} }
} }
return id if err := bot.db.InsertPrivateMessage(msg); err != nil {
log.Warnf("记录聊天数据时出现错误: %v", err)
return -1
}
return msg.GlobalID
} }
/*
// InsertTempMessage 临时消息入数据库 // InsertTempMessage 临时消息入数据库
func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32 { func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32 {
val := MSG{ val := global.MSG{
"message-id": m.Id, "message-id": m.Id,
// FIXME(InsertTempMessage) InternalId missing // FIXME(InsertTempMessage) InternalId missing
"from-group": m.GroupCode, "from-group": m.GroupCode,
@ -463,7 +447,7 @@ func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32
"time": int32(time.Now().Unix()), "time": int32(time.Now().Unix()),
"message": ToStringMessage(m.Elements, 0, true), "message": ToStringMessage(m.Elements, 0, true),
} }
id := toGlobalID(m.Sender.Uin, m.Id) id := db.ToGlobalID(m.Sender.Uin, m.Id)
if bot.db != nil { if bot.db != nil {
buf := global.NewBuffer() buf := global.NewBuffer()
defer global.PutBuffer(buf) defer global.PutBuffer(buf)
@ -478,20 +462,14 @@ func (bot *CQBot) InsertTempMessage(target int64, m *message.TempMessage) int32
} }
return id return id
} }
*/
// toGlobalID 构建`code`-`msgID`的字符串并返回其CRC32 Checksum的值
func toGlobalID(code int64, msgID int32) int32 {
return int32(crc32.ChecksumIEEE([]byte(fmt.Sprintf("%d-%d", code, msgID))))
}
// Release 释放Bot实例 // Release 释放Bot实例
func (bot *CQBot) Release() { func (bot *CQBot) Release() {
if bot.db != nil {
_ = bot.db.Close()
}
} }
func (bot *CQBot) dispatchEventMessage(m MSG) { func (bot *CQBot) dispatchEventMessage(m global.MSG) {
bot.lock.RLock() bot.lock.RLock()
defer bot.lock.RUnlock() defer bot.lock.RUnlock()
@ -519,9 +497,9 @@ func (bot *CQBot) dispatchEventMessage(m MSG) {
global.PutBuffer(event.buffer) global.PutBuffer(event.buffer)
} }
func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG { func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) global.MSG {
cqm := ToStringMessage(m.Elements, m.GroupCode, true) cqm := ToStringMessage(m.Elements, m.GroupCode, true)
gm := MSG{ gm := global.MSG{
"anonymous": nil, "anonymous": nil,
"font": 0, "font": 0,
"group_id": m.GroupCode, "group_id": m.GroupCode,
@ -536,7 +514,7 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
}(), }(),
"raw_message": cqm, "raw_message": cqm,
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"sender": MSG{ "sender": global.MSG{
"age": 0, "age": 0,
"area": "", "area": "",
"level": "", "level": "",
@ -548,12 +526,12 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
} }
if m.Sender.IsAnonymous() { if m.Sender.IsAnonymous() {
gm["anonymous"] = MSG{ gm["anonymous"] = global.MSG{
"flag": m.Sender.AnonymousInfo.AnonymousId + "|" + m.Sender.AnonymousInfo.AnonymousNick, "flag": m.Sender.AnonymousInfo.AnonymousId + "|" + m.Sender.AnonymousInfo.AnonymousNick,
"id": m.Sender.Uin, "id": m.Sender.Uin,
"name": m.Sender.AnonymousInfo.AnonymousNick, "name": m.Sender.AnonymousInfo.AnonymousNick,
} }
gm["sender"].(MSG)["nickname"] = "匿名消息" gm["sender"].(global.MSG)["nickname"] = "匿名消息"
gm["sub_type"] = "anonymous" gm["sub_type"] = "anonymous"
} else { } else {
group := bot.Client.FindGroup(m.GroupCode) group := bot.Client.FindGroup(m.GroupCode)
@ -571,7 +549,7 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) MSG {
return nil return nil
} }
} }
ms := gm["sender"].(MSG) ms := gm["sender"].(global.MSG)
switch mem.Permission { switch mem.Permission {
case client.Owner: case client.Owner:
ms["role"] = "owner" ms["role"] = "owner"
@ -618,24 +596,10 @@ func (bot *CQBot) uploadMedia(raw message.IMessageElement, target int64, group b
return nil, errors.New("unsupported message element type") return nil, errors.New("unsupported message element type")
} }
// IsLawfulImage 判断给定流是否为合法图片 // encodeMessageID 临时先这样, 暂时用不上
// 返回 是否合法, 实际Mime func encodeMessageID(target int64, seq int32) string {
// 判断后会自动将 Stream Seek 至 0 return hex.EncodeToString(binary.NewWriterF(func(w *binary.Writer) {
func IsLawfulImage(r io.ReadSeeker) (bool, string) { w.WriteUInt64(uint64(target))
if SkipMimeScan { w.WriteUInt32(uint32(seq))
return true, "" }))
}
_, _ = r.Seek(0, io.SeekStart)
defer func() { _, _ = r.Seek(0, io.SeekStart) }()
t, err := mimetype.DetectReader(r)
if err != nil {
log.Debugf("扫描 Mime 时出现问题: %v", err)
return false, ""
}
for _, lt := range lawfulImageTypes {
if t.Is(lt) {
return true, t.String()
}
}
return false, t.String()
} }

View File

@ -20,13 +20,14 @@ import (
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/gabriel-vasile/mimetype"
"github.com/segmentio/asm/base64"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/codec" "github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/cache"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
/* /*
@ -35,18 +36,6 @@ var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`) var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
*/ */
// RemoveReplyAt 是否删除reply后的at
var RemoveReplyAt bool
// ExtraReplyData 是否上报额外reply信息
var ExtraReplyData bool
// IgnoreInvalidCQCode 是否忽略无效CQ码
var IgnoreInvalidCQCode = false
// SplitURL 是否分割URL
var SplitURL = false
const ( const (
maxImageSize = 1024 * 1024 * 30 // 30MB maxImageSize = 1024 * 1024 * 30 // 30MB
maxVideoSize = 1024 * 1024 * 100 // 100MB maxVideoSize = 1024 * 1024 * 100 // 100MB
@ -125,8 +114,8 @@ func (e *PokeElement) Type() message.ElementType {
} }
// ToArrayMessage 将消息元素数组转为MSG数组以用于消息上报 // ToArrayMessage 将消息元素数组转为MSG数组以用于消息上报
func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) { func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []global.MSG) {
r = make([]MSG, 0, len(e)) r = make([]global.MSG, 0, len(e))
m := &message.SendingMessage{Elements: e} m := &message.SendingMessage{Elements: e}
reply := m.FirstOrNil(func(e message.IMessageElement) bool { reply := m.FirstOrNil(func(e message.IMessageElement) bool {
_, ok := e.(*message.ReplyElement) _, ok := e.(*message.ReplyElement)
@ -138,11 +127,11 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
if rid == 0 { if rid == 0 {
rid = replyElem.Sender rid = replyElem.Sender
} }
if ExtraReplyData { if base.ExtraReplyData {
r = append(r, MSG{ r = append(r, global.MSG{
"type": "reply", "type": "reply",
"data": map[string]string{ "data": map[string]string{
"id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10), "id": strconv.FormatInt(int64(db.ToGlobalID(rid, replyElem.ReplySeq)), 10),
"seq": strconv.FormatInt(int64(replyElem.ReplySeq), 10), "seq": strconv.FormatInt(int64(replyElem.ReplySeq), 10),
"qq": strconv.FormatInt(replyElem.Sender, 10), "qq": strconv.FormatInt(replyElem.Sender, 10),
"time": strconv.FormatInt(int64(replyElem.Time), 10), "time": strconv.FormatInt(int64(replyElem.Time), 10),
@ -150,66 +139,66 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
}, },
}) })
} else { } else {
r = append(r, MSG{ r = append(r, global.MSG{
"type": "reply", "type": "reply",
"data": map[string]string{"id": strconv.FormatInt(int64(toGlobalID(rid, replyElem.ReplySeq)), 10)}, "data": map[string]string{"id": strconv.FormatInt(int64(db.ToGlobalID(rid, replyElem.ReplySeq)), 10)},
}) })
} }
} }
for i, elem := range e { for i, elem := range e {
var m MSG var m global.MSG
switch o := elem.(type) { switch o := elem.(type) {
case *message.ReplyElement: case *message.ReplyElement:
if RemoveReplyAt && i+1 < len(e) { if base.RemoveReplyAt && i+1 < len(e) {
elem, ok := e[i+1].(*message.AtElement) elem, ok := e[i+1].(*message.AtElement)
if ok && elem.Target == o.Sender { if ok && elem.Target == o.Sender {
e[i+1] = nil e[i+1] = nil
} }
} }
case *message.TextElement: case *message.TextElement:
m = MSG{ m = global.MSG{
"type": "text", "type": "text",
"data": map[string]string{"text": o.Content}, "data": map[string]string{"text": o.Content},
} }
case *message.LightAppElement: case *message.LightAppElement:
m = MSG{ m = global.MSG{
"type": "json", "type": "json",
"data": map[string]string{"data": o.Content}, "data": map[string]string{"data": o.Content},
} }
case *message.AtElement: case *message.AtElement:
if o.Target == 0 { if o.Target == 0 {
m = MSG{ m = global.MSG{
"type": "at", "type": "at",
"data": map[string]string{"qq": "all"}, "data": map[string]string{"qq": "all"},
} }
} else { } else {
m = MSG{ m = global.MSG{
"type": "at", "type": "at",
"data": map[string]string{"qq": strconv.FormatInt(o.Target, 10)}, "data": map[string]string{"qq": strconv.FormatInt(o.Target, 10)},
} }
} }
case *message.RedBagElement: case *message.RedBagElement:
m = MSG{ m = global.MSG{
"type": "redbag", "type": "redbag",
"data": map[string]string{"title": o.Title}, "data": map[string]string{"title": o.Title},
} }
case *message.ForwardElement: case *message.ForwardElement:
m = MSG{ m = global.MSG{
"type": "forward", "type": "forward",
"data": map[string]string{"id": o.ResId}, "data": map[string]string{"id": o.ResId},
} }
case *message.FaceElement: case *message.FaceElement:
m = MSG{ m = global.MSG{
"type": "face", "type": "face",
"data": map[string]string{"id": strconv.FormatInt(int64(o.Index), 10)}, "data": map[string]string{"id": strconv.FormatInt(int64(o.Index), 10)},
} }
case *message.VoiceElement: case *message.VoiceElement:
m = MSG{ m = global.MSG{
"type": "record", "type": "record",
"data": map[string]string{"file": o.Name, "url": o.Url}, "data": map[string]string{"file": o.Name, "url": o.Url},
} }
case *message.ShortVideoElement: case *message.ShortVideoElement:
m = MSG{ m = global.MSG{
"type": "video", "type": "video",
"data": map[string]string{"file": o.Name, "url": o.Url}, "data": map[string]string{"file": o.Name, "url": o.Url},
} }
@ -222,7 +211,7 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
data["type"] = "show" data["type"] = "show"
data["id"] = strconv.FormatInt(int64(o.EffectID), 10) data["id"] = strconv.FormatInt(int64(o.EffectID), 10)
} }
m = MSG{ m = global.MSG{
"type": "image", "type": "image",
"data": data, "data": data,
} }
@ -231,18 +220,18 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []MSG) {
if o.Flash { if o.Flash {
data["type"] = "flash" data["type"] = "flash"
} }
m = MSG{ m = global.MSG{
"type": "image", "type": "image",
"data": data, "data": data,
} }
case *message.ServiceElement: case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk { if isOk := strings.Contains(o.Content, "<?xml"); isOk {
m = MSG{ m = global.MSG{
"type": "xml", "type": "xml",
"data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)}, "data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)},
} }
} else { } else {
m = MSG{ m = global.MSG{
"type": "json", "type": "json",
"data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)}, "data": map[string]string{"data": o.Content, "resid": strconv.FormatInt(int64(o.Id), 10)},
} }
@ -280,19 +269,19 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
if rid == 0 { if rid == 0 {
rid = replyElem.Sender rid = replyElem.Sender
} }
if ExtraReplyData { if base.ExtraReplyData {
write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]", write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]",
toGlobalID(rid, replyElem.ReplySeq), db.ToGlobalID(rid, replyElem.ReplySeq),
replyElem.ReplySeq, replyElem.Sender, replyElem.Time, replyElem.ReplySeq, replyElem.Sender, replyElem.Time,
CQCodeEscapeValue(ToStringMessage(replyElem.Elements, groupID))) CQCodeEscapeValue(ToStringMessage(replyElem.Elements, groupID)))
} else { } else {
write("[CQ:reply,id=%d]", toGlobalID(rid, replyElem.ReplySeq)) write("[CQ:reply,id=%d]", db.ToGlobalID(rid, replyElem.ReplySeq))
} }
} }
for i, elem := range e { for i, elem := range e {
switch o := elem.(type) { switch o := elem.(type) {
case *message.ReplyElement: case *message.ReplyElement:
if RemoveReplyAt && len(e) > i+1 { if base.RemoveReplyAt && len(e) > i+1 {
elem, ok := e[i+1].(*message.AtElement) elem, ok := e[i+1].(*message.AtElement)
if ok && elem.Target == o.Sender { if ok && elem.Target == o.Sender {
e[i+1] = nil e[i+1] = nil
@ -362,6 +351,110 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
return return
} }
// ToMessageContent 将消息转换成 Content. 忽略 Reply
// 不同于 onebot 的 Array Message, 此函数转换出来的 Content 的 data 段为实际类型
// 方便数据库查询
func ToMessageContent(e []message.IMessageElement) (r []global.MSG) {
for _, elem := range e {
var m global.MSG
switch o := elem.(type) {
case *message.TextElement:
m = global.MSG{
"type": "text",
"data": global.MSG{"text": o.Content},
}
case *message.LightAppElement:
m = global.MSG{
"type": "json",
"data": global.MSG{"data": o.Content},
}
case *message.AtElement:
if o.Target == 0 {
m = global.MSG{
"type": "at",
"data": global.MSG{
"subType": "all",
},
}
} else {
m = global.MSG{
"type": "at",
"data": global.MSG{
"subType": "user",
"target": o.Target,
"display": o.Display,
},
}
}
case *message.RedBagElement:
m = global.MSG{
"type": "redbag",
"data": global.MSG{"title": o.Title, "type": o.MsgType},
}
case *message.ForwardElement:
m = global.MSG{
"type": "forward",
"data": global.MSG{"id": o.ResId},
}
case *message.FaceElement:
m = global.MSG{
"type": "face",
"data": global.MSG{"id": o.Index},
}
case *message.VoiceElement:
m = global.MSG{
"type": "record",
"data": global.MSG{"file": o.Name, "url": o.Url},
}
case *message.ShortVideoElement:
m = global.MSG{
"type": "video",
"data": global.MSG{"file": o.Name, "url": o.Url},
}
case *message.GroupImageElement:
data := global.MSG{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url, "subType": uint32(o.ImageBizType)}
switch {
case o.Flash:
data["type"] = "flash"
case o.EffectID != 0:
data["type"] = "show"
data["id"] = o.EffectID
}
m = global.MSG{
"type": "image",
"data": data,
}
case *message.FriendImageElement:
data := global.MSG{"file": hex.EncodeToString(o.Md5) + ".image", "url": o.Url}
if o.Flash {
data["type"] = "flash"
}
m = global.MSG{
"type": "image",
"data": data,
}
case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk {
m = global.MSG{
"type": "xml",
"data": global.MSG{"data": o.Content, "resid": o.Id},
}
} else {
m = global.MSG{
"type": "json",
"data": global.MSG{"data": o.Content, "resid": o.Id},
}
}
default:
continue
}
if m != nil {
r = append(r, m)
}
}
return
}
// ConvertStringMessage 将消息字符串转为消息元素数组 // ConvertStringMessage 将消息字符串转为消息元素数组
func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IMessageElement) { func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IMessageElement) {
var t, key string var t, key string
@ -380,7 +473,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
switch { switch {
case customText != "": case customText != "":
var elem *message.ReplyElement var elem *message.ReplyElement
var org MSG var org db.IStoredMessage
sender, senderErr := strconv.ParseInt(d["qq"], 10, 64) sender, senderErr := strconv.ParseInt(d["qq"], 10, 64)
if senderErr != nil && err != nil { if senderErr != nil && err != nil {
log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id") log.Warnf("警告: 自定义 Reply 元素中必须包含 Uin 或 id")
@ -392,13 +485,13 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
} }
messageSeq, seqErr := strconv.ParseInt(d["seq"], 10, 64) messageSeq, seqErr := strconv.ParseInt(d["seq"], 10, 64)
if err == nil { if err == nil {
org = bot.GetMessage(int32(mid)) org, _ = bot.db.GetMessageByGlobalID(int32(mid))
} }
if org != nil { if org != nil {
elem = &message.ReplyElement{ elem = &message.ReplyElement{
ReplySeq: org["message-id"].(int32), ReplySeq: org.GetAttribute().MessageSeq,
Sender: org["sender"].(message.Sender).Uin, Sender: org.GetAttribute().SenderUin,
Time: org["time"].(int32), Time: int32(org.GetAttribute().Timestamp),
Elements: bot.ConvertStringMessage(customText, isGroup), Elements: bot.ConvertStringMessage(customText, isGroup),
} }
if senderErr != nil { if senderErr != nil {
@ -420,14 +513,14 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
} }
r = append([]message.IMessageElement{elem}, r...) r = append([]message.IMessageElement{elem}, r...)
case err == nil: case err == nil:
org := bot.GetMessage(int32(mid)) org, err := bot.db.GetMessageByGlobalID(int32(mid))
if org != nil { if err == nil {
r = append([]message.IMessageElement{ r = append([]message.IMessageElement{
&message.ReplyElement{ &message.ReplyElement{
ReplySeq: org["message-id"].(int32), ReplySeq: org.GetAttribute().MessageSeq,
Sender: org["sender"].(message.Sender).Uin, Sender: org.GetAttribute().SenderUin,
Time: org["time"].(int32), Time: int32(org.GetAttribute().Timestamp),
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup), Elements: bot.ConvertContentMessage(org.GetContent(), isGroup),
}, },
}, r...) }, r...)
} }
@ -455,7 +548,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
org += "," + k + "=" + v org += "," + k + "=" + v
} }
org += "]" org += "]"
if !IgnoreInvalidCQCode { if !base.IgnoreInvalidCQCode {
log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err)
r = append(r, message.NewText(org)) r = append(r, message.NewText(org))
} else { } else {
@ -477,8 +570,8 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
i++ i++
} }
if i > 0 { if i > 0 {
if SplitURL { if base.SplitURL {
for _, txt := range global.SplitURL(CQCodeUnescapeText(raw[:i])) { for _, txt := range param.SplitURL(CQCodeUnescapeText(raw[:i])) {
r = append(r, message.NewText(txt)) r = append(r, message.NewText(txt))
} }
} else { } else {
@ -552,7 +645,7 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
switch { switch {
case customText != "": case customText != "":
var elem *message.ReplyElement var elem *message.ReplyElement
var org MSG var org db.IStoredMessage
sender, senderErr := strconv.ParseInt(e.Get("data.[user_id,qq]").String(), 10, 64) sender, senderErr := strconv.ParseInt(e.Get("data.[user_id,qq]").String(), 10, 64)
if senderErr != nil && err != nil { if senderErr != nil && err != nil {
log.Warnf("警告: 自定义 Reply 元素中必须包含 user_id 或 id") log.Warnf("警告: 自定义 Reply 元素中必须包含 user_id 或 id")
@ -564,13 +657,13 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
} }
messageSeq, seqErr := strconv.ParseInt(e.Get("data.seq").String(), 10, 64) messageSeq, seqErr := strconv.ParseInt(e.Get("data.seq").String(), 10, 64)
if err == nil { if err == nil {
org = bot.GetMessage(int32(mid)) org, _ = bot.db.GetMessageByGlobalID(int32(mid))
} }
if org != nil { if org != nil {
elem = &message.ReplyElement{ elem = &message.ReplyElement{
ReplySeq: org["message-id"].(int32), ReplySeq: org.GetAttribute().MessageSeq,
Sender: org["sender"].(message.Sender).Uin, Sender: org.GetAttribute().SenderUin,
Time: org["time"].(int32), Time: int32(org.GetAttribute().Timestamp),
Elements: bot.ConvertStringMessage(customText, isGroup), Elements: bot.ConvertStringMessage(customText, isGroup),
} }
if senderErr != nil { if senderErr != nil {
@ -592,14 +685,14 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
} }
r = append([]message.IMessageElement{elem}, r...) r = append([]message.IMessageElement{elem}, r...)
case err == nil: case err == nil:
org := bot.GetMessage(int32(mid)) org, err := bot.db.GetMessageByGlobalID(int32(mid))
if org != nil { if err == nil {
r = append([]message.IMessageElement{ r = append([]message.IMessageElement{
&message.ReplyElement{ &message.ReplyElement{
ReplySeq: org["message-id"].(int32), ReplySeq: org.GetAttribute().MessageSeq,
Sender: org["sender"].(message.Sender).Uin, Sender: org.GetAttribute().SenderUin,
Time: org["time"].(int32), Time: int32(org.GetAttribute().Timestamp),
Elements: bot.ConvertStringMessage(org["message"].(string), isGroup), Elements: bot.ConvertContentMessage(org.GetContent(), isGroup),
}, },
}, r...) }, r...)
} }
@ -655,6 +748,75 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
return return
} }
// ConvertContentMessage 将数据库用的 content 转换为消息元素数组
func (bot *CQBot) ConvertContentMessage(content []global.MSG, group bool) (r []message.IMessageElement) {
for _, c := range content {
data := c["data"].(global.MSG)
switch c["type"] {
case "text":
r = append(r, message.NewText(data["text"].(string)))
case "image":
e, err := bot.makeImageOrVideoElem(map[string]string{"file": data["file"].(string)}, false, group)
if err != nil {
log.Warnf("make image elem error: %v", err)
continue
}
flash, id := false, int32(0)
if t, ok := data["type"]; ok {
if t.(string) == "flash" {
flash = true
}
if t.(string) == "show" {
id = data["id"].(int32)
if id < 40000 || id >= 40006 {
id = 40000
}
}
}
switch img := e.(type) {
case *LocalImageElement:
img.Flash = flash
img.EffectID = id
case *message.GroupImageElement:
img.Flash = flash
img.EffectID = id
img.ImageBizType = message.ImageBizType(data["subType"].(uint32))
case *message.FriendImageElement:
img.Flash = flash
}
r = append(r, e)
case "at":
switch data["subType"].(string) {
case "all":
r = append(r, message.NewAt(0))
case "user":
r = append(r, message.NewAt(data["target"].(int64), data["display"].(string)))
default:
continue
}
case "redbag":
r = append(r, &message.RedBagElement{
MsgType: message.RedBagMessageType(data["type"].(int)),
Title: data["title"].(string),
})
case "forward":
r = append(r, &message.ForwardElement{
ResId: data["id"].(string),
})
case "face":
r = append(r, message.NewFace(data["id"].(int32)))
case "video":
e, err := bot.makeImageOrVideoElem(map[string]string{"file": data["file"].(string)}, true, group)
if err != nil {
log.Warnf("make image elem error: %v", err)
continue
}
r = append(r, e)
}
}
return
}
// ToElement 将解码后的CQCode转换为Element. // ToElement 将解码后的CQCode转换为Element.
// //
// 返回 interface{} 存在三种类型 // 返回 interface{} 存在三种类型
@ -663,9 +825,9 @@ func (bot *CQBot) ConvertObjectMessage(m gjson.Result, isGroup bool) (r []messag
func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m interface{}, err error) { func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m interface{}, err error) {
switch t { switch t {
case "text": case "text":
if SplitURL { if base.SplitURL {
var ret []message.IMessageElement var ret []message.IMessageElement
for _, text := range global.SplitURL(d["text"]) { for _, text := range param.SplitURL(d["text"]) {
ret = append(ret, message.NewText(text)) ret = append(ret, message.NewText(text))
} }
return ret, nil return ret, nil
@ -726,7 +888,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &message.VoiceElement{Data: codec.RecodeTo24K(data)}, nil return &message.VoiceElement{Data: base.ResampleSilk(data)}, nil
case "record": case "record":
f := d["file"] f := d["file"]
data, err := global.FindFile(f, d["cache"], global.VoicePath) data, err := global.FindFile(f, d["cache"], global.VoicePath)
@ -736,17 +898,10 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !SkipMimeScan && !global.IsAMRorSILK(data) { if !global.IsAMRorSILK(data) {
mt := mimetype.Detect(data) lawful, mt := base.IsLawfulAudio(bytes.NewReader(data))
lawful := false
for _, lt := range lawfulAudioTypes {
if mt.Is(lt) {
lawful = true
break
}
}
if !lawful { if !lawful {
return nil, errors.New("audio type error: " + mt.String()) return nil, errors.New("audio type error: " + mt)
} }
} }
if !global.IsAMRorSILK(data) { if !global.IsAMRorSILK(data) {
@ -1118,7 +1273,7 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
return &LocalImageElement{File: fu.Path}, nil return &LocalImageElement{File: fu.Path}, nil
} }
if strings.HasPrefix(f, "base64") && !video { if strings.HasPrefix(f, "base64") && !video {
b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(f, "base64://")) b, err := param.Base64DecodeString(strings.TrimPrefix(f, "base64://"))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1126,23 +1281,31 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
} }
rawPath := path.Join(global.ImagePath, f) rawPath := path.Join(global.ImagePath, f)
if video { if video {
if strings.HasSuffix(f, ".video") && cache.EnableCacheDB {
hash, err := hex.DecodeString(strings.TrimSuffix(f, ".video"))
if err == nil {
if b := cache.Video.Get(hash); b != nil {
return bot.readVideoCache(b), nil
}
}
}
rawPath = path.Join(global.VideoPath, f) rawPath = path.Join(global.VideoPath, f)
if !global.PathExists(rawPath) { if !global.PathExists(rawPath) {
return nil, errors.New("invalid video") return nil, errors.New("invalid video")
} }
if path.Ext(rawPath) == ".video" { if path.Ext(rawPath) != ".video" {
b, _ := os.ReadFile(rawPath) return &LocalVideoElement{File: rawPath}, nil
r := binary.NewReader(b) }
return &message.ShortVideoElement{ // todo 检查缓存是否有效 b, _ := os.ReadFile(rawPath)
Md5: r.ReadBytes(16), return bot.readVideoCache(b), nil
ThumbMd5: r.ReadBytes(16), }
Size: r.ReadInt32(), if strings.HasSuffix(f, ".image") && cache.EnableCacheDB {
ThumbSize: r.ReadInt32(), hash, err := hex.DecodeString(strings.TrimSuffix(f, ".image"))
Name: r.ReadString(), if err == nil {
Uuid: r.ReadAvailable(), if b := cache.Image.Get(hash); b != nil {
}, nil return bot.readImageCache(b, group)
}
} }
return &LocalVideoElement{File: rawPath}, nil
} }
exist := global.PathExists(rawPath) exist := global.PathExists(rawPath)
if !exist && global.PathExists(path.Join(global.ImagePathOld, f)) { if !exist && global.PathExists(path.Join(global.ImagePathOld, f)) {
@ -1162,8 +1325,13 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
if err != nil { if err != nil {
return nil, err return nil, err
} }
return bot.readImageCache(b, group)
}
func (bot *CQBot) readImageCache(b []byte, group bool) (message.IMessageElement, error) {
var err error
if len(b) < 20 { if len(b) < 20 {
return nil, errors.New("invalid local file") return nil, errors.New("invalid cache")
} }
r := binary.NewReader(b) r := binary.NewReader(b)
hash := r.ReadBytes(16) hash := r.ReadBytes(16)
@ -1195,6 +1363,18 @@ ok:
return rsp, nil return rsp, nil
} }
func (bot *CQBot) readVideoCache(b []byte) message.IMessageElement {
r := binary.NewReader(b)
return &message.ShortVideoElement{ // todo 检查缓存是否有效
Md5: r.ReadBytes(16),
ThumbMd5: r.ReadBytes(16),
Size: r.ReadInt32(),
ThumbSize: r.ReadInt32(),
Name: r.ReadString(),
Uuid: r.ReadAvailable(),
}
}
// makeShowPic 一种xml 方式发送的群消息图片 // makeShowPic 一种xml 方式发送的群消息图片
func (bot *CQBot) makeShowPic(elem message.IMessageElement, source string, brief string, icon string, minWidth int64, minHeight int64, maxWidth int64, maxHeight int64, group bool) ([]message.IMessageElement, error) { func (bot *CQBot) makeShowPic(elem message.IMessageElement, source string, brief string, icon string, minWidth int64, minHeight int64, maxWidth int64, maxHeight int64, group bool) ([]message.IMessageElement, error) {
xml := "" xml := ""

View File

@ -41,7 +41,7 @@ const bText = `123456789[]&987654321[]&987654321[]&987654321[]&987654321[]&98765
func BenchmarkCQCodeEscapeText(b *testing.B) { func BenchmarkCQCodeEscapeText(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
ret := bText ret := bText
ret = CQCodeEscapeText(ret) CQCodeEscapeText(ret)
} }
} }
@ -50,7 +50,7 @@ func BenchmarkCQCodeEscapeTextBefore(b *testing.B) {
ret := bText ret := bText
ret = strings.ReplaceAll(ret, "&", "&amp;") ret = strings.ReplaceAll(ret, "&", "&amp;")
ret = strings.ReplaceAll(ret, "[", "&#91;") ret = strings.ReplaceAll(ret, "[", "&#91;")
ret = strings.ReplaceAll(ret, "]", "&#93;") strings.ReplaceAll(ret, "]", "&#93;")
} }
} }

View File

@ -8,7 +8,11 @@ import (
"strings" "strings"
"time" "time"
"github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/go-cqhttp/internal/cache"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
@ -16,18 +20,11 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
var format = "string"
// SetMessageFormat 设置消息上报格式默认为string
func SetMessageFormat(f string) {
format = f
}
// ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式 // ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式
func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...bool) (r interface{}) { func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...bool) (r interface{}) {
if format == "string" { if base.PostFormat == "string" {
r = ToStringMessage(e, groupID, isRaw...) r = ToStringMessage(e, groupID, isRaw...)
} else if format == "array" { } else if base.PostFormat == "array" {
r = ToArrayMessage(e, groupID) r = ToArrayMessage(e, groupID)
} }
return return
@ -41,7 +38,7 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
id = bot.InsertPrivateMessage(m) id = bot.InsertPrivateMessage(m)
} }
log.Infof("收到好友 %v(%v) 的消息: %v (%v)", m.Sender.DisplayName(), m.Sender.Uin, cqm, id) log.Infof("收到好友 %v(%v) 的消息: %v (%v)", m.Sender.DisplayName(), m.Sender.Uin, cqm, id)
fm := MSG{ fm := global.MSG{
"post_type": func() string { "post_type": func() string {
if m.Sender.Uin == bot.Client.Uin { if m.Sender.Uin == bot.Client.Uin {
return "message_sent" return "message_sent"
@ -58,7 +55,7 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
"font": 0, "font": 0,
"self_id": c.Uin, "self_id": c.Uin,
"time": time.Now().Unix(), "time": time.Now().Unix(),
"sender": MSG{ "sender": global.MSG{
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"nickname": m.Sender.Nickname, "nickname": m.Sender.Nickname,
"sex": "unknown", "sex": "unknown",
@ -73,12 +70,12 @@ func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage)
for _, elem := range m.Elements { for _, elem := range m.Elements {
if file, ok := elem.(*message.GroupFileElement); ok { if file, ok := elem.(*message.GroupFileElement); ok {
log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name) log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_upload", "notice_type": "group_upload",
"group_id": m.GroupCode, "group_id": m.GroupCode,
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"file": MSG{ "file": global.MSG{
"id": file.Path, "id": file.Path,
"name": file.Name, "name": file.Name,
"size": file.Size, "size": file.Size,
@ -111,11 +108,12 @@ func (bot *CQBot) tempMessageEvent(c *client.QQClient, e *client.TempMessageEven
cqm := ToStringMessage(m.Elements, 0, true) cqm := ToStringMessage(m.Elements, 0, true)
bot.tempSessionCache.Store(m.Sender.Uin, e.Session) bot.tempSessionCache.Store(m.Sender.Uin, e.Session)
id := m.Id id := m.Id
if bot.db != nil { if bot.db != nil { // nolint
id = bot.InsertTempMessage(m.Sender.Uin, m) // todo(Mrs4s)
// id = bot.InsertTempMessage(m.Sender.Uin, m)
} }
log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm) log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm)
tm := MSG{ tm := global.MSG{
"post_type": "message", "post_type": "message",
"message_type": "private", "message_type": "private",
"sub_type": "group", "sub_type": "group",
@ -127,7 +125,7 @@ func (bot *CQBot) tempMessageEvent(c *client.QQClient, e *client.TempMessageEven
"font": 0, "font": 0,
"self_id": c.Uin, "self_id": c.Uin,
"time": time.Now().Unix(), "time": time.Now().Unix(),
"sender": MSG{ "sender": global.MSG{
"user_id": m.Sender.Uin, "user_id": m.Sender.Uin,
"group_id": m.GroupCode, "group_id": m.GroupCode,
"nickname": m.Sender.Nickname, "nickname": m.Sender.Nickname,
@ -158,7 +156,7 @@ func (bot *CQBot) groupMutedEvent(c *client.QQClient, e *client.GroupMuteEvent)
} }
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"duration": e.Time, "duration": e.Time,
"group_id": e.GroupCode, "group_id": e.GroupCode,
@ -178,10 +176,10 @@ func (bot *CQBot) groupMutedEvent(c *client.QQClient, e *client.GroupMuteEvent)
func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRecalledEvent) { func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRecalledEvent) {
g := c.FindGroup(e.GroupCode) g := c.FindGroup(e.GroupCode)
gid := toGlobalID(e.GroupCode, e.MessageId) gid := db.ToGlobalID(e.GroupCode, e.MessageId)
log.Infof("群 %v 内 %v 撤回了 %v 的消息: %v.", log.Infof("群 %v 内 %v 撤回了 %v 的消息: %v.",
formatGroupName(g), formatMemberName(g.FindMember(e.OperatorUin)), formatMemberName(g.FindMember(e.AuthorUin)), gid) formatGroupName(g), formatMemberName(g.FindMember(e.OperatorUin)), formatMemberName(g.FindMember(e.AuthorUin)), gid)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": e.GroupCode, "group_id": e.GroupCode,
"notice_type": "group_recall", "notice_type": "group_recall",
@ -200,7 +198,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
sender := group.FindMember(notify.Sender) sender := group.FindMember(notify.Sender)
receiver := group.FindMember(notify.Receiver) receiver := group.FindMember(notify.Receiver)
log.Infof("群 %v 内 %v 戳了戳 %v", formatGroupName(group), formatMemberName(sender), formatMemberName(receiver)) log.Infof("群 %v 内 %v 戳了戳 %v", formatGroupName(group), formatMemberName(sender), formatMemberName(receiver))
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -215,7 +213,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
sender := group.FindMember(notify.Sender) sender := group.FindMember(notify.Sender)
luckyKing := group.FindMember(notify.LuckyKing) luckyKing := group.FindMember(notify.LuckyKing)
log.Infof("群 %v 内 %v 的红包被抢完, %v 是运气王", formatGroupName(group), formatMemberName(sender), formatMemberName(luckyKing)) log.Infof("群 %v 内 %v 的红包被抢完, %v 是运气王", formatGroupName(group), formatMemberName(sender), formatMemberName(luckyKing))
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -228,7 +226,7 @@ func (bot *CQBot) groupNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
}) })
case *client.MemberHonorChangedNotifyEvent: case *client.MemberHonorChangedNotifyEvent:
log.Info(notify.Content()) log.Info(notify.Content())
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": group.Code, "group_id": group.Code,
"notice_type": "notify", "notice_type": "notify",
@ -264,7 +262,7 @@ func (bot *CQBot) friendNotifyEvent(c *client.QQClient, e client.INotifyEvent) {
} else { } else {
log.Infof("好友 %v 戳了戳你.", friend.Nickname) log.Infof("好友 %v 戳了戳你.", friend.Nickname)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "notify", "notice_type": "notify",
"sub_type": "poke", "sub_type": "poke",
@ -281,7 +279,7 @@ func (bot *CQBot) memberTitleUpdatedEvent(c *client.QQClient, e *client.MemberSp
group := c.FindGroup(e.GroupCode) group := c.FindGroup(e.GroupCode)
mem := group.FindMember(e.Uin) mem := group.FindMember(e.Uin)
log.Infof("群 %v(%v) 内成员 %v(%v) 获得了新的头衔: %v", group.Name, group.Code, mem.DisplayName(), mem.Uin, e.NewTitle) log.Infof("群 %v(%v) 内成员 %v(%v) 获得了新的头衔: %v", group.Name, group.Code, mem.DisplayName(), mem.Uin, e.NewTitle)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "notify", "notice_type": "notify",
"sub_type": "title", "sub_type": "title",
@ -295,13 +293,13 @@ func (bot *CQBot) memberTitleUpdatedEvent(c *client.QQClient, e *client.MemberSp
func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) { func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) {
f := c.FindFriend(e.FriendUin) f := c.FindFriend(e.FriendUin)
gid := toGlobalID(e.FriendUin, e.MessageId) gid := db.ToGlobalID(e.FriendUin, e.MessageId)
if f != nil { if f != nil {
log.Infof("好友 %v(%v) 撤回了消息: %v", f.Nickname, f.Uin, gid) log.Infof("好友 %v(%v) 撤回了消息: %v", f.Nickname, f.Uin, gid)
} else { } else {
log.Infof("好友 %v 撤回了消息: %v", e.FriendUin, gid) log.Infof("好友 %v 撤回了消息: %v", e.FriendUin, gid)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "friend_recall", "notice_type": "friend_recall",
"self_id": c.Uin, "self_id": c.Uin,
@ -317,11 +315,11 @@ func (bot *CQBot) offlineFileEvent(c *client.QQClient, e *client.OfflineFileEven
return return
} }
log.Infof("好友 %v(%v) 发送了离线文件 %v", f.Nickname, f.Uin, e.FileName) log.Infof("好友 %v(%v) 发送了离线文件 %v", f.Nickname, f.Uin, e.FileName)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "offline_file", "notice_type": "offline_file",
"user_id": e.Sender, "user_id": e.Sender,
"file": MSG{ "file": global.MSG{
"name": e.FileName, "name": e.FileName,
"size": e.FileSize, "size": e.FileSize,
"url": e.DownloadUrl, "url": e.DownloadUrl,
@ -352,7 +350,7 @@ func (bot *CQBot) memberPermissionChangedEvent(c *client.QQClient, e *client.Mem
} }
return "unset" return "unset"
}() }()
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_admin", "notice_type": "group_admin",
"sub_type": st, "sub_type": st,
@ -365,7 +363,7 @@ func (bot *CQBot) memberPermissionChangedEvent(c *client.QQClient, e *client.Mem
func (bot *CQBot) memberCardUpdatedEvent(c *client.QQClient, e *client.MemberCardUpdatedEvent) { func (bot *CQBot) memberCardUpdatedEvent(c *client.QQClient, e *client.MemberCardUpdatedEvent) {
log.Infof("群 %v 的 %v 更新了名片 %v -> %v", formatGroupName(e.Group), formatMemberName(e.Member), e.OldCard, e.Member.CardName) log.Infof("群 %v 的 %v 更新了名片 %v -> %v", formatGroupName(e.Group), formatMemberName(e.Member), e.OldCard, e.Member.CardName)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_card", "notice_type": "group_card",
"group_id": e.Group.Code, "group_id": e.Group.Code,
@ -395,7 +393,7 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
log.Infof("收到来自 %v(%v) 的好友请求: %v", e.RequesterNick, e.RequesterUin, e.Message) log.Infof("收到来自 %v(%v) 的好友请求: %v", e.RequesterNick, e.RequesterUin, e.Message)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.friendReqCache.Store(flag, e) bot.friendReqCache.Store(flag, e)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "friend", "request_type": "friend",
"user_id": e.RequesterUin, "user_id": e.RequesterUin,
@ -409,7 +407,7 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) { func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) {
log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin) log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin)
bot.tempSessionCache.Delete(e.Friend.Uin) bot.tempSessionCache.Delete(e.Friend.Uin)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "friend_add", "notice_type": "friend_add",
"self_id": c.Uin, "self_id": c.Uin,
@ -421,7 +419,7 @@ func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent)
func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) { func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) {
log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin) log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "group", "request_type": "group",
"sub_type": "invite", "sub_type": "invite",
@ -437,7 +435,7 @@ func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRe
func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) { func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) {
log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupCode, e.RequesterNick, e.RequesterUin) log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupCode, e.RequesterNick, e.RequesterUin)
flag := strconv.FormatInt(e.RequestId, 10) flag := strconv.FormatInt(e.RequestId, 10)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "request", "post_type": "request",
"request_type": "group", "request_type": "group",
"sub_type": "add", "sub_type": "add",
@ -456,11 +454,11 @@ func (bot *CQBot) otherClientStatusChangedEvent(c *client.QQClient, e *client.Ot
} else { } else {
log.Infof("Bot 账号在客户端 %v (%v) 登出.", e.Client.DeviceName, e.Client.DeviceKind) log.Infof("Bot 账号在客户端 %v (%v) 登出.", e.Client.DeviceName, e.Client.DeviceKind)
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "client_status", "notice_type": "client_status",
"online": e.Online, "online": e.Online,
"client": MSG{ "client": global.MSG{
"app_id": e.Client.AppId, "app_id": e.Client.AppId,
"device_name": e.Client.DeviceName, "device_name": e.Client.DeviceName,
"device_kind": e.Client.DeviceKind, "device_kind": e.Client.DeviceKind,
@ -472,7 +470,7 @@ func (bot *CQBot) otherClientStatusChangedEvent(c *client.QQClient, e *client.Ot
func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent) { func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent) {
g := c.FindGroup(e.GroupCode) g := c.FindGroup(e.GroupCode)
gid := toGlobalID(e.GroupCode, e.MessageID) gid := db.ToGlobalID(e.GroupCode, e.MessageID)
if e.OperationType == 1 { if e.OperationType == 1 {
log.Infof( log.Infof(
"群 %v 内 %v 将 %v 的消息(%v)设为了精华消息.", "群 %v 内 %v 将 %v 的消息(%v)设为了精华消息.",
@ -493,7 +491,7 @@ func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent
if e.OperatorUin == bot.Client.Uin { if e.OperatorUin == bot.Client.Uin {
return return
} }
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(global.MSG{
"post_type": "notice", "post_type": "notice",
"group_id": e.GroupCode, "group_id": e.GroupCode,
"notice_type": "essence", "notice_type": "essence",
@ -511,8 +509,8 @@ func (bot *CQBot) groupEssenceMsg(c *client.QQClient, e *client.GroupDigestEvent
}) })
} }
func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) MSG { func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) global.MSG {
return MSG{ return global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_increase", "notice_type": "group_increase",
"group_id": groupCode, "group_id": groupCode,
@ -524,8 +522,8 @@ func (bot *CQBot) groupIncrease(groupCode, operatorUin, userUin int64) MSG {
} }
} }
func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.GroupMemberInfo) MSG { func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.GroupMemberInfo) global.MSG {
return MSG{ return global.MSG{
"post_type": "notice", "post_type": "notice",
"notice_type": "group_decrease", "notice_type": "group_decrease",
"group_id": groupCode, "group_id": groupCode,
@ -551,29 +549,37 @@ func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.Group
} }
func (bot *CQBot) checkMedia(e []message.IMessageElement) { func (bot *CQBot) checkMedia(e []message.IMessageElement) {
// TODO(wdvxdr): remove these old cache file in v1.0.0
for _, elem := range e { for _, elem := range e {
switch i := elem.(type) { switch i := elem.(type) {
case *message.GroupImageElement: case *message.GroupImageElement:
data := binary.NewWriterF(func(w *binary.Writer) {
w.Write(i.Md5)
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.ImageId)
w.WriteString(i.Url)
})
filename := hex.EncodeToString(i.Md5) + ".image" filename := hex.EncodeToString(i.Md5) + ".image"
if !global.PathExists(path.Join(global.ImagePath, filename)) { if cache.EnableCacheDB {
_ = os.WriteFile(path.Join(global.ImagePath, filename), binary.NewWriterF(func(w *binary.Writer) { cache.Image.Insert(i.Md5, data)
w.Write(i.Md5) } else if !global.PathExists(path.Join(global.ImagePath, filename)) {
w.WriteUInt32(uint32(i.Size)) _ = os.WriteFile(path.Join(global.ImagePath, filename), data, 0o644)
w.WriteString(i.ImageId)
w.WriteString(i.Url)
}), 0o644)
} }
case *message.FriendImageElement: case *message.FriendImageElement:
data := binary.NewWriterF(func(w *binary.Writer) {
w.Write(i.Md5)
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.ImageId)
w.WriteString(i.Url)
})
filename := hex.EncodeToString(i.Md5) + ".image" filename := hex.EncodeToString(i.Md5) + ".image"
if !global.PathExists(path.Join(global.ImagePath, filename)) { if cache.EnableCacheDB {
_ = os.WriteFile(path.Join(global.ImagePath, filename), binary.NewWriterF(func(w *binary.Writer) { cache.Image.Insert(i.Md5, data)
w.Write(i.Md5) } else if !global.PathExists(path.Join(global.ImagePath, filename)) {
w.WriteUInt32(uint32(i.Size)) _ = os.WriteFile(path.Join(global.ImagePath, filename), data, 0o644)
w.WriteString(i.ImageId)
w.WriteString(i.Url)
}), 0o644)
} }
case *message.VoiceElement: case *message.VoiceElement:
// todo: don't download original file?
i.Name = strings.ReplaceAll(i.Name, "{", "") i.Name = strings.ReplaceAll(i.Name, "{", "")
i.Name = strings.ReplaceAll(i.Name, "}", "") i.Name = strings.ReplaceAll(i.Name, "}", "")
if !global.PathExists(path.Join(global.VoicePath, i.Name)) { if !global.PathExists(path.Join(global.VoicePath, i.Name)) {
@ -585,16 +591,19 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
_ = os.WriteFile(path.Join(global.VoicePath, i.Name), b, 0o644) _ = os.WriteFile(path.Join(global.VoicePath, i.Name), b, 0o644)
} }
case *message.ShortVideoElement: case *message.ShortVideoElement:
data := binary.NewWriterF(func(w *binary.Writer) {
w.Write(i.Md5)
w.Write(i.ThumbMd5)
w.WriteUInt32(uint32(i.Size))
w.WriteUInt32(uint32(i.ThumbSize))
w.WriteString(i.Name)
w.Write(i.Uuid)
})
filename := hex.EncodeToString(i.Md5) + ".video" filename := hex.EncodeToString(i.Md5) + ".video"
if !global.PathExists(path.Join(global.VideoPath, filename)) { if cache.EnableCacheDB {
_ = os.WriteFile(path.Join(global.VideoPath, filename), binary.NewWriterF(func(w *binary.Writer) { cache.Video.Insert(i.Md5, data)
w.Write(i.Md5) } else if !global.PathExists(path.Join(global.VideoPath, filename)) {
w.Write(i.ThumbMd5) _ = os.WriteFile(path.Join(global.VideoPath, filename), data, 0o644)
w.WriteUInt32(uint32(i.Size))
w.WriteUInt32(uint32(i.ThumbSize))
w.WriteString(i.Name)
w.Write(i.Uuid)
}), 0o644)
} }
i.Name = filename i.Name = filename
i.Url = bot.Client.GetShortVideoUrl(i.Uuid, i.Md5) i.Url = bot.Client.GetShortVideoUrl(i.Uuid, i.Md5)

101
db/database.go Normal file
View File

@ -0,0 +1,101 @@
package db
import (
"fmt"
"hash/crc32"
"github.com/Mrs4s/go-cqhttp/global"
)
type (
// IDatabase 数据库操作接口定义
IDatabase interface {
// Open 初始化数据库
Open() error
// GetMessageByGlobalID 通过 GlobalID 来获取消息
GetMessageByGlobalID(int32) (IStoredMessage, error)
// GetGroupMessageByGlobalID 通过 GlobalID 来获取群消息
GetGroupMessageByGlobalID(int32) (*StoredGroupMessage, error)
// GetPrivateMessageByGlobalID 通过 GlobalID 来获取私聊消息
GetPrivateMessageByGlobalID(int32) (*StoredPrivateMessage, error)
// InsertGroupMessage 向数据库写入新的群消息
InsertGroupMessage(*StoredGroupMessage) error
// InsertPrivateMessage 向数据库写入新的私聊消息
InsertPrivateMessage(*StoredPrivateMessage) error
}
IStoredMessage interface {
GetID() string
GetType() string
GetGlobalID() int32
GetAttribute() *StoredMessageAttribute
GetContent() []global.MSG
}
// StoredGroupMessage 持久化群消息
StoredGroupMessage struct {
ID string `bson:"_id"`
GlobalID int32 `bson:"globalId"`
Attribute *StoredMessageAttribute `bson:"attribute"`
SubType string `bson:"subType"`
QuotedInfo *QuotedInfo `bson:"quotedInfo"`
GroupCode int64 `bson:"groupCode"`
AnonymousID string `bson:"anonymousId"`
Content []global.MSG `bson:"content"`
}
// StoredPrivateMessage 持久化私聊消息
StoredPrivateMessage struct {
ID string `bson:"_id"`
GlobalID int32 `bson:"globalId"`
Attribute *StoredMessageAttribute `bson:"attribute"`
SubType string `bson:"subType"`
QuotedInfo *QuotedInfo `bson:"quotedInfo"`
SessionUin int64 `bson:"sessionUin"`
TargetUin int64 `bson:"targetUin"`
Content []global.MSG `bson:"content"`
}
// StoredMessageAttribute 持久化消息属性
StoredMessageAttribute struct {
MessageSeq int32 `bson:"messageSeq"`
InternalID int32 `bson:"internalId"`
SenderUin int64 `bson:"senderUin"`
SenderName string `bson:"senderName"`
Timestamp int64 `bson:"timestamp"`
}
// QuotedInfo 引用回复
QuotedInfo struct {
PrevID string `bson:"prevId"`
PrevGlobalID int32 `bson:"prevGlobalId"`
QuotedContent []global.MSG `bson:"quotedContent"`
}
)
// ToGlobalID 构建`code`-`msgID`的字符串并返回其CRC32 Checksum的值
func ToGlobalID(code int64, msgID int32) int32 {
return int32(crc32.ChecksumIEEE([]byte(fmt.Sprintf("%d-%d", code, msgID))))
}
func (m *StoredGroupMessage) GetID() string { return m.ID }
func (m *StoredGroupMessage) GetType() string { return "group" }
func (m *StoredGroupMessage) GetGlobalID() int32 { return m.GlobalID }
func (m *StoredGroupMessage) GetAttribute() *StoredMessageAttribute { return m.Attribute }
func (m *StoredGroupMessage) GetContent() []global.MSG { return m.Content }
func (m *StoredPrivateMessage) GetID() string { return m.ID }
func (m *StoredPrivateMessage) GetType() string { return "private" }
func (m *StoredPrivateMessage) GetGlobalID() int32 { return m.GlobalID }
func (m *StoredPrivateMessage) GetAttribute() *StoredMessageAttribute { return m.Attribute }
func (m *StoredPrivateMessage) GetContent() []global.MSG { return m.Content }

118
db/leveldb.go Normal file
View File

@ -0,0 +1,118 @@
package db
import (
"bytes"
"encoding/gob"
"path"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/pkg/errors"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/Mrs4s/go-cqhttp/global"
)
type LevelDBImpl struct {
db *leveldb.DB
}
const (
group byte = 0x0
private byte = 0x1
)
func UseLevelDB() *LevelDBImpl {
gob.Register(StoredMessageAttribute{})
gob.Register(QuotedInfo{})
gob.Register(global.MSG{})
gob.Register(StoredGroupMessage{})
gob.Register(StoredPrivateMessage{})
return &LevelDBImpl{}
}
func (db *LevelDBImpl) Open() error {
p := path.Join("data", "leveldb-v2")
d, err := leveldb.OpenFile(p, &opt.Options{
WriteBuffer: 128 * opt.KiB,
})
if err != nil {
return errors.Wrap(err, "open level db error")
}
db.db = d
return nil
}
func (db *LevelDBImpl) GetMessageByGlobalID(id int32) (IStoredMessage, error) {
v, err := db.db.Get(binary.ToBytes(id), nil)
if err != nil {
return nil, errors.Wrap(err, "get value error")
}
r := binary.NewReader(v)
switch r.ReadByte() {
case group:
g := &StoredGroupMessage{}
if err = gob.NewDecoder(bytes.NewReader(r.ReadAvailable())).Decode(g); err != nil {
return nil, errors.Wrap(err, "decode message error")
}
return g, nil
case private:
p := &StoredPrivateMessage{}
if err = gob.NewDecoder(bytes.NewReader(r.ReadAvailable())).Decode(p); err != nil {
return nil, errors.Wrap(err, "decode message error")
}
return p, nil
default:
return nil, errors.New("unknown message flag")
}
}
func (db *LevelDBImpl) GetGroupMessageByGlobalID(id int32) (*StoredGroupMessage, error) {
i, err := db.GetMessageByGlobalID(id)
if err != nil {
return nil, err
}
g, ok := i.(*StoredGroupMessage)
if !ok {
return nil, errors.New("message type error")
}
return g, nil
}
func (db *LevelDBImpl) GetPrivateMessageByGlobalID(id int32) (*StoredPrivateMessage, error) {
i, err := db.GetMessageByGlobalID(id)
if err != nil {
return nil, err
}
p, ok := i.(*StoredPrivateMessage)
if !ok {
return nil, errors.New("message type error")
}
return p, nil
}
func (db *LevelDBImpl) InsertGroupMessage(msg *StoredGroupMessage) error {
buf := global.NewBuffer()
defer global.PutBuffer(buf)
if err := gob.NewEncoder(buf).Encode(msg); err != nil {
return errors.Wrap(err, "encode message error")
}
err := db.db.Put(binary.ToBytes(msg.GlobalID), binary.NewWriterF(func(w *binary.Writer) {
w.WriteByte(group)
w.Write(buf.Bytes())
}), nil)
return errors.Wrap(err, "put data error")
}
func (db *LevelDBImpl) InsertPrivateMessage(msg *StoredPrivateMessage) error {
buf := global.NewBuffer()
defer global.PutBuffer(buf)
if err := gob.NewEncoder(buf).Encode(msg); err != nil {
return errors.Wrap(err, "encode message error")
}
err := db.db.Put(binary.ToBytes(msg.GlobalID), binary.NewWriterF(func(w *binary.Writer) {
w.WriteByte(private)
w.Write(buf.Bytes())
}), nil)
return errors.Wrap(err, "put data error")
}

71
db/mongodb.go Normal file
View File

@ -0,0 +1,71 @@
package db
import (
"context"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoDBImpl struct {
uri string
db string
mongo *mongo.Database
}
const (
MongoGroupMessageCollection = "group-messages"
MongoPrivateMessageCollection = "private-messages"
)
func UseMongoDB(uri, db string) *MongoDBImpl {
return &MongoDBImpl{uri: uri, db: db}
}
func (db *MongoDBImpl) Open() error {
cli, err := mongo.Connect(context.Background(), options.Client().ApplyURI(db.uri))
if err != nil {
return errors.Wrap(err, "open mongo connection error")
}
db.mongo = cli.Database(db.db)
return nil
}
func (db *MongoDBImpl) GetMessageByGlobalID(id int32) (IStoredMessage, error) {
if r, err := db.GetGroupMessageByGlobalID(id); err == nil {
return r, nil
}
return db.GetPrivateMessageByGlobalID(id)
}
func (db *MongoDBImpl) GetGroupMessageByGlobalID(id int32) (*StoredGroupMessage, error) {
coll := db.mongo.Collection(MongoGroupMessageCollection)
var ret StoredGroupMessage
if err := coll.FindOne(context.Background(), bson.D{{"globalId", id}}).Decode(&ret); err != nil {
return nil, errors.Wrap(err, "query error")
}
return &ret, nil
}
func (db *MongoDBImpl) GetPrivateMessageByGlobalID(id int32) (*StoredPrivateMessage, error) {
coll := db.mongo.Collection(MongoPrivateMessageCollection)
var ret StoredPrivateMessage
if err := coll.FindOne(context.Background(), bson.D{{"globalId", id}}).Decode(&ret); err != nil {
return nil, errors.Wrap(err, "query error")
}
return &ret, nil
}
func (db *MongoDBImpl) InsertGroupMessage(msg *StoredGroupMessage) error {
coll := db.mongo.Collection(MongoGroupMessageCollection)
_, err := coll.InsertOne(context.Background(), msg)
return errors.Wrap(err, "insert error")
}
func (db *MongoDBImpl) InsertPrivateMessage(msg *StoredPrivateMessage) error {
coll := db.mongo.Collection(MongoPrivateMessageCollection)
_, err := coll.InsertOne(context.Background(), msg)
return errors.Wrap(err, "insert error")
}

68
db/multidb.go Normal file
View File

@ -0,0 +1,68 @@
package db
import "github.com/pkg/errors"
// MultiDBImpl 多数据库支持
// 写入会对所有 Backend 进行写入
// 读取只会读取第一个库
type MultiDBImpl struct {
backends []IDatabase
}
func NewMultiDatabase(backends ...IDatabase) *MultiDBImpl {
return &MultiDBImpl{
backends: backends,
}
}
func (db *MultiDBImpl) UseDB(backend IDatabase) {
db.backends = append(db.backends, backend)
}
func (db *MultiDBImpl) Open() error {
for _, b := range db.backends {
if err := b.Open(); err != nil {
return errors.Wrap(err, "open backend error")
}
}
return nil
}
func (db *MultiDBImpl) GetMessageByGlobalID(id int32) (IStoredMessage, error) {
if len(db.backends) == 0 {
return nil, errors.New("database disabled")
}
return db.backends[0].GetMessageByGlobalID(id)
}
func (db *MultiDBImpl) GetGroupMessageByGlobalID(id int32) (*StoredGroupMessage, error) {
if len(db.backends) == 0 {
return nil, errors.New("database disabled")
}
return db.backends[0].GetGroupMessageByGlobalID(id)
}
func (db *MultiDBImpl) GetPrivateMessageByGlobalID(id int32) (*StoredPrivateMessage, error) {
if len(db.backends) == 0 {
return nil, errors.New("database disabled")
}
return db.backends[0].GetPrivateMessageByGlobalID(id)
}
func (db *MultiDBImpl) InsertGroupMessage(m *StoredGroupMessage) error {
for _, b := range db.backends {
if err := b.InsertGroupMessage(m); err != nil {
return errors.Wrap(err, "insert message to backend error")
}
}
return nil
}
func (db *MultiDBImpl) InsertPrivateMessage(m *StoredPrivateMessage) error {
for _, b := range db.backends {
if err := b.InsertPrivateMessage(m); err != nil {
return errors.Wrap(err, "insert message to backend error")
}
}
return nil
}

View File

@ -154,7 +154,7 @@ database: # 数据库相关设置
> 注4关闭心跳服务可能引起断线请谨慎关闭 > 注4关闭心跳服务可能引起断线请谨慎关闭
> 注5关于MINE扫描 详见[MINE](file.md#MINE) > 注5关于MIME扫描 详见[MIME](file.md#MIME)
## 在线状态 ## 在线状态

View File

@ -39,11 +39,11 @@ go-cqhttp 默认生成的文件树如下所示:
| 0x14 | string | 图片原名(QQ内部ID) | | 0x14 | string | 图片原名(QQ内部ID) |
| 0x14 + 原名长度 | string | 图片下载链接 | | 0x14 + 原名长度 | string | 图片下载链接 |
# MINE # MIME
启用MINE检查可以及时发现媒体资源格式错误引起的上传失败(通常表现为请求网页图片但服务端返回404.html) 启用MINE检查可以及时发现媒体资源格式错误引起的上传失败(通常表现为请求网页图片但服务端返回404.html)
在配置文件中设置 `skip-mine-scan: false`go-cqhttp 会在上传媒体资源(视频暂不支持)前对MINE进行检查 在配置文件中设置 `skip-mine-scan: false`go-cqhttp 会在上传媒体资源(视频暂不支持)前对MIME进行检查
详细允许类型如下所示: 详细允许类型如下所示:
图片: 图片:

View File

@ -7,9 +7,9 @@ import (
"os/exec" "os/exec"
"path" "path"
"github.com/Mrs4s/go-cqhttp/global/codec"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
// EncoderSilk 将音频编码为Silk // EncoderSilk 将音频编码为Silk
@ -23,7 +23,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) { if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
return os.ReadFile(silkPath) return os.ReadFile(silkPath)
} }
slk, err := codec.EncodeToSilk(data, tempName, true) slk, err := base.EncodeSilk(data, tempName)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "encode silk failed") return nil, errors.Wrap(err, "encode silk failed")
} }

View File

@ -1,2 +0,0 @@
// Package codec Slik编码核心模块
package codec

View File

@ -1,4 +0,0 @@
package codec
// Debug mode controls the ffmpeg output.
var Debug bool

View File

@ -14,8 +14,9 @@ import (
"strings" "strings"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/segmentio/asm/base64"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/internal/param"
) )
const ( const (
@ -98,7 +99,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
return nil, err return nil, err
} }
case strings.HasPrefix(file, "base64"): case strings.HasPrefix(file, "base64"):
data, err = base64.StdEncoding.DecodeString(strings.TrimPrefix(file, "base64://")) data, err = param.Base64DecodeString(strings.TrimPrefix(file, "base64://"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -12,22 +12,22 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time"
"github.com/guonaihong/gout"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
var ( var (
client = &http.Client{ client = &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
Proxy: func(request *http.Request) (u *url.URL, e error) { Proxy: func(request *http.Request) (u *url.URL, e error) {
if Proxy == "" { if base.Proxy == "" {
return http.ProxyFromEnvironment(request) return http.ProxyFromEnvironment(request)
} }
return url.Parse(Proxy) return url.Parse(base.Proxy)
}, },
ForceAttemptHTTP2: true, ForceAttemptHTTP2: true,
MaxConnsPerHost: 0, MaxConnsPerHost: 0,
@ -36,9 +36,6 @@ var (
}, },
} }
// Proxy 存储Config.proxy_rewrite,用于设置代理
Proxy string
// ErrOverSize 响应主体过大时返回此错误 // ErrOverSize 响应主体过大时返回此错误
ErrOverSize = errors.New("oversize") ErrOverSize = errors.New("oversize")
@ -249,22 +246,6 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
return lastErr return lastErr
} }
// GetSliderTicket 通过给定的验证链接raw和id,获取验证结果Ticket
func GetSliderTicket(raw, id string) (string, error) {
var rsp string
if err := gout.POST("https://api.shkong.com/gocqhttpapi/task").SetJSON(gout.H{
"id": id,
"url": raw,
}).SetTimeout(time.Second * 35).BindBody(&rsp).Do(); err != nil {
return "", err
}
g := gjson.Parse(rsp)
if g.Get("error").Str != "" {
return "", errors.New(g.Get("error").Str)
}
return g.Get("ticket").Str, nil
}
// QQMusicSongInfo 通过给定id在QQ音乐上查找曲目信息 // QQMusicSongInfo 通过给定id在QQ音乐上查找曲目信息
func QQMusicSongInfo(id string) (gjson.Result, error) { func QQMusicSongInfo(id string) (gjson.Result, error) {
d, err := GetBytes(`https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data={%22comm%22:{%22ct%22:24,%22cv%22:0},%22songinfo%22:{%22method%22:%22get_song_detail_yqq%22,%22param%22:{%22song_type%22:0,%22song_mid%22:%22%22,%22song_id%22:` + id + `},%22module%22:%22music.pf_song_detail_svr%22}}`) d, err := GetBytes(`https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data={%22comm%22:{%22ct%22:24,%22cv%22:0},%22songinfo%22:{%22method%22:%22get_song_detail_yqq%22,%22param%22:{%22song_type%22:0,%22song_mid%22:%22%22,%22song_id%22:` + id + `},%22module%22:%22music.pf_song_detail_svr%22}}`)

View File

@ -1,58 +1,14 @@
package global package global
import ( import (
"math"
"reflect"
"regexp" "regexp"
"strconv" "strconv"
"strings"
"sync"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
// EnsureBool 判断给定的p是否可表示为合法Bool类型,否则返回defaultVal // MSG 消息Map
// type MSG map[string]interface{}
// 支持的合法类型有
//
// type bool
//
// type gjson.True or gjson.False
//
// type string "true","yes","1" or "false","no","0" (case insensitive)
func EnsureBool(p interface{}, defaultVal bool) bool {
var str string
if b, ok := p.(bool); ok {
return b
}
if j, ok := p.(gjson.Result); ok {
if !j.Exists() {
return defaultVal
}
switch j.Type { // nolint
case gjson.True:
return true
case gjson.False:
return false
case gjson.String:
str = j.Str
default:
return defaultVal
}
} else if s, ok := p.(string); ok {
str = s
}
str = strings.ToLower(str)
switch str {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return defaultVal
}
}
// VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则 // VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则
// //
@ -88,67 +44,3 @@ func VersionNameCompare(current, remote string) bool {
} }
return cur[4] < re[4] return cur[4] < re[4]
} }
// SetAtDefault 在变量 variable 为默认值 defaultValue 的时候修改为 value
func SetAtDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if v.Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
// SetExcludeDefault 在目标值 value 不为默认值 defaultValue 时修改 variable 为 value
func SetExcludeDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if reflect.Indirect(v2).Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
var (
// once lazy compile the reg
once sync.Once
// reg is splitURL regex pattern.
reg *regexp.Regexp
)
// SplitURL 将给定URL字符串分割为两部分用于URL预处理防止风控
func SplitURL(s string) []string {
once.Do(func() { // lazy init.
reg = regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`)
})
idx := reg.FindAllStringIndex(s, -1)
if len(idx) == 0 {
return []string{s}
}
var result []string
last := 0
for i := 0; i < len(idx); i++ {
if len(idx[i]) != 2 {
continue
}
m := int(math.Abs(float64(idx[i][0]-idx[i][1]))/1.5) + idx[i][0]
result = append(result, s[last:m])
last = m
}
result = append(result, s[last:])
return result
}

View File

@ -1,93 +0,0 @@
// Package update 包含go-cqhttp自我更新相关函数
package update
import (
"bufio"
"bytes"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"github.com/dustin/go-humanize"
"github.com/kardianos/osext"
log "github.com/sirupsen/logrus"
)
// WriteSumCounter 写入量计算实例
type WriteSumCounter struct {
Total uint64
Hash hash.Hash
}
// Write 方法将写入的byte长度追加至写入的总长度Total中
func (wc *WriteSumCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.Hash.Write(p)
fmt.Printf("\r ")
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
return n, nil
}
// FromStream copy form getlantern/go-update
func FromStream(updateWith io.Reader) (err error, errRecover error) {
updatePath, err := osext.Executable()
if err != nil {
return
}
var newBytes []byte
// no patch to apply, go on through
bufBytes := bufio.NewReader(updateWith)
updateWith = io.Reader(bufBytes)
newBytes, err = io.ReadAll(updateWith)
if err != nil {
return
}
// get the directory the executable exists in
updateDir := filepath.Dir(updatePath)
filename := filepath.Base(updatePath)
// Copy the contents of of newbinary to a the new executable file
newPath := filepath.Join(updateDir, fmt.Sprintf(".%s.new", filename))
fp, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return
}
// We won't log this error, because it's always going to happen.
defer func() { _ = fp.Close() }()
if _, err = io.Copy(fp, bytes.NewReader(newBytes)); err != nil {
log.Errorf("Unable to copy data: %v\n", err)
}
// if we don't call fp.Close(), windows won't let us move the new executable
// because the file will still be "in use"
if err := fp.Close(); err != nil {
log.Errorf("Unable to close file: %v\n", err)
}
// this is where we'll move the executable to so that we can swap in the updated replacement
oldPath := filepath.Join(updateDir, fmt.Sprintf(".%s.old", filename))
// delete any existing old exec file - this is necessary on Windows for two reasons:
// 1. after a successful update, Windows can't remove the .old file because the process is still running
// 2. windows rename operations fail if the destination file already exists
_ = os.Remove(oldPath)
// move the existing executable to a new file in the same directory
err = os.Rename(updatePath, oldPath)
if err != nil {
return
}
// move the new executable in to become the new program
err = os.Rename(newPath, updatePath)
if err != nil {
// copy unsuccessful
errRecover = os.Rename(oldPath, updatePath)
} else {
// copy successful, remove the old binary
_ = os.Remove(oldPath)
}
return
}

14
go.mod
View File

@ -9,9 +9,9 @@ require (
github.com/Microsoft/go-winio v0.5.0 github.com/Microsoft/go-winio v0.5.0
github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82 github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/fumiama/go-hide-param v0.1.4
github.com/gabriel-vasile/mimetype v1.3.1 github.com/gabriel-vasile/mimetype v1.3.1
github.com/gorilla/websocket v1.4.2 github.com/gorilla/websocket v1.4.2
github.com/guonaihong/gout v0.2.4
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
@ -22,6 +22,7 @@ require (
github.com/tidwall/gjson v1.8.1 github.com/tidwall/gjson v1.8.1
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60
go.mongodb.org/mongo-driver v1.7.2
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
@ -30,9 +31,11 @@ require (
require ( require (
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect github.com/go-stack/stack v1.8.0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/google/uuid v1.1.1 // indirect github.com/google/uuid v1.1.1 // indirect
github.com/jonboulle/clockwork v0.2.2 // indirect github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/klauspost/compress v1.9.5 // indirect
github.com/klauspost/cpuid/v2 v2.0.6 // indirect github.com/klauspost/cpuid/v2 v2.0.6 // indirect
github.com/lestrrat-go/strftime v1.0.5 // indirect github.com/lestrrat-go/strftime v1.0.5 // indirect
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 // indirect github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 // indirect
@ -44,12 +47,15 @@ require (
github.com/tidwall/match v1.0.3 // indirect github.com/tidwall/match v1.0.3 // indirect
github.com/tidwall/pretty v1.1.0 // indirect github.com/tidwall/pretty v1.1.0 // indirect
github.com/willf/bitset v1.2.0 // indirect github.com/willf/bitset v1.2.0 // indirect
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.0.2 // indirect
github.com/xdg-go/stringprep v1.0.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 // indirect golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect
golang.org/x/text v0.3.6 // indirect
google.golang.org/protobuf v1.27.1 // indirect google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
modernc.org/libc v1.8.1 // indirect modernc.org/libc v1.8.1 // indirect
modernc.org/mathutil v1.2.2 // indirect modernc.org/mathutil v1.2.2 // indirect
modernc.org/memory v1.0.4 // indirect modernc.org/memory v1.0.4 // indirect

126
go.sum
View File

@ -18,24 +18,40 @@ github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25Kn
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fumiama/go-hide-param v0.1.4 h1:y7TRTzZMdCH9GOXnIzU3B+1BSkcmvejVGmGsz4t0DGU=
github.com/fumiama/go-hide-param v0.1.4/go.mod h1:vJkQlJIEI56nIyp7tCQu1/2QOyKtZpudsnJkGk9U1aY=
github.com/gabriel-vasile/mimetype v1.3.1 h1:qevA6c2MtE1RorlScnixeG0VA1H4xrXyhyX3oWBynNQ= github.com/gabriel-vasile/mimetype v1.3.1 h1:qevA6c2MtE1RorlScnixeG0VA1H4xrXyhyX3oWBynNQ=
github.com/gabriel-vasile/mimetype v1.3.1/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= github.com/gabriel-vasile/mimetype v1.3.1/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gin-gonic/gin v1.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU= github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
github.com/gin-gonic/gin v1.7.0/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk=
github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28=
github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo=
github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk=
github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw=
github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360=
github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg=
github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE=
github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8=
github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ=
github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0=
github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
@ -43,57 +59,65 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/guonaihong/gout v0.2.4 h1:BlWpWWay/Q1LkyIwupEWBZE3PMl4xzzAgMHw+OrZxBs=
github.com/guonaihong/gout v0.2.4/go.mod h1:ISabiAAj0z1h3bOFUKzfRqPMvX0wmcYzIh6i4xIxMPo=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA=
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4=
github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA=
github.com/klauspost/compress v1.9.5 h1:U+CaK85mrNNb4k8BNOfgJtJ/gr6kswUCFj6miSzVC6M=
github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/cpuid/v2 v2.0.6 h1:dQ5ueTiftKxp0gyjKSx5+8BtPWkyQbd95m8Gys/RarI= github.com/klauspost/cpuid/v2 v2.0.6 h1:dQ5ueTiftKxp0gyjKSx5+8BtPWkyQbd95m8Gys/RarI=
github.com/klauspost/cpuid/v2 v2.0.6/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.6/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is=
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4= github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4=
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
github.com/lestrrat-go/strftime v1.0.5 h1:A7H3tT8DhTz8u65w+JRpiBxM4dINQhUXAZnhBa2xeOE= github.com/lestrrat-go/strftime v1.0.5 h1:A7H3tT8DhTz8u65w+JRpiBxM4dINQhUXAZnhBa2xeOE=
github.com/lestrrat-go/strftime v1.0.5/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g= github.com/lestrrat-go/strftime v1.0.5/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g=
github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE=
github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0=
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 h1:u9jwvcKbQpghIXgNl/EOL8hzhAFXh4ePrEP493W3tNA= github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 h1:u9jwvcKbQpghIXgNl/EOL8hzhAFXh4ePrEP493W3tNA=
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4/go.mod h1:kcRFpEzolcEklV6rD7W95mG49/sbdX/PlFmd7ni3RvA= github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4/go.mod h1:kcRFpEzolcEklV6rD7W95mG49/sbdX/PlFmd7ni3RvA=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@ -102,17 +126,26 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/segmentio/asm v1.0.0 h1:GMF7/2eLkte13LERSOmPI766AJXJDRlsqqiN8T7Mfmk= github.com/segmentio/asm v1.0.0 h1:GMF7/2eLkte13LERSOmPI766AJXJDRlsqqiN8T7Mfmk=
github.com/segmentio/asm v1.0.0/go.mod h1:4EUJGaKsB8ImLUwOGORVsNd9vTRDeh44JGsY4aKp5I4= github.com/segmentio/asm v1.0.0/go.mod h1:4EUJGaKsB8ImLUwOGORVsNd9vTRDeh44JGsY4aKp5I4=
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE= github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
@ -121,23 +154,30 @@ github.com/tidwall/gjson v1.8.1 h1:8j5EE9Hrh3l9Od1OIEDAb7IpezNA20UdRngNAj5N0WU=
github.com/tidwall/gjson v1.8.1/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk= github.com/tidwall/gjson v1.8.1/go.mod h1:5/xDoumyyDNerp2U36lyolv46b3uF/9Bu6OfyQ9GImk=
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE= github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8= github.com/tidwall/pretty v1.1.0 h1:K3hMW5epkdAVwibsQEfR/7Zj0Qgt4DxtNumTq/VloO8=
github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tidwall/pretty v1.1.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 h1:BWVtt2VBY+lmVDu9MGKqLGKl04B+iRHcrW1Ptyi/8tg= github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2 h1:BWVtt2VBY+lmVDu9MGKqLGKl04B+iRHcrW1Ptyi/8tg=
github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2/go.mod h1:lPnW9HVS0vJdeYyQtOvIvlXgZPNhUAhwz+z5r8AJk0Y= github.com/tuotoo/qrcode v0.0.0-20190222102259-ac9c44189bf2/go.mod h1:lPnW9HVS0vJdeYyQtOvIvlXgZPNhUAhwz+z5r8AJk0Y=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 h1:lRKf10iIOW0VsH5WDF621ihzR+R2wEBZVtNRHuLLCb4= github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60 h1:lRKf10iIOW0VsH5WDF621ihzR+R2wEBZVtNRHuLLCb4=
github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60/go.mod h1:ecFKZPX81BaB70I6ruUgEwYcDOtuNgJGnjdK+MIl5ko= github.com/wdvxdr1123/go-silk v0.0.0-20210316130616-d47b553def60/go.mod h1:ecFKZPX81BaB70I6ruUgEwYcDOtuNgJGnjdK+MIl5ko=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
go.mongodb.org/mongo-driver v1.7.2 h1:pFttQyIiJUHEn50YfZgC9ECjITMT44oiN36uArf/OFg=
go.mongodb.org/mongo-driver v1.7.2/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8NzkI+yfU8=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d h1:RNPAfi2nHY7C2srAV8A49jpsYr0ADedCk1wq6fTMTvs=
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
@ -147,20 +187,27 @@ golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 h1:Ugb8sMTWuWRC3+sz5WeN/4kejDx9BvIwnPUiJBjJE+8= golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 h1:Ugb8sMTWuWRC3+sz5WeN/4kejDx9BvIwnPUiJBjJE+8=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -174,8 +221,8 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE=
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs=
@ -184,7 +231,11 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
@ -206,14 +257,15 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

37
internal/base/feature.go Normal file
View File

@ -0,0 +1,37 @@
package base
import (
"io"
"github.com/pkg/errors"
)
// silk encode features
var (
EncodeSilk = encodeSilk // 编码 SilkV3 音频
ResampleSilk = resampleSilk // 将silk重新编码为 24000 bit rate
)
func encodeSilk(_ []byte, _ string) ([]byte, error) {
return nil, errors.New("not supported now")
}
func resampleSilk(data []byte) []byte {
return data
}
// Mime scan feature
var (
IsLawfulImage = nocheck // 检查图片MIME
IsLawfulAudio = nocheck // 检查音频MIME
)
func nocheck(_ io.ReadSeeker) (bool, string) {
return true, ""
}
// todo: enable in v1.1.0
// onebot v12 feature
const (
AcceptOneBotV12HTTPEndPoint = false
)

148
internal/base/flag.go Normal file
View File

@ -0,0 +1,148 @@
// Package base provides base config for go-cqhttp
package base
import (
"flag"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/modules/config"
)
// command flags
var (
LittleC string // config file
LittleD bool // daemon
LittleH bool // Help
LittleWD string // working directory
)
// config file flags
var (
Debug bool // 是否开启 debug 模式
RemoveReplyAt bool // 是否删除reply后的at
ExtraReplyData bool // 是否上报额外reply信息
IgnoreInvalidCQCode bool // 是否忽略无效CQ码
SplitURL bool // 是否分割URL
ForceFragmented bool // 是否启用强制分片
SkipMimeScan bool // 是否跳过Mime扫描
ReportSelfMessage bool // 是否上报自身消息
UseSSOAddress bool // 是否使用服务器下发的新地址进行重连
LogForceNew bool // 是否在每次启动时强制创建全新的文件储存日志
FastStart bool // 是否为快速启动
PostFormat string // 上报格式 string or array
Proxy string // 存储 proxy_rewrite,用于设置代理
PasswordHash [16]byte // 存储QQ密码哈希供登录使用
AccountToken []byte // 存储 AccountToken 供登录使用
Account *config.Account // 账户配置
Reconnect *config.Reconnect // 重连配置
LogLevel string // 日志等级
LogAging = time.Hour * 24 * 365 // 日志时效
HeartbeatInterval = time.Second * 5 // 心跳间隔
Servers []map[string]yaml.Node // 连接服务列表
Database map[string]yaml.Node // 数据库列表
)
// Parse parse flags
func Parse() {
wd, _ := os.Getwd()
dc := path.Join(wd, "config.yml")
flag.StringVar(&LittleC, "c", dc, "configuration filename")
flag.BoolVar(&LittleD, "d", false, "running as a daemon")
flag.BoolVar(&LittleH, "h", false, "this Help")
flag.StringVar(&LittleWD, "w", "", "cover the working directory")
d := flag.Bool("D", false, "debug mode")
flag.Parse()
if *d {
Debug = true
}
}
// Init read config from yml file
func Init() {
conf := config.Parse(LittleC)
{ // bool config
if conf.Output.Debug {
Debug = true
}
IgnoreInvalidCQCode = conf.Message.IgnoreInvalidCQCode
SplitURL = conf.Message.FixURL
RemoveReplyAt = conf.Message.RemoveReplyAt
ExtraReplyData = conf.Message.ExtraReplyData
ForceFragmented = conf.Message.ForceFragment
SkipMimeScan = conf.Message.SkipMimeScan
ReportSelfMessage = conf.Message.ReportSelfMessage
UseSSOAddress = conf.Account.UseSSOAddress
}
{ // others
Proxy = conf.Message.ProxyRewrite
Account = conf.Account
Reconnect = conf.Account.ReLogin
Servers = conf.Servers
Database = conf.Database
LogLevel = conf.Output.LogLevel
if conf.Message.PostFormat != "string" && conf.Message.PostFormat != "array" {
log.Warnf("post-format 配置错误, 将自动使用 string")
PostFormat = "string"
} else {
PostFormat = conf.Message.PostFormat
}
if conf.Output.LogAging > 0 {
LogAging = time.Hour * 24 * time.Duration(conf.Output.LogAging)
}
if conf.Heartbeat.Interval > 0 {
HeartbeatInterval = time.Second * time.Duration(conf.Heartbeat.Interval)
}
if conf.Heartbeat.Disabled || conf.Heartbeat.Interval < 0 {
HeartbeatInterval = 0
}
}
}
// Help cli命令行-h的帮助提示
func Help() {
fmt.Printf(`go-cqhttp service
version: %s
Usage:
server [OPTIONS]
Options:
`, Version)
flag.PrintDefaults()
os.Exit(0)
}
// ResetWorkingDir 重设工作路径
func ResetWorkingDir() {
wd := LittleWD
args := make([]string, 0, len(os.Args))
for i := 1; i < len(os.Args); i++ {
if os.Args[i] == "-w" {
i++ // skip value field
} else if !strings.HasPrefix(os.Args[i], "-w") {
args = append(args, os.Args[i])
}
}
p, _ := filepath.Abs(os.Args[0])
proc := exec.Command(p, args...)
proc.Stdin = os.Stdin
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
proc.Dir = wd
err := proc.Run()
if err != nil {
panic(err)
}
os.Exit(0)
}

16
internal/base/version.go Normal file
View File

@ -0,0 +1,16 @@
package base
import "runtime/debug"
// Version go-cqhttp的版本信息在编译时使用ldflags进行覆盖
var Version = "unknown"
func init() {
if Version != "unknown" {
return
}
info, ok := debug.ReadBuildInfo()
if ok {
Version = info.Main.Version
}
}

524
internal/btree/btree.go Normal file
View File

@ -0,0 +1,524 @@
// Package btree provide a disk-based btree
package btree
import (
"io"
"math/rand"
"os"
"unsafe"
"github.com/pkg/errors"
)
const (
hashSize = 16 // md5 hash
tableSize = (1024 - 1) / int(unsafe.Sizeof(item{}))
cacheSlots = 11 // prime
superSize = int(unsafe.Sizeof(super{}))
tableStructSize = int(unsafe.Sizeof(table{}))
)
type item struct {
hash [hashSize]byte
offset int64
child int64
}
type table struct {
items [tableSize]item
size int
}
type cache struct {
table *table
offset int64
}
type super struct {
top int64
freeTop int64
alloc int64
}
// DB ...
type DB struct {
fd *os.File
top int64
freeTop int64
alloc int64
cache [cacheSlots]cache
inAllocator bool
deleteLarger bool
fqueue [freeQueueLen]chunk
fqueueLen int
}
func (d *DB) get(offset int64) *table {
assert(offset != 0)
// take from cache
slot := &d.cache[offset%cacheSlots]
if slot.offset == offset {
return slot.table
}
table := new(table)
d.fd.Seek(offset, io.SeekStart)
err := readTable(d.fd, table)
if err != nil {
panic(errors.Wrap(err, "btree I/O error"))
}
return table
}
func (d *DB) put(t *table, offset int64) {
assert(offset != 0)
// overwrite cache
slot := &d.cache[offset%cacheSlots]
slot.table = t
slot.offset = offset
}
func (d *DB) flush(t *table, offset int64) {
assert(offset != 0)
d.fd.Seek(offset, io.SeekStart)
err := writeTable(d.fd, t)
if err != nil {
panic(errors.Wrap(err, "btree I/O error"))
}
d.put(t, offset)
}
func (d *DB) flushSuper() {
d.fd.Seek(0, io.SeekStart)
super := super{
top: d.top,
freeTop: d.freeTop,
alloc: d.alloc,
}
err := writeSuper(d.fd, &super)
if err != nil {
panic(errors.Wrap(err, "btree I/O error"))
}
}
// Open opens an existed btree file
func Open(name string) (*DB, error) {
btree := new(DB)
fd, err := os.OpenFile(name, os.O_RDWR, 0o644)
if err != nil {
return nil, errors.Wrap(err, "btree open file failed")
}
btree.fd = fd
super := super{}
err = readSuper(fd, &super)
btree.top = super.top
btree.freeTop = super.freeTop
btree.alloc = super.alloc
return btree, errors.Wrap(err, "btree read meta info failed")
}
// Create creates a database
func Create(name string) (*DB, error) {
btree := new(DB)
fd, err := os.OpenFile(name, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil {
return nil, errors.Wrap(err, "btree open file failed")
}
btree.fd = fd
btree.alloc = int64(superSize)
btree.flushSuper()
return btree, nil
}
// Close closes the database
func (d *DB) Close() error {
_ = d.fd.Sync()
err := d.fd.Close()
for i := 0; i < cacheSlots; i++ {
d.cache[i] = cache{}
}
return errors.Wrap(err, "btree close failed")
}
func collapse(bt *DB, offset int64) int64 {
table := bt.get(offset)
if table.size != 0 {
/* unable to collapse */
bt.put(table, offset)
return offset
}
ret := table.items[0].child
bt.put(table, offset)
/*
* WARNING: this is dangerous as the chunk is added to allocation tree
* before the references to it are removed!
*/
bt.freeChunk(offset, int(unsafe.Sizeof(table)))
return ret
}
// split a table. The pivot item is stored to 'hash' and 'offset'.
// Returns offset to the new table.
func (d *DB) split(t *table, hash *byte, offset *int64) int64 {
copyhash(hash, &t.items[tableSize/2].hash[0])
*offset = t.items[tableSize/2].offset
ntable := new(table)
ntable.size = t.size - tableSize/2 - 1
t.size = tableSize / 2
copy(ntable.items[:ntable.size+1], t.items[tableSize/2+1:])
noff := d.allocChunk(tableStructSize)
d.flush(ntable, noff)
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
return noff
}
// takeSmallest find and remove the smallest item from the given table. The key of the item
// is stored to 'hash'. Returns offset to the item
func (d *DB) takeSmallest(toff int64, sha1 *byte) int64 {
table := d.get(toff)
assert(table.size > 0)
var off int64
child := table.items[0].child
if child == 0 {
off = d.remove(table, 0, sha1)
} else {
/* recursion */
off = d.takeSmallest(child, sha1)
table.items[0].child = collapse(d, child)
}
d.flush(table, toff)
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
return off
}
// takeLargest find and remove the largest item from the given table. The key of the item
// is stored to 'hash'. Returns offset to the item
func (d *DB) takeLargest(toff int64, hash *byte) int64 {
table := d.get(toff)
assert(table.size > 0)
var off int64
child := table.items[table.size].child
if child == 0 {
off = d.remove(table, table.size-1, hash)
} else {
/* recursion */
off = d.takeLargest(child, hash)
table.items[table.size].child = collapse(d, child)
}
d.flush(table, toff)
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
return off
}
// remove an item in position 'i' from the given table. The key of the
// removed item is stored to 'hash'. Returns offset to the item.
func (d *DB) remove(t *table, i int, hash *byte) int64 {
assert(i < t.size)
if hash != nil {
copyhash(hash, &t.items[i].hash[0])
}
offset := t.items[i].offset
lc := t.items[i].child
rc := t.items[i+1].child
if lc != 0 && rc != 0 {
/* replace the removed item by taking an item from one of the
child tables */
var noff int64
if rand.Int()&1 != 0 {
noff = d.takeLargest(lc, &t.items[i].hash[0])
t.items[i].child = collapse(d, lc)
} else {
noff = d.takeSmallest(rc, &t.items[i].hash[0])
t.items[i+1].child = collapse(d, rc)
}
t.items[i].child = noff
} else {
// memmove(&table->items[i], &table->items[i + 1],
// (table->size - i) * sizeof(struct btree_item));
copy(t.items[i:], t.items[i+1:])
t.size--
if lc != 0 {
t.items[i].child = lc
} else {
t.items[i].child = rc
}
}
return offset
}
func (d *DB) insert(toff int64, hash *byte, data []byte, size int) int64 {
table := d.get(toff)
assert(table.size < tableSize-1)
left, right := 0, table.size
for left < right {
mid := (right-left)>>1 + left
switch cmp := cmp(hash, &table.items[mid].hash[0]); {
case cmp == 0:
// already in the table
ret := table.items[mid].offset
d.put(table, toff)
return ret
case cmp < 0:
right = mid
default:
left = mid + 1
}
}
i := left
var off, rc, ret int64
lc := table.items[i].child
if lc != 0 {
/* recursion */
ret = d.insert(lc, hash, data, size)
/* check if we need to split */
child := d.get(lc)
if child.size < tableSize-1 {
/* nothing to do */
d.put(table, toff)
d.put(child, lc)
return ret
}
/* overwrites SHA-1 */
rc = d.split(child, hash, &off)
/* flush just in case changes happened */
d.flush(child, lc)
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
} else {
off = d.insertData(data, size)
ret = off
}
table.size++
// memmove(&table->items[i + 1], &table->items[i],
// (table->size - i) * sizeof(struct btree_item));
copy(table.items[i+1:], table.items[i:])
copyhash(&table.items[i].hash[0], hash)
table.items[i].offset = off
table.items[i].child = lc
table.items[i+1].child = rc
d.flush(table, toff)
return ret
}
func (d *DB) insertData(data []byte, size int) int64 {
if data == nil {
return int64(size)
}
assert(len(data) == size)
offset := d.allocChunk(4 + len(data))
d.fd.Seek(offset, io.SeekStart)
err := write32(d.fd, int32(len(data)))
if err != nil {
panic(errors.Wrap(err, "btree I/O error"))
}
_, err = d.fd.Write(data)
if err != nil {
panic(errors.Wrap(err, "btree I/O error"))
}
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
return offset
}
// delete remove an item with key 'hash' from the given table. The offset to the
// removed item is returned.
// Please note that 'hash' is overwritten when called inside the allocator.
func (d *DB) delete(offset int64, hash *byte) int64 {
if offset == 0 {
return 0
}
table := d.get(offset)
left, right := 0, table.size
for left < right {
i := (right-left)>>1 + left
switch cmp := cmp(hash, &table.items[i].hash[0]); {
case cmp == 0:
// found
ret := d.remove(table, i, hash)
d.flush(table, offset)
return ret
case cmp < 0:
right = i
default:
left = i + 1
}
}
// not found - recursion
i := left
child := table.items[i].child
ret := d.delete(child, hash)
if ret != 0 {
table.items[i].child = collapse(d, child)
}
if ret == 0 && d.deleteLarger && i < table.size {
ret = d.remove(table, i, hash)
}
if ret != 0 {
/* flush just in case changes happened */
d.flush(table, offset)
} else {
d.put(table, offset)
}
return ret
}
func (d *DB) insertTopLevel(toff *int64, hash *byte, data []byte, size int) int64 { // nolint:unparam
var off, ret, rc int64
if *toff != 0 {
ret = d.insert(*toff, hash, data, size)
/* check if we need to split */
table := d.get(*toff)
if table.size < tableSize-1 {
/* nothing to do */
d.put(table, *toff)
return ret
}
rc = d.split(table, hash, &off)
d.flush(table, *toff)
} else {
off = d.insertData(data, size)
ret = off
}
/* create new top level table */
t := new(table)
t.size = 1
copyhash(&t.items[0].hash[0], hash)
t.items[0].offset = off
t.items[0].child = *toff
t.items[1].child = rc
ntoff := d.allocChunk(tableStructSize)
d.flush(t, ntoff)
*toff = ntoff
// make sure data is written before a reference is added to it
_ = d.fd.Sync()
return ret
}
func (d *DB) lookup(toff int64, hash *byte) int64 {
if toff == 0 {
return 0
}
table := d.get(toff)
left, right := 0, table.size
for left < right {
mid := (right-left)>>1 + left
switch cmp := cmp(hash, &table.items[mid].hash[0]); {
case cmp == 0:
// found
ret := table.items[mid].offset
d.put(table, toff)
return ret
case cmp < 0:
right = mid
default:
left = mid + 1
}
}
i := left
child := table.items[i].child
d.put(table, toff)
return d.lookup(child, hash)
}
// Insert a new item with key 'hash' with the contents in 'data' to the
// database file.
func (d *DB) Insert(chash *byte, data []byte) {
/* SHA-1 must be in writable memory */
var hash [hashSize]byte
copyhash(&hash[0], chash)
_ = d.insertTopLevel(&d.top, &hash[0], data, len(data))
freeQueued(d)
d.flushSuper()
}
// Get look up item with the given key 'hash' in the database file. Length of the
// item is stored in 'len'. Returns a pointer to the contents of the item.
// The returned pointer should be released with free() after use.
func (d *DB) Get(hash *byte) []byte {
off := d.lookup(d.top, hash)
if off == 0 {
return nil
}
d.fd.Seek(off, io.SeekStart)
length, err := read32(d.fd)
if err != nil {
return nil
}
data := make([]byte, length)
n, err := io.ReadFull(d.fd, data)
if err != nil {
return nil
}
return data[:n]
}
// Delete remove item with the given key 'hash' from the database file.
func (d *DB) Delete(hash *byte) error {
var h [hashSize]byte
copyhash(&h[0], hash)
off := d.delete(d.top, &h[0])
if off == 0 {
return nil // not found key
}
d.top = collapse(d, d.top)
freeQueued(d)
d.flushSuper()
d.fd.Seek(off, io.SeekStart)
length, err := read32(d.fd) // len: 0
if err != nil {
return errors.Wrap(err, "btree I/O error")
}
d.freeChunk(off, int(length+4))
freeQueued(d)
d.flushSuper()
return nil
}

View File

@ -0,0 +1,61 @@
package btree
import (
"crypto/sha1"
"os"
"testing"
assert2 "github.com/stretchr/testify/assert"
)
func tempfile(t *testing.T) string {
temp, err := os.CreateTemp(".", "temp.*.db")
assert2.NoError(t, temp.Close())
assert2.NoError(t, err)
return temp.Name()
}
func TestCreate(t *testing.T) {
f := tempfile(t)
_, err := Create(f)
assert2.NoError(t, err)
defer os.Remove(f)
}
func TestBtree(t *testing.T) {
f := tempfile(t)
defer os.Remove(f)
bt, err := Create(f)
assert2.NoError(t, err)
var tests = []string{
"hello world",
"123",
"We are met on a great battle-field of that war.",
"Abraham Lincoln, November 19, 1863, Gettysburg, Pennsylvania",
}
var sha = make([]*byte, len(tests))
for i, tt := range tests {
var hash = sha1.New()
hash.Write([]byte(tt))
sha[i] = &hash.Sum(nil)[0]
bt.Insert(sha[i], []byte(tt))
}
assert2.NoError(t, bt.Close())
bt, err = Open(f)
assert2.NoError(t, err)
for i, tt := range tests {
assert2.Equal(t, []byte(tt), bt.Get(sha[i]))
}
for i := range tests {
assert2.NoError(t, bt.Delete(sha[i]))
}
for i := range tests {
assert2.Equal(t, []byte(nil), bt.Get(sha[i]))
}
assert2.NoError(t, bt.Close())
}

122
internal/btree/chunk.go Normal file
View File

@ -0,0 +1,122 @@
package btree
import (
"math/rand"
"unsafe"
)
type chunk struct {
offset int64
len int
}
const freeQueueLen = 64
func freeQueued(bt *DB) {
for i := 0; i < bt.fqueueLen; i++ {
chunk := &bt.fqueue[i]
bt.freeChunk(chunk.offset, chunk.len)
}
bt.fqueueLen = 0
}
func (d *DB) allocChunk(size int) int64 {
assert(size > 0)
size = power2(size)
var offset int64
if d.inAllocator {
const i32s = unsafe.Sizeof(int32(0))
/* create fake size SHA-1 */
var sha1 [hashSize]byte
p := unsafe.Pointer(&sha1[0])
*(*int32)(p) = -1 // *(uint32_t *) hash = -1;
*(*uint32)(unsafe.Add(p, i32s)) = uint32(size) // ((__be32 *) hash)[1] = to_be32(size);
/* find free chunk with the larger or the same size/SHA-1 */
d.inAllocator = true
d.deleteLarger = true
offset = d.delete(d.freeTop, &sha1[0])
d.deleteLarger = false
if offset != 0 {
assert(*(*int32)(p) == -1) // assert(*(uint32_t *) hash == (uint32_t) -1)
flen := int(*(*uint32)(unsafe.Add(p, i32s))) // size_t free_len = from_be32(((__be32 *) hash)[1])
assert(power2(flen) == flen)
assert(flen >= size)
/* delete buddy information */
resethash(&sha1[0])
*(*int64)(p) = offset
buddyLen := d.delete(d.freeTop, &sha1[0])
assert(buddyLen == int64(size))
d.freeTop = collapse(d, d.freeTop)
d.inAllocator = false
/* free extra space at the end of the chunk */
for flen > size {
flen >>= 1
d.freeChunk(offset+int64(flen), flen)
}
} else {
d.inAllocator = false
}
}
if offset == 0 {
/* not found, allocate from the end of the file */
offset = d.alloc
/* TODO: this wastes memory.. */
if offset&int64(size-1) != 0 {
offset += int64(size) - (offset & (int64(size) - 1))
}
d.alloc = offset + int64(size)
}
d.flushSuper()
// make sure the allocation tree is up-to-date before using the chunk
_ = d.fd.Sync()
return offset
}
/* Mark a chunk as unused in the database file */
func (d *DB) freeChunk(offset int64, size int) {
assert(size > 0)
assert(offset != 0)
size = power2(size)
assert(offset&int64(size-1) == 0)
if d.inAllocator {
chunk := &d.fqueue[d.fqueueLen]
d.fqueueLen++
chunk.offset = offset
chunk.len = size
return
}
/* create fake offset SHA-1 for buddy allocation */
var sha1 [hashSize]byte
p := unsafe.Pointer(&sha1[0])
d.inAllocator = true
const i32s = unsafe.Sizeof(int32(0))
/* add buddy information */
resethash(&sha1[0])
*(*int32)(p) = -1 // *(uint32_t *) hash = -1;
*(*uint32)(unsafe.Add(p, i32s)) = uint32(size) // ((__be32 *) hash)[1] = to_be32(size);
*(*uint32)(unsafe.Add(p, i32s*2)) = rand.Uint32() /* to make SHA-1 unique */
*(*uint32)(unsafe.Add(p, i32s*3)) = rand.Uint32()
// insert_toplevel(btree, &btree->free_top, hash, NULL, offset);
_ = d.insertTopLevel(&d.freeTop, &sha1[0], nil, int(offset))
d.inAllocator = false
d.flushSuper()
// make sure the allocation tree is up-to-date before removing
// references to the chunk
_ = d.fd.Sync()
}

106
internal/btree/helper.go Normal file
View File

@ -0,0 +1,106 @@
package btree
import (
"io"
"reflect"
"unsafe"
)
func assert(cond bool) {
if !cond {
panic("assert failed!")
}
}
// power2 returns a value that is greater or equal to 'val' and is power-of-two.
func power2(val int) int {
i := 1
for i < val {
i <<= 1
}
return i
}
// helpers for hash
func cmp(a, b *byte) int64 {
pa, pb := unsafe.Pointer(a), unsafe.Pointer(b)
if *(*uint64)(pa) != *(*uint64)(pb) {
return int64(*(*uint64)(pa) - *(*uint64)(pb))
}
pa, pb = unsafe.Add(pa, 8), unsafe.Add(pb, 8)
return int64(*(*uint64)(pa) - *(*uint64)(pb))
}
func copyhash(dst *byte, src *byte) {
pa, pb := unsafe.Pointer(dst), unsafe.Pointer(src)
*(*[hashSize]byte)(pa) = *(*[hashSize]byte)(pb)
}
func resethash(sha1 *byte) {
p := unsafe.Pointer(sha1)
*(*[hashSize]byte)(p) = [hashSize]byte{}
}
// reading table
func read32(r io.Reader) (int32, error) {
var b = make([]byte, 4)
_, err := r.Read(b)
if err != nil {
return 0, err
}
return *(*int32)(unsafe.Pointer(&b[0])), nil
}
func readTable(r io.Reader, t *table) error {
buf := make([]byte, tableStructSize)
_, err := r.Read(buf)
if err != nil {
return err
}
*t = *(*table)(unsafe.Pointer(&buf[0]))
return nil
}
func readSuper(r io.Reader, s *super) error {
buf := make([]byte, superSize)
_, err := r.Read(buf)
if err != nil {
return err
}
*s = *(*super)(unsafe.Pointer(&buf[0]))
return nil
}
// write table
func write32(w io.Writer, t int32) error {
var p []byte
ph := (*reflect.SliceHeader)(unsafe.Pointer(&p))
ph.Data = uintptr(unsafe.Pointer(&t))
ph.Len = 4
ph.Cap = 4
_, err := w.Write(p)
return err
}
func writeTable(w io.Writer, t *table) error {
var p []byte
ph := (*reflect.SliceHeader)(unsafe.Pointer(&p))
ph.Data = uintptr(unsafe.Pointer(t))
ph.Len = tableStructSize
ph.Cap = tableStructSize
_, err := w.Write(p)
return err
}
func writeSuper(w io.Writer, s *super) error {
var p []byte
ph := (*reflect.SliceHeader)(unsafe.Pointer(&p))
ph.Data = uintptr(unsafe.Pointer(s))
ph.Len = superSize
ph.Cap = superSize
_, err := w.Write(p)
return err
}

97
internal/cache/cache.go vendored Normal file
View File

@ -0,0 +1,97 @@
// Package cache impl the cache for gocq
package cache
import (
"fmt"
"sync"
log "github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/btree"
)
// todo(wdvxdr): always enable db-cache in v1.0.0
// EnableCacheDB 是否启用 btree db缓存图片等
var EnableCacheDB bool
// Media Cache DBs
var (
Image Cache
Video Cache
// todo: Voice?
)
// Cache wraps the btree.DB for concurrent safe
type Cache struct {
lock sync.RWMutex
db *btree.DB
}
// Insert 添加媒体缓存
func (c *Cache) Insert(md5, data []byte) {
c.lock.Lock()
defer c.lock.Unlock()
var hash [16]byte
copy(hash[:], md5)
c.db.Insert(&hash[0], data)
}
// Get 获取缓存信息
func (c *Cache) Get(md5 []byte) []byte {
c.lock.RLock()
defer c.lock.RUnlock()
var hash [16]byte
copy(hash[:], md5)
return c.db.Get(&hash[0])
}
// Delete 删除指定缓存
func (c *Cache) Delete(md5 []byte) {
c.lock.Lock()
defer c.lock.Unlock()
var hash [16]byte
copy(hash[:], md5)
_ = c.db.Delete(&hash[0])
}
// Init 初始化 Cache
func Init() {
node, ok := base.Database["cache"]
if !ok {
return
}
EnableCacheDB = true
var conf map[string]string
err := node.Decode(&conf)
if err != nil {
log.Fatalf("failed to read cache config: %v", err)
}
var open = func(typ string, cache *Cache) {
file := conf[typ]
if file == "" {
file = fmt.Sprintf("data/%s.db", typ)
}
if global.PathExists(file) {
db, err := btree.Open(file)
if err != nil {
log.Fatalf("open %s cache failed: %v", typ, err)
}
cache.db = db
} else {
db, err := btree.Create(file)
if err != nil {
log.Fatalf("create %s cache failed: %v", typ, err)
}
cache.db = db
}
}
open("image", &Image)
open("video", &Video)
}

130
internal/param/param.go Normal file
View File

@ -0,0 +1,130 @@
// Package param provide some util for param parse
package param
import (
"math"
"reflect"
"regexp"
"strings"
"sync"
"github.com/Mrs4s/MiraiGo/utils"
"github.com/segmentio/asm/base64"
"github.com/tidwall/gjson"
)
// EnsureBool 判断给定的p是否可表示为合法Bool类型,否则返回defaultVal
//
// 支持的合法类型有
//
// type bool
//
// type gjson.True or gjson.False
//
// type string "true","yes","1" or "false","no","0" (case insensitive)
func EnsureBool(p interface{}, defaultVal bool) bool {
var str string
if b, ok := p.(bool); ok {
return b
}
if j, ok := p.(gjson.Result); ok {
if !j.Exists() {
return defaultVal
}
switch j.Type { // nolint
case gjson.True:
return true
case gjson.False:
return false
case gjson.String:
str = j.Str
default:
return defaultVal
}
} else if s, ok := p.(string); ok {
str = s
}
str = strings.ToLower(str)
switch str {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return defaultVal
}
}
var (
// once lazy compile the reg
once sync.Once
// reg is splitURL regex pattern.
reg *regexp.Regexp
)
// SplitURL 将给定URL字符串分割为两部分用于URL预处理防止风控
func SplitURL(s string) []string {
once.Do(func() { // lazy init.
reg = regexp.MustCompile(`(?i)[a-z\d][-a-z\d]{0,62}(\.[a-z\d][-a-z\d]{0,62})+\.?`)
})
idx := reg.FindAllStringIndex(s, -1)
if len(idx) == 0 {
return []string{s}
}
var result []string
last := 0
for i := 0; i < len(idx); i++ {
if len(idx[i]) != 2 {
continue
}
m := int(math.Abs(float64(idx[i][0]-idx[i][1]))/1.5) + idx[i][0]
result = append(result, s[last:m])
last = m
}
result = append(result, s[last:])
return result
}
// Base64DecodeString decode base64 with avx2
// see https://github.com/segmentio/asm/issues/50
// avoid incorrect unsafe usage in origin library
func Base64DecodeString(s string) ([]byte, error) {
e := base64.StdEncoding
dst := make([]byte, e.DecodedLen(len(s)))
n, err := e.Decode(dst, utils.S2B(s))
return dst[:n], err
}
// SetAtDefault 在变量 variable 为默认值 defaultValue 的时候修改为 value
func SetAtDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if v.Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}
// SetExcludeDefault 在目标值 value 不为默认值 defaultValue 时修改 variable 为 value
func SetExcludeDefault(variable, value, defaultValue interface{}) {
v := reflect.ValueOf(variable)
v2 := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if reflect.Indirect(v2).Interface() != defaultValue {
return
}
if v.Kind() != v2.Kind() {
return
}
v.Set(v2)
}

View File

@ -0,0 +1,206 @@
// Package selfupdate 版本升级检查和自更新
package selfupdate
import (
"bufio"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/dustin/go-humanize"
"github.com/kardianos/osext"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func readLine() (str string) {
console := bufio.NewReader(os.Stdin)
str, _ = console.ReadString('\n')
str = strings.TrimSpace(str)
return
}
func lastVersion() (string, error) {
r, err := global.GetBytes("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest")
if err != nil {
return "", err
}
return gjson.GetBytes(r, "tag_name").Str, nil
}
// CheckUpdate 检查更新
func CheckUpdate() {
logrus.Infof("正在检查更新.")
if base.Version == "(devel)" {
logrus.Warnf("检查更新失败: 使用的 Actions 测试版或自编译版本.")
return
}
latest, err := lastVersion()
if err != nil {
logrus.Warnf("检查更新失败: %v", err)
return
}
if global.VersionNameCompare(base.Version, latest) {
logrus.Infof("当前有更新的 go-cqhttp 可供更新, 请前往 https://github.com/Mrs4s/go-cqhttp/releases 下载.")
logrus.Infof("当前版本: %v 最新版本: %v", base.Version, latest)
return
}
logrus.Infof("检查更新完成. 当前已运行最新版本.")
}
func binaryName() string {
goarch := runtime.GOARCH
if goarch == "arm" {
goarch += "v7"
}
ext := "tar.gz"
if runtime.GOOS == "windows" {
ext = "zip"
}
return fmt.Sprintf("go-cqhttp_%v_%v.%v", runtime.GOOS, goarch, ext)
}
func checksum(github, version string) []byte {
sumURL := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp_checksums.txt", github, version)
closer, err := global.HTTPGetReadCloser(sumURL)
if err != nil {
return nil
}
rd := bufio.NewReader(closer)
for {
str, err := rd.ReadString('\n')
if err != nil {
break
}
str = strings.TrimSpace(str)
if strings.HasSuffix(str, binaryName()) {
sum, _ := hex.DecodeString(strings.TrimSuffix(str, " "+binaryName()))
return sum
}
}
return nil
}
func wait() {
logrus.Info("按 Enter 继续....")
readLine()
os.Exit(0)
}
// SelfUpdate 自更新
func SelfUpdate(github string) {
if github == "" {
github = "https://github.com"
}
logrus.Infof("正在检查更新.")
latest, err := lastVersion()
if err != nil {
logrus.Warnf("获取最新版本失败: %v", err)
wait()
}
url := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/%v", github, latest, binaryName())
if base.Version == latest {
logrus.Info("当前版本已经是最新版本!")
wait()
}
logrus.Info("当前最新版本为 ", latest)
logrus.Warn("是否更新(y/N): ")
r := strings.TrimSpace(readLine())
if r != "y" && r != "Y" {
logrus.Warn("已取消更新!")
wait()
}
logrus.Info("正在更新,请稍等...")
sum := checksum(github, latest)
if sum != nil {
err = update(url, sum)
if err != nil {
logrus.Error("更新失败: ", err)
} else {
logrus.Info("更新成功!")
}
} else {
logrus.Error("checksum 失败!")
}
wait()
}
// writeSumCounter 写入量计算实例
type writeSumCounter struct {
total uint64
hash hash.Hash
}
// Write 方法将写入的byte长度追加至写入的总长度Total中
func (wc *writeSumCounter) Write(p []byte) (int, error) {
n := len(p)
wc.total += uint64(n)
wc.hash.Write(p)
fmt.Printf("\r ")
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.total))
return n, nil
}
// FromStream copy form getlantern/go-update
func fromStream(updateWith io.Reader) (err error, errRecover error) {
updatePath, err := osext.Executable()
if err != nil {
return
}
// get the directory the executable exists in
updateDir := filepath.Dir(updatePath)
filename := filepath.Base(updatePath)
// Copy the contents of of newbinary to a the new executable file
newPath := filepath.Join(updateDir, fmt.Sprintf(".%s.new", filename))
fp, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return
}
// We won't log this error, because it's always going to happen.
defer func() { _ = fp.Close() }()
if _, err = io.Copy(fp, bufio.NewReader(updateWith)); err != nil {
logrus.Errorf("Unable to copy data: %v\n", err)
}
// if we don't call fp.Close(), windows won't let us move the new executable
// because the file will still be "in use"
if err := fp.Close(); err != nil {
logrus.Errorf("Unable to close file: %v\n", err)
}
// this is where we'll move the executable to so that we can swap in the updated replacement
oldPath := filepath.Join(updateDir, fmt.Sprintf(".%s.old", filename))
// delete any existing old exec file - this is necessary on Windows for two reasons:
// 1. after a successful update, Windows can't remove the .old file because the process is still running
// 2. windows rename operations fail if the destination file already exists
_ = os.Remove(oldPath)
// move the existing executable to a new file in the same directory
err = os.Rename(updatePath, oldPath)
if err != nil {
return
}
// move the new executable in to become the new program
err = os.Rename(newPath, updatePath)
if err != nil {
// copy unsuccessful
errRecover = os.Rename(oldPath, updatePath)
} else {
// copy successful, remove the old binary
_ = os.Remove(oldPath)
}
return
}

View File

@ -1,7 +1,7 @@
//go:build !windows //go:build !windows
// +build !windows // +build !windows
package update package selfupdate
import ( import (
"archive/tar" "archive/tar"
@ -14,21 +14,21 @@ import (
"net/http" "net/http"
) )
// Update go-cqhttp自我更新 // update go-cqhttp自我更新
func Update(url string, sum []byte) error { func update(url string, sum []byte) error {
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
wc := WriteSumCounter{ wc := writeSumCounter{
Hash: sha256.New(), hash: sha256.New(),
} }
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc)) rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
if err != nil { if err != nil {
return err return err
} }
if !bytes.Equal(wc.Hash.Sum(nil), sum) { if !bytes.Equal(wc.hash.Sum(nil), sum) {
return errors.New("文件已损坏") return errors.New("文件已损坏")
} }
gr, err := gzip.NewReader(bytes.NewReader(rsp)) gr, err := gzip.NewReader(bytes.NewReader(rsp))
@ -42,7 +42,7 @@ func Update(url string, sum []byte) error {
return err return err
} }
if header.Name == "go-cqhttp" { if header.Name == "go-cqhttp" {
err, _ := FromStream(tr) err, _ := fromStream(tr)
fmt.Println() fmt.Println()
if err != nil { if err != nil {
return err return err

View File

@ -1,4 +1,4 @@
package update package selfupdate
import ( import (
"archive/zip" "archive/zip"
@ -10,21 +10,21 @@ import (
"net/http" "net/http"
) )
// Update go-cqhttp自我更新 // update go-cqhttp自我更新
func Update(url string, sum []byte) error { func update(url string, sum []byte) error {
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
wc := WriteSumCounter{ wc := writeSumCounter{
Hash: sha256.New(), hash: sha256.New(),
} }
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc)) rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
if err != nil { if err != nil {
return err return err
} }
if !bytes.Equal(wc.Hash.Sum(nil), sum) { if !bytes.Equal(wc.hash.Sum(nil), sum) {
return errors.New("文件已损坏") return errors.New("文件已损坏")
} }
reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength) reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength)
@ -32,7 +32,7 @@ func Update(url string, sum []byte) error {
if err != nil { if err != nil {
return err return err
} }
err, _ = FromStream(file) err, _ = fromStream(file)
fmt.Println() fmt.Println()
if err != nil { if err != nil {
return err return err

View File

@ -18,13 +18,13 @@ import (
var console = bufio.NewReader(os.Stdin) var console = bufio.NewReader(os.Stdin)
var readLine = func() (str string) { func readLine() (str string) {
str, _ = console.ReadString('\n') str, _ = console.ReadString('\n')
str = strings.TrimSpace(str) str = strings.TrimSpace(str)
return return
} }
var readLineTimeout = func(t time.Duration, de string) (str string) { func readLineTimeout(t time.Duration, de string) (str string) {
r := make(chan string) r := make(chan string)
go func() { go func() {
select { select {

411
main.go
View File

@ -1,107 +1,70 @@
package main package main
import ( import (
"bufio"
"crypto/aes" "crypto/aes"
"crypto/md5" "crypto/md5"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"flag"
"fmt"
"os" "os"
"os/exec"
"path" "path"
"path/filepath"
"runtime"
"strings"
"sync" "sync"
"time" "time"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/codec"
"github.com/Mrs4s/go-cqhttp/global/config"
"github.com/Mrs4s/go-cqhttp/global/terminal"
"github.com/Mrs4s/go-cqhttp/global/update"
"github.com/Mrs4s/go-cqhttp/server"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/guonaihong/gout" para "github.com/fumiama/go-hide-param"
rotatelogs "github.com/lestrrat-go/file-rotatelogs" rotatelogs "github.com/lestrrat-go/file-rotatelogs"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
"golang.org/x/term" "golang.org/x/term"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/terminal"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/cache"
"github.com/Mrs4s/go-cqhttp/internal/selfupdate"
"github.com/Mrs4s/go-cqhttp/modules/servers"
"github.com/Mrs4s/go-cqhttp/server"
_ "github.com/Mrs4s/go-cqhttp/modules/mime" // mime检查模块
_ "github.com/Mrs4s/go-cqhttp/modules/silk" // silk编码模块
) )
var ( // 允许通过配置文件设置的状态列表
conf *config.Config var allowStatus = [...]client.UserOnlineStatus{
isFastStart = false client.StatusOnline, client.StatusAway, client.StatusInvisible, client.StatusBusy,
// PasswordHash 存储QQ密码哈希供登录使用 client.StatusListening, client.StatusConstellation, client.StatusWeather, client.StatusMeetSpring,
PasswordHash [16]byte client.StatusTimi, client.StatusEatChicken, client.StatusLoving, client.StatusWangWang, client.StatusCookedRice,
client.StatusStudy, client.StatusStayUp, client.StatusPlayBall, client.StatusSignal, client.StatusStudyOnline,
// AccountToken 存储AccountToken供登录使用 client.StatusGaming, client.StatusVacationing, client.StatusWatchingTV, client.StatusFitness,
AccountToken []byte }
// 允许通过配置文件设置的状态列表
allowStatus = [...]client.UserOnlineStatus{
client.StatusOnline, client.StatusAway, client.StatusInvisible, client.StatusBusy,
client.StatusListening, client.StatusConstellation, client.StatusWeather, client.StatusMeetSpring,
client.StatusTimi, client.StatusEatChicken, client.StatusLoving, client.StatusWangWang, client.StatusCookedRice,
client.StatusStudy, client.StatusStayUp, client.StatusPlayBall, client.StatusSignal, client.StatusStudyOnline,
client.StatusGaming, client.StatusVacationing, client.StatusWatchingTV, client.StatusFitness,
}
)
func main() { func main() {
c := flag.String("c", config.DefaultConfigFile, "configuration filename") base.Parse()
d := flag.Bool("d", false, "running as a daemon")
h := flag.Bool("h", false, "this help")
wd := flag.String("w", "", "cover the working directory")
debug := flag.Bool("D", false, "debug mode")
flag.Parse()
switch { switch {
case *h: case base.LittleH:
help() base.Help()
case *d: case base.LittleD:
server.Daemon() server.Daemon()
case *wd != "": case base.LittleWD != "":
resetWorkDir(*wd) base.ResetWorkingDir()
}
// 通过-c 参数替换 配置文件路径
config.DefaultConfigFile = *c
conf = config.Get()
if *debug {
conf.Output.Debug = true
}
if conf.Output.Debug {
log.SetReportCaller(true)
codec.Debug = true
} }
base.Init()
rotateOptions := []rotatelogs.Option{ rotateOptions := []rotatelogs.Option{
rotatelogs.WithRotationTime(time.Hour * 24), rotatelogs.WithRotationTime(time.Hour * 24),
} }
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(base.LogAging))
if conf.Output.LogAging > 0 { if base.LogForceNew {
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(time.Hour*24*time.Duration(conf.Output.LogAging)))
} else {
rotateOptions = append(rotateOptions, rotatelogs.WithMaxAge(time.Hour*24*365*10))
}
if conf.Output.LogForceNew {
rotateOptions = append(rotateOptions, rotatelogs.ForceNewFile()) rotateOptions = append(rotateOptions, rotatelogs.ForceNewFile())
} }
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotateOptions...) w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotateOptions...)
if err != nil { if err != nil {
log.Errorf("rotatelogs init err: %v", err) log.Errorf("rotatelogs init err: %v", err)
panic(err) panic(err)
} }
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(base.LogLevel)...))
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(conf.Output.LogLevel)...))
mkCacheDir := func(path string, _type string) { mkCacheDir := func(path string, _type string) {
if !global.PathExists(path) { if !global.PathExists(path) {
@ -114,6 +77,7 @@ func main() {
mkCacheDir(global.VoicePath, "语音") mkCacheDir(global.VoicePath, "语音")
mkCacheDir(global.VideoPath, "视频") mkCacheDir(global.VideoPath, "视频")
mkCacheDir(global.CachePath, "发送图片") mkCacheDir(global.CachePath, "发送图片")
cache.Init()
var byteKey []byte var byteKey []byte
arg := os.Args arg := os.Args
@ -122,20 +86,23 @@ func main() {
switch arg[i] { switch arg[i] {
case "update": case "update":
if len(arg) > i+1 { if len(arg) > i+1 {
selfUpdate(arg[i+1]) selfupdate.SelfUpdate(arg[i+1])
} else { } else {
selfUpdate("") selfupdate.SelfUpdate("")
} }
case "key": case "key":
if len(arg) > i+1 { p := i + 1
byteKey = []byte(arg[i+1]) if len(arg) > p {
byteKey = []byte(arg[p])
para.Hide(p)
} }
case "faststart": case "faststart":
isFastStart = true base.FastStart = true
} }
} }
} }
if terminal.RunningByDoubleClick() && !isFastStart {
if !base.FastStart && terminal.RunningByDoubleClick() {
err := terminal.NoMoreDoubleClick() err := terminal.NoMoreDoubleClick()
if err != nil { if err != nil {
log.Errorf("遇到错误: %v", err) log.Errorf("遇到错误: %v", err)
@ -144,17 +111,18 @@ func main() {
return return
} }
if (conf.Account.Uin == 0 || (conf.Account.Password == "" && !conf.Account.Encrypt)) && !global.PathExists("session.token") { if (base.Account.Uin == 0 || (base.Account.Password == "" && !base.Account.Encrypt)) && !global.PathExists("session.token") {
log.Warn("账号密码未配置, 将使用二维码登录.") log.Warn("账号密码未配置, 将使用二维码登录.")
if !isFastStart { if !base.FastStart {
log.Warn("将在 5秒 后继续.") log.Warn("将在 5秒 后继续.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
} }
} }
log.Info("当前版本:", coolq.Version) log.Info("当前版本:", base.Version)
if conf.Output.Debug { if base.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
log.SetReportCaller(true)
log.Warnf("已开启Debug模式.") log.Warnf("已开启Debug模式.")
log.Debugf("开发交流群: 192548878") log.Debugf("开发交流群: 192548878")
} }
@ -171,22 +139,22 @@ func main() {
} }
} }
if conf.Account.Encrypt { if base.Account.Encrypt {
if !global.PathExists("password.encrypt") { if !global.PathExists("password.encrypt") {
if conf.Account.Password == "" { if base.Account.Password == "" {
log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.") log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
} }
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)") log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd())) byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
PasswordHash = md5.Sum([]byte(conf.Account.Password)) base.PasswordHash = md5.Sum([]byte(base.Account.Password))
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(PasswordHash[:], byteKey)), 0o644) _ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(base.PasswordHash[:], byteKey)), 0o644)
log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.") log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
} else { } else {
if conf.Account.Password != "" { if base.Account.Password != "" {
log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.") log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
readLine() readLine()
os.Exit(0) os.Exit(0)
@ -218,12 +186,12 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码") log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
} }
copy(PasswordHash[:], ph) copy(base.PasswordHash[:], ph)
} }
} else { } else if len(base.Account.Password) > 0 {
PasswordHash = md5.Sum([]byte(conf.Account.Password)) base.PasswordHash = md5.Sum([]byte(base.Account.Password))
} }
if !isFastStart { if !base.FastStart {
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.") log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
} }
@ -244,21 +212,20 @@ func main() {
return "未知" return "未知"
}()) }())
cli = newClient() cli = newClient()
global.Proxy = conf.Message.ProxyRewrite isQRCodeLogin := (base.Account.Uin == 0 || len(base.Account.Password) == 0) && !base.Account.Encrypt
isQRCodeLogin := (conf.Account.Uin == 0 || len(conf.Account.Password) == 0) && !conf.Account.Encrypt
isTokenLogin := false isTokenLogin := false
saveToken := func() { saveToken := func() {
AccountToken = cli.GenToken() base.AccountToken = cli.GenToken()
_ = os.WriteFile("session.token", AccountToken, 0o644) _ = os.WriteFile("session.token", base.AccountToken, 0o644)
} }
if global.PathExists("session.token") { if global.PathExists("session.token") {
token, err := os.ReadFile("session.token") token, err := os.ReadFile("session.token")
if err == nil { if err == nil {
if conf.Account.Uin != 0 { if base.Account.Uin != 0 {
r := binary.NewReader(token) r := binary.NewReader(token)
cu := r.ReadInt64() cu := r.ReadInt64()
if cu != conf.Account.Uin { if cu != base.Account.Uin {
log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", conf.Account.Uin, cu) log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", base.Account.Uin, cu)
log.Warnf("1. 使用会话缓存继续.") log.Warnf("1. 使用会话缓存继续.")
log.Warnf("2. 删除会话缓存并重启.") log.Warnf("2. 删除会话缓存并重启.")
log.Warnf("请选择: (5秒后自动选1)") log.Warnf("请选择: (5秒后自动选1)")
@ -282,9 +249,9 @@ func main() {
} }
} }
} }
if conf.Account.Uin != 0 && PasswordHash != [16]byte{} { if base.Account.Uin != 0 && base.PasswordHash != [16]byte{} {
cli.Uin = conf.Account.Uin cli.Uin = base.Account.Uin
cli.PasswordMd5 = PasswordHash cli.PasswordMd5 = base.PasswordHash
} }
if !isTokenLogin { if !isTokenLogin {
if !isQRCodeLogin { if !isQRCodeLogin {
@ -307,19 +274,19 @@ func main() {
return return
} }
log.Warnf("Bot已离线: %v", e.Message) log.Warnf("Bot已离线: %v", e.Message)
time.Sleep(time.Second * time.Duration(conf.Account.ReLogin.Delay)) time.Sleep(time.Second * time.Duration(base.Reconnect.Delay))
for { for {
if conf.Account.ReLogin.Disabled { if base.Reconnect.Disabled {
log.Warnf("未启用自动重连, 将退出.") log.Warnf("未启用自动重连, 将退出.")
os.Exit(1) os.Exit(1)
} }
if times > conf.Account.ReLogin.MaxTimes && conf.Account.ReLogin.MaxTimes != 0 { if times > base.Reconnect.MaxTimes && base.Reconnect.MaxTimes != 0 {
log.Fatalf("Bot重连次数超过限制, 停止") log.Fatalf("Bot重连次数超过限制, 停止")
} }
times++ times++
if conf.Account.ReLogin.Interval > 0 { if base.Reconnect.Interval > 0 {
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", conf.Account.ReLogin.Interval, times, conf.Account.ReLogin.MaxTimes) log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", base.Reconnect.Interval, times, base.Reconnect.MaxTimes)
time.Sleep(time.Second * time.Duration(conf.Account.ReLogin.Interval)) time.Sleep(time.Second * time.Duration(base.Reconnect.Interval))
} else { } else {
time.Sleep(time.Second) time.Sleep(time.Second)
} }
@ -328,7 +295,7 @@ func main() {
break break
} }
log.Warnf("尝试重连...") log.Warnf("尝试重连...")
err := cli.TokenLogin(AccountToken) err := cli.TokenLogin(base.AccountToken)
if err == nil { if err == nil {
saveToken() saveToken()
return return
@ -356,70 +323,16 @@ func main() {
log.Infof("开始加载群列表...") log.Infof("开始加载群列表...")
global.Check(cli.ReloadGroupList(), true) global.Check(cli.ReloadGroupList(), true)
log.Infof("共加载 %v 个群.", len(cli.GroupList)) log.Infof("共加载 %v 个群.", len(cli.GroupList))
if conf.Account.Status >= int32(len(allowStatus)) || conf.Account.Status < 0 { if uint(base.Account.Status) >= uint(len(allowStatus)) {
conf.Account.Status = 0 base.Account.Status = 0
}
cli.SetOnlineStatus(allowStatus[int(conf.Account.Status)])
bot := coolq.NewQQBot(cli, conf)
_ = bot.Client
if conf.Message.PostFormat != "string" && conf.Message.PostFormat != "array" {
log.Warnf("post-format 配置错误, 将自动使用 string")
coolq.SetMessageFormat("string")
} else {
coolq.SetMessageFormat(conf.Message.PostFormat)
}
coolq.IgnoreInvalidCQCode = conf.Message.IgnoreInvalidCQCode
coolq.SplitURL = conf.Message.FixURL
coolq.ForceFragmented = conf.Message.ForceFragment
coolq.RemoveReplyAt = conf.Message.RemoveReplyAt
coolq.ExtraReplyData = conf.Message.ExtraReplyData
coolq.SkipMimeScan = conf.Message.SkipMimeScan
for _, m := range conf.Servers {
if h, ok := m["http"]; ok {
hc := new(config.HTTPServer)
if err := h.Decode(hc); err != nil {
log.Warn("读取http配置失败 :", err)
} else {
go server.RunHTTPServerAndClients(bot, hc)
}
}
if s, ok := m["ws"]; ok {
sc := new(config.WebsocketServer)
if err := s.Decode(sc); err != nil {
log.Warn("读取正向Websocket配置失败 :", err)
} else {
go server.RunWebSocketServer(bot, sc)
}
}
if c, ok := m["ws-reverse"]; ok {
rc := new(config.WebsocketReverse)
if err := c.Decode(rc); err != nil {
log.Warn("读取反向Websocket配置失败 :", err)
} else {
go server.RunWebSocketClient(bot, rc)
}
}
if p, ok := m["pprof"]; ok {
pc := new(config.PprofServer)
if err := p.Decode(pc); err != nil {
log.Warn("读取pprof配置失败 :", err)
} else {
go server.RunPprofServer(pc)
}
}
if p, ok := m["lambda"]; ok {
lc := new(config.LambdaServer)
if err := p.Decode(lc); err != nil {
log.Warn("读取pprof配置失败 :", err)
} else {
go server.RunLambdaClient(bot, lc)
}
}
} }
cli.SetOnlineStatus(allowStatus[base.Account.Status])
servers.Run(coolq.NewQQBot(cli))
log.Info("资源初始化完成, 开始处理信息.") log.Info("资源初始化完成, 开始处理信息.")
log.Info("アトリは、高性能ですから!") log.Info("アトリは、高性能ですから!")
go checkUpdate() go selfupdate.CheckUpdate()
<-global.SetupMainSignalHandler() <-global.SetupMainSignalHandler()
} }
@ -455,178 +368,10 @@ func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, erro
return result, nil return result, nil
} }
func checkUpdate() {
log.Infof("正在检查更新.")
if coolq.Version == "(devel)" {
log.Warnf("检查更新失败: 使用的 Actions 测试版或自编译版本.")
return
}
var res string
if err := gout.GET("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest").BindBody(&res).Do(); err != nil {
log.Warnf("检查更新失败: %v", err)
return
}
info := gjson.Parse(res)
if global.VersionNameCompare(coolq.Version, info.Get("tag_name").Str) {
log.Infof("当前有更新的 go-cqhttp 可供更新, 请前往 https://github.com/Mrs4s/go-cqhttp/releases 下载.")
log.Infof("当前版本: %v 最新版本: %v", coolq.Version, info.Get("tag_name").Str)
return
}
log.Infof("检查更新完成. 当前已运行最新版本.")
}
func selfUpdate(imageURL string) {
log.Infof("正在检查更新.")
var res, r string
if err := gout.GET("https://api.github.com/repos/Mrs4s/go-cqhttp/releases/latest").BindBody(&res).Do(); err != nil {
log.Warnf("检查更新失败: %v", err)
return
}
info := gjson.Parse(res)
version := info.Get("tag_name").Str
if coolq.Version == version {
log.Info("当前版本已经是最新版本!")
goto wait
}
log.Info("当前最新版本为 ", version)
log.Warn("是否更新(y/N): ")
r = strings.TrimSpace(readLine())
if r != "y" && r != "Y" {
log.Warn("已取消更新!")
} else {
log.Info("正在更新,请稍等...")
sumURL := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/go-cqhttp_checksums.txt",
func() string {
if imageURL != "" {
return imageURL
}
return "https://github.com"
}(), version)
closer, err := global.HTTPGetReadCloser(sumURL)
if err != nil {
log.Error("更新失败: ", err)
goto wait
}
rd := bufio.NewReader(closer)
binaryName := fmt.Sprintf("go-cqhttp_%v_%v.%v", runtime.GOOS, func() string {
if runtime.GOARCH == "arm" {
return "armv7"
}
return runtime.GOARCH
}(), func() string {
if runtime.GOOS == "windows" {
return "zip"
}
return "tar.gz"
}())
var sum []byte
for {
str, err := rd.ReadString('\n')
if err != nil {
break
}
str = strings.TrimSpace(str)
if strings.HasSuffix(str, binaryName) {
sum, _ = hex.DecodeString(strings.TrimSuffix(str, " "+binaryName))
break
}
}
url := fmt.Sprintf("%v/Mrs4s/go-cqhttp/releases/download/%v/%v",
func() string {
if imageURL != "" {
return imageURL
}
return "https://github.com"
}(), version, binaryName)
err = update.Update(url, sum)
if err != nil {
log.Error("更新失败: ", err)
} else {
log.Info("更新成功!")
}
}
wait:
log.Info("按 Enter 继续....")
readLine()
os.Exit(0)
}
/*
func restart(args []string) {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
file, err := exec.LookPath(args[0])
if err != nil {
log.Errorf("重启失败:%s", err.Error())
return
}
path, err := filepath.Abs(file)
if err != nil {
log.Errorf("重启失败:%s", err.Error())
}
args = append([]string{"/c", "start ", path, "faststart"}, args[1:]...)
cmd = &exec.Cmd{
Path: "cmd.exe",
Args: args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
} else {
args = append(args, "faststart")
cmd = &exec.Cmd{
Path: args[0],
Args: args,
Stderr: os.Stderr,
Stdout: os.Stdout,
}
}
_ = cmd.Start()
}
*/
// help cli命令行-h的帮助提示
func help() {
fmt.Printf(`go-cqhttp service
version: %s
Usage:
server [OPTIONS]
Options:
`, coolq.Version)
flag.PrintDefaults()
os.Exit(0)
}
func resetWorkDir(wd string) {
args := make([]string, 0, len(os.Args))
for i := 1; i < len(os.Args); i++ {
if os.Args[i] == "-w" {
i++ // skip value field
} else if !strings.HasPrefix(os.Args[i], "-w") {
args = append(args, os.Args[i])
}
}
p, _ := filepath.Abs(os.Args[0])
proc := exec.Command(p, args...)
proc.Stdin = os.Stdin
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
proc.Dir = wd
err := proc.Run()
if err != nil {
panic(err)
}
os.Exit(0)
}
func newClient() *client.QQClient { func newClient() *client.QQClient {
c := client.NewClientEmpty() c := client.NewClientEmpty()
c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool { c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool {
if !conf.Account.UseSSOAddress { if !base.UseSSOAddress {
log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.") log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.")
return false return false
} }

View File

@ -6,12 +6,10 @@ import (
_ "embed" // embed the default config file _ "embed" // embed the default config file
"fmt" "fmt"
"os" "os"
"path"
"strconv" "strconv"
"strings" "strings"
"sync"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/internal/param"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -21,27 +19,27 @@ import (
//go:embed default_config.yml //go:embed default_config.yml
var defaultConfig string var defaultConfig string
var currentPath = getCurrentPath() // Reconnect 重连配置
type Reconnect struct {
Disabled bool `yaml:"disabled"`
Delay uint `yaml:"delay"`
MaxTimes uint `yaml:"max-times"`
Interval int `yaml:"interval"`
}
// DefaultConfigFile 默认配置文件路径 // Account 账号配置
var DefaultConfigFile = path.Join(currentPath, "config.yml") type Account struct {
Uin int64 `yaml:"uin"`
Password string `yaml:"password"`
Encrypt bool `yaml:"encrypt"`
Status int `yaml:"status"`
ReLogin *Reconnect `yaml:"relogin"`
UseSSOAddress bool `yaml:"use-sso-address"`
}
// Config 总配置文件 // Config 总配置文件
type Config struct { type Config struct {
Account struct { Account *Account `yaml:"account"`
Uin int64 `yaml:"uin"`
Password string `yaml:"password"`
Encrypt bool `yaml:"encrypt"`
Status int32 `yaml:"status"`
ReLogin struct {
Disabled bool `yaml:"disabled"`
Delay uint `yaml:"delay"`
MaxTimes uint `yaml:"max-times"`
Interval int `yaml:"interval"`
}
UseSSOAddress bool `yaml:"use-sso-address"`
} `yaml:"account"`
Heartbeat struct { Heartbeat struct {
Disabled bool `yaml:"disabled"` Disabled bool `yaml:"disabled"`
Interval int `yaml:"interval"` Interval int `yaml:"interval"`
@ -49,10 +47,10 @@ type Config struct {
Message struct { Message struct {
PostFormat string `yaml:"post-format"` PostFormat string `yaml:"post-format"`
ProxyRewrite string `yaml:"proxy-rewrite"`
IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"` IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"`
ForceFragment bool `yaml:"force-fragment"` ForceFragment bool `yaml:"force-fragment"`
FixURL bool `yaml:"fix-url"` FixURL bool `yaml:"fix-url"`
ProxyRewrite string `yaml:"proxy-rewrite"`
ReportSelfMessage bool `yaml:"report-self-message"` ReportSelfMessage bool `yaml:"report-self-message"`
RemoveReplyAt bool `yaml:"remove-reply-at"` RemoveReplyAt bool `yaml:"remove-reply-at"`
ExtraReplyData bool `yaml:"extra-reply-data"` ExtraReplyData bool `yaml:"extra-reply-data"`
@ -139,113 +137,104 @@ type LevelDBConfig struct {
Enable bool `yaml:"enable"` Enable bool `yaml:"enable"`
} }
var ( // MongoDBConfig mongodb 相关配置
config *Config type MongoDBConfig struct {
once sync.Once Enable bool `yaml:"enable"`
) URI string `yaml:"uri"`
Database string `yaml:"database"`
// Get 从默认配置文件路径中获取
func Get() *Config {
once.Do(func() {
hasEnvironmentConf := os.Getenv("GCQ_UIN") != ""
file, err := os.Open(DefaultConfigFile)
config = &Config{}
if err == nil {
defer func() { _ = file.Close() }()
if err = yaml.NewDecoder(file).Decode(config); err != nil && !hasEnvironmentConf {
log.Fatal("配置文件不合法!", err)
}
} else if !hasEnvironmentConf {
generateConfig()
os.Exit(0)
}
if hasEnvironmentConf {
// type convert tools
toInt64 := func(str string) int64 {
i, _ := strconv.ParseInt(str, 10, 64)
return i
}
// load config from environment variable
global.SetAtDefault(&config.Account.Uin, toInt64(os.Getenv("GCQ_UIN")), int64(0))
global.SetAtDefault(&config.Account.Password, os.Getenv("GCQ_PWD"), "")
global.SetAtDefault(&config.Account.Status, int32(toInt64(os.Getenv("GCQ_STATUS"))), int32(0))
global.SetAtDefault(&config.Account.ReLogin.Disabled, !global.EnsureBool(os.Getenv("GCQ_RELOGIN_DISABLED"), true), false)
global.SetAtDefault(&config.Account.ReLogin.Delay, uint(toInt64(os.Getenv("GCQ_RELOGIN_DELAY"))), uint(0))
global.SetAtDefault(&config.Account.ReLogin.MaxTimes, uint(toInt64(os.Getenv("GCQ_RELOGIN_MAX_TIMES"))), uint(0))
dbConf := &LevelDBConfig{Enable: global.EnsureBool(os.Getenv("GCQ_LEVELDB"), true)}
if config.Database == nil {
config.Database = make(map[string]yaml.Node)
}
config.Database["leveldb"] = func() yaml.Node {
n := &yaml.Node{}
_ = n.Encode(dbConf)
return *n
}()
accessTokenEnv := os.Getenv("GCQ_ACCESS_TOKEN")
if os.Getenv("GCQ_HTTP_PORT") != "" {
node := &yaml.Node{}
httpConf := &HTTPServer{
Host: "0.0.0.0",
Port: 5700,
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
global.SetExcludeDefault(&httpConf.Disabled, global.EnsureBool(os.Getenv("GCQ_HTTP_DISABLE"), false), false)
global.SetExcludeDefault(&httpConf.Host, os.Getenv("GCQ_HTTP_HOST"), "")
global.SetExcludeDefault(&httpConf.Port, int(toInt64(os.Getenv("GCQ_HTTP_PORT"))), 0)
if os.Getenv("GCQ_HTTP_POST_URL") != "" {
httpConf.Post = append(httpConf.Post, struct {
URL string `yaml:"url"`
Secret string `yaml:"secret"`
}{os.Getenv("GCQ_HTTP_POST_URL"), os.Getenv("GCQ_HTTP_POST_SECRET")})
}
_ = node.Encode(httpConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"http": *node})
}
if os.Getenv("GCQ_WS_PORT") != "" {
node := &yaml.Node{}
wsServerConf := &WebsocketServer{
Host: "0.0.0.0",
Port: 6700,
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
global.SetExcludeDefault(&wsServerConf.Disabled, global.EnsureBool(os.Getenv("GCQ_WS_DISABLE"), false), false)
global.SetExcludeDefault(&wsServerConf.Host, os.Getenv("GCQ_WS_HOST"), "")
global.SetExcludeDefault(&wsServerConf.Port, int(toInt64(os.Getenv("GCQ_WS_PORT"))), 0)
_ = node.Encode(wsServerConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws": *node})
}
if os.Getenv("GCQ_RWS_API") != "" || os.Getenv("GCQ_RWS_EVENT") != "" || os.Getenv("GCQ_RWS_UNIVERSAL") != "" {
node := &yaml.Node{}
rwsConf := &WebsocketReverse{
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
global.SetExcludeDefault(&rwsConf.Disabled, global.EnsureBool(os.Getenv("GCQ_RWS_DISABLE"), false), false)
global.SetExcludeDefault(&rwsConf.API, os.Getenv("GCQ_RWS_API"), "")
global.SetExcludeDefault(&rwsConf.Event, os.Getenv("GCQ_RWS_EVENT"), "")
global.SetExcludeDefault(&rwsConf.Universal, os.Getenv("GCQ_RWS_UNIVERSAL"), "")
_ = node.Encode(rwsConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws-reverse": *node})
}
}
})
return config
} }
// getCurrentPath 获取当前文件路径直接返回string // Parse 从默认配置文件路径中获取
func getCurrentPath() string { func Parse(path string) *Config {
cwd, e := os.Getwd() fromEnv := os.Getenv("GCQ_UIN") != ""
if e != nil {
panic(e) file, err := os.Open(path)
config := &Config{}
if err == nil {
defer func() { _ = file.Close() }()
if err = yaml.NewDecoder(file).Decode(config); err != nil && !fromEnv {
log.Fatal("配置文件不合法!", err)
}
} else if !fromEnv {
generateConfig()
os.Exit(0)
} }
return cwd if fromEnv {
// type convert tools
toInt64 := func(str string) int64 {
i, _ := strconv.ParseInt(str, 10, 64)
return i
}
// load config from environment variable
param.SetAtDefault(&config.Account.Uin, toInt64(os.Getenv("GCQ_UIN")), int64(0))
param.SetAtDefault(&config.Account.Password, os.Getenv("GCQ_PWD"), "")
param.SetAtDefault(&config.Account.Status, int32(toInt64(os.Getenv("GCQ_STATUS"))), int32(0))
param.SetAtDefault(&config.Account.ReLogin.Disabled, !param.EnsureBool(os.Getenv("GCQ_RELOGIN_DISABLED"), true), false)
param.SetAtDefault(&config.Account.ReLogin.Delay, uint(toInt64(os.Getenv("GCQ_RELOGIN_DELAY"))), uint(0))
param.SetAtDefault(&config.Account.ReLogin.MaxTimes, uint(toInt64(os.Getenv("GCQ_RELOGIN_MAX_TIMES"))), uint(0))
dbConf := &LevelDBConfig{Enable: param.EnsureBool(os.Getenv("GCQ_LEVELDB"), true)}
if config.Database == nil {
config.Database = make(map[string]yaml.Node)
}
config.Database["leveldb"] = func() yaml.Node {
n := &yaml.Node{}
_ = n.Encode(dbConf)
return *n
}()
accessTokenEnv := os.Getenv("GCQ_ACCESS_TOKEN")
if os.Getenv("GCQ_HTTP_PORT") != "" {
node := &yaml.Node{}
httpConf := &HTTPServer{
Host: "0.0.0.0",
Port: 5700,
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
param.SetExcludeDefault(&httpConf.Disabled, param.EnsureBool(os.Getenv("GCQ_HTTP_DISABLE"), false), false)
param.SetExcludeDefault(&httpConf.Host, os.Getenv("GCQ_HTTP_HOST"), "")
param.SetExcludeDefault(&httpConf.Port, int(toInt64(os.Getenv("GCQ_HTTP_PORT"))), 0)
if os.Getenv("GCQ_HTTP_POST_URL") != "" {
httpConf.Post = append(httpConf.Post, struct {
URL string `yaml:"url"`
Secret string `yaml:"secret"`
}{os.Getenv("GCQ_HTTP_POST_URL"), os.Getenv("GCQ_HTTP_POST_SECRET")})
}
_ = node.Encode(httpConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"http": *node})
}
if os.Getenv("GCQ_WS_PORT") != "" {
node := &yaml.Node{}
wsServerConf := &WebsocketServer{
Host: "0.0.0.0",
Port: 6700,
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
param.SetExcludeDefault(&wsServerConf.Disabled, param.EnsureBool(os.Getenv("GCQ_WS_DISABLE"), false), false)
param.SetExcludeDefault(&wsServerConf.Host, os.Getenv("GCQ_WS_HOST"), "")
param.SetExcludeDefault(&wsServerConf.Port, int(toInt64(os.Getenv("GCQ_WS_PORT"))), 0)
_ = node.Encode(wsServerConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws": *node})
}
if os.Getenv("GCQ_RWS_API") != "" || os.Getenv("GCQ_RWS_EVENT") != "" || os.Getenv("GCQ_RWS_UNIVERSAL") != "" {
node := &yaml.Node{}
rwsConf := &WebsocketReverse{
MiddleWares: MiddleWares{
AccessToken: accessTokenEnv,
},
}
param.SetExcludeDefault(&rwsConf.Disabled, param.EnsureBool(os.Getenv("GCQ_RWS_DISABLE"), false), false)
param.SetExcludeDefault(&rwsConf.API, os.Getenv("GCQ_RWS_API"), "")
param.SetExcludeDefault(&rwsConf.Event, os.Getenv("GCQ_RWS_EVENT"), "")
param.SetExcludeDefault(&rwsConf.Universal, os.Getenv("GCQ_RWS_UNIVERSAL"), "")
_ = node.Encode(rwsConf)
config.Servers = append(config.Servers, map[string]yaml.Node{"ws-reverse": *node})
}
}
return config
} }
// generateConfig 生成配置文件 // generateConfig 生成配置文件

View File

@ -75,6 +75,11 @@ database: # 数据库相关设置
# 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能 # 关闭将无法使用 撤回 回复 get_msg 等上下文相关功能
enable: true enable: true
# 媒体文件缓存, 删除此项则使用缓存文件(旧版行为)
cache:
image: data/image.db
video: data/video.db
# 连接服务列表 # 连接服务列表
servers: servers:
# 添加方式,同一连接方式可添加多个,具体配置说明请查看文档 # 添加方式,同一连接方式可添加多个,具体配置说明请查看文档

70
modules/mime/mime.go Normal file
View File

@ -0,0 +1,70 @@
// Package mime 提供MIME检查功能
package mime
import (
"io"
"github.com/gabriel-vasile/mimetype"
"github.com/sirupsen/logrus"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func init() {
base.IsLawfulAudio = checkImage
base.IsLawfulAudio = checkAudio
}
// keep sync with /docs/file.md#MINE
var lawfulImage = [...]string{
"image/bmp",
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
}
var lawfulAudio = [...]string{
"audio/aac",
"audio/aiff",
"audio/amr",
"audio/ape",
"audio/flac",
"audio/midi",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/x-m4a",
}
func check(r io.ReadSeeker, list []string) (bool, string) {
if base.SkipMimeScan {
return true, ""
}
_, _ = r.Seek(0, io.SeekStart)
defer r.Seek(0, io.SeekStart)
t, err := mimetype.DetectReader(r)
if err != nil {
logrus.Debugf("扫描 Mime 时出现问题: %v", err)
return false, ""
}
for _, lt := range list {
if t.Is(lt) {
return true, t.String()
}
}
return false, t.String()
}
// checkImage 判断给定流是否为合法图片
// 返回 是否合法, 实际Mime
// 判断后会自动将 Stream Seek 至 0
func checkImage(r io.ReadSeeker) (bool, string) {
return check(r, lawfulImage[:])
}
// checkImage 判断给定流是否为合法音频
func checkAudio(r io.ReadSeeker) (bool, string) {
return check(r, lawfulAudio[:])
}

View File

@ -0,0 +1,31 @@
// Package servers provide servers register
package servers
import (
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/internal/base"
)
var svr = make(map[string]func(*coolq.CQBot, yaml.Node))
// Register 注册 Server
func Register(name string, proc func(*coolq.CQBot, yaml.Node)) {
_, ok := svr[name]
if ok {
panic(name + " server has existed")
}
svr[name] = proc
}
// Run 运行所有svr
func Run(bot *coolq.CQBot) {
for _, l := range base.Servers {
for name, conf := range l {
if fn, ok := svr[name]; ok {
go fn(bot, conf)
}
}
}
}

View File

@ -4,7 +4,7 @@
// +build !race // +build !race
// +build !nosilk // +build !nosilk
package codec package silk
import ( import (
"os" "os"
@ -13,12 +13,14 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/wdvxdr1123/go-silk" "github.com/wdvxdr1123/go-silk"
"github.com/Mrs4s/go-cqhttp/internal/base"
) )
const silkCachePath = "data/cache" const silkCachePath = "data/cache"
// EncodeToSilk 将音频编码为Silk // encode 将音频编码为Silk
func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte, err error) { func encode(record []byte, tempName string) (silkWav []byte, err error) {
// 1. 写入缓存文件 // 1. 写入缓存文件
rawPath := path.Join(silkCachePath, tempName+".wav") rawPath := path.Join(silkCachePath, tempName+".wav")
err = os.WriteFile(rawPath, record, os.ModePerm) err = os.WriteFile(rawPath, record, os.ModePerm)
@ -30,7 +32,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
// 2.转换pcm // 2.转换pcm
pcmPath := path.Join(silkCachePath, tempName+".pcm") pcmPath := path.Join(silkCachePath, tempName+".pcm")
cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath) cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath)
if Debug { if base.Debug {
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
} }
@ -48,15 +50,13 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
if err != nil { if err != nil {
return nil, errors.Wrap(err, "silk encode error") return nil, errors.Wrap(err, "silk encode error")
} }
if useCache { silkPath := path.Join(silkCachePath, tempName+".silk")
silkPath := path.Join(silkCachePath, tempName+".silk") err = os.WriteFile(silkPath, silkWav, 0o666)
err = os.WriteFile(silkPath, silkWav, 0o666)
}
return return
} }
// RecodeTo24K 将silk重新编码为 24000 bit rate // resample 将silk重新编码为 24000 bit rate
func RecodeTo24K(data []byte) []byte { func resample(data []byte) []byte {
pcm, err := silk.DecodeSilkBuffToPcm(data, 24000) pcm, err := silk.DecodeSilkBuffToPcm(data, 24000)
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -1,16 +1,16 @@
//go:build (!arm && !arm64 && !amd64 && !386) || (!windows && !linux && !darwin) || (windows && arm) || (windows && arm64) || race || nosilk //go:build (!arm && !arm64 && !amd64 && !386) || (!windows && !linux && !darwin) || (windows && arm) || (windows && arm64) || race || nosilk
// +build !arm,!arm64,!amd64,!386 !windows,!linux,!darwin windows,arm windows,arm64 race nosilk // +build !arm,!arm64,!amd64,!386 !windows,!linux,!darwin windows,arm windows,arm64 race nosilk
package codec package silk
import "errors" import "errors"
// EncodeToSilk 将音频编码为Silk // encode 将音频编码为Silk
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) { func encode(record []byte, tempName string) ([]byte, error) {
return nil, errors.New("not supported now") return nil, errors.New("not supported now")
} }
// RecodeTo24K 将silk重新编码为 24000 bit rate // resample 将silk重新编码为 24000 bit rate
func RecodeTo24K(data []byte) []byte { func resample(data []byte) []byte {
return data return data
} }

11
modules/silk/stubs.go Normal file
View File

@ -0,0 +1,11 @@
// Package silk Silk编码核心模块
package silk
import (
"github.com/Mrs4s/go-cqhttp/internal/base"
)
func init() {
base.EncodeSilk = encode
base.ResampleSilk = resample
}

View File

@ -5,6 +5,7 @@ import (
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/param"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -13,57 +14,57 @@ type resultGetter interface {
Get(string) gjson.Result Get(string) gjson.Result
} }
type handler func(action string, p resultGetter) coolq.MSG type handler func(action string, p resultGetter) global.MSG
type apiCaller struct { type apiCaller struct {
bot *coolq.CQBot bot *coolq.CQBot
handlers []handler handlers []handler
} }
func getLoginInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getLoginInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetLoginInfo() return bot.CQGetLoginInfo()
} }
func getQiDianAccountInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getQiDianAccountInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetQiDianAccountInfo() return bot.CQGetQiDianAccountInfo()
} }
func getFriendList(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getFriendList(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetFriendList() return bot.CQGetFriendList()
} }
func getUnidirectionalFriendList(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getUnidirectionalFriendList(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetUnidirectionalFriendList() return bot.CQGetUnidirectionalFriendList()
} }
func deleteFriend(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteFriend(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteFriend(p.Get("[user_id,id]").Int()) return bot.CQDeleteFriend(p.Get("[user_id,id].0").Int())
} }
func deleteUnidirectionalFriend(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteUnidirectionalFriend(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteUnidirectionalFriend(p.Get("user_id").Int()) return bot.CQDeleteUnidirectionalFriend(p.Get("user_id").Int())
} }
func getGroupList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupList(p.Get("no_cache").Bool()) return bot.CQGetGroupList(p.Get("no_cache").Bool())
} }
func getGroupInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupInfo(p.Get("group_id").Int(), p.Get("no_cache").Bool()) return bot.CQGetGroupInfo(p.Get("group_id").Int(), p.Get("no_cache").Bool())
} }
func getGroupMemberList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMemberList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool()) return bot.CQGetGroupMemberList(p.Get("group_id").Int(), p.Get("no_cache").Bool())
} }
func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMemberInfo( return bot.CQGetGroupMemberInfo(
p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("no_cache").Bool(), p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("no_cache").Bool(),
) )
} }
func sendMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
autoEscape := global.EnsureBool(p.Get("auto_escape"), false) autoEscape := param.EnsureBool(p.Get("auto_escape"), false)
if p.Get("message_type").Str == "private" { if p.Get("message_type").Str == "private" {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), autoEscape) return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), autoEscape)
} }
@ -76,28 +77,28 @@ func sendMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG {
if p.Get("group_id").Int() != 0 { if p.Get("group_id").Int() != 0 {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), autoEscape) return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), autoEscape)
} }
return coolq.MSG{} return global.MSG{}
} }
func sendGroupMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"), return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message"),
global.EnsureBool(p.Get("auto_escape"), false)) param.EnsureBool(p.Get("auto_escape"), false))
} }
func sendGroupForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupForwardMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendGroupForwardMessage(p.Get("group_id").Int(), p.Get("messages")) return bot.CQSendGroupForwardMessage(p.Get("group_id").Int(), p.Get("messages"))
} }
func sendPrivateMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendPrivateMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"),
global.EnsureBool(p.Get("auto_escape"), false)) param.EnsureBool(p.Get("auto_escape"), false))
} }
func deleteMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteMessage(int32(p.Get("message_id").Int())) return bot.CQDeleteMessage(int32(p.Get("message_id").Int()))
} }
func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) global.MSG {
apr := true apr := true
if p.Get("approve").Exists() { if p.Get("approve").Exists() {
apr = p.Get("approve").Bool() apr = p.Get("approve").Bool()
@ -105,7 +106,7 @@ func setFriendAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQProcessFriendRequest(p.Get("flag").Str, apr) return bot.CQProcessFriendRequest(p.Get("flag").Str, apr)
} }
func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) global.MSG {
subType := p.Get("sub_type").Str subType := p.Get("sub_type").Str
apr := true apr := true
if subType == "" { if subType == "" {
@ -117,19 +118,19 @@ func setGroupAddRequest(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, p.Get("reason").Str, apr) return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, p.Get("reason").Str, apr)
} }
func setGroupCard(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupCard(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str) return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str)
} }
func setGroupSpecialTitle(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupSpecialTitle(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str) return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str)
} }
func setGroupKick(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupKick(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str, p.Get("reject_add_request").Bool()) return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str, p.Get("reject_add_request").Bool())
} }
func setGroupBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupBan(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 { return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), func() uint32 {
if p.Get("duration").Exists() { if p.Get("duration").Exists() {
return uint32(p.Get("duration").Int()) return uint32(p.Get("duration").Int())
@ -138,7 +139,7 @@ func setGroupBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupWholeBan(p.Get("group_id").Int(), func() bool { return bot.CQSetGroupWholeBan(p.Get("group_id").Int(), func() bool {
if p.Get("enable").Exists() { if p.Get("enable").Exists() {
return p.Get("enable").Bool() return p.Get("enable").Bool()
@ -147,11 +148,11 @@ func setGroupWholeBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func setGroupName(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupName(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("group_name").Str) return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("group_name").Str)
} }
func setGroupAdmin(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAdmin(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupAdmin(p.Get("group_id").Int(), p.Get("user_id").Int(), func() bool { return bot.CQSetGroupAdmin(p.Get("group_id").Int(), p.Get("user_id").Int(), func() bool {
if p.Get("enable").Exists() { if p.Get("enable").Exists() {
return p.Get("enable").Bool() return p.Get("enable").Bool()
@ -160,19 +161,19 @@ func setGroupAdmin(bot *coolq.CQBot, p resultGetter) coolq.MSG {
}()) }())
} }
func sendGroupNotice(bot *coolq.CQBot, p resultGetter) coolq.MSG { func sendGroupNotice(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupMemo(p.Get("group_id").Int(), p.Get("content").Str, p.Get("image").String()) return bot.CQSetGroupMemo(p.Get("group_id").Int(), p.Get("content").Str, p.Get("image").String())
} }
func setGroupLeave(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupLeave(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupLeave(p.Get("group_id").Int()) return bot.CQSetGroupLeave(p.Get("group_id").Int())
} }
func getImage(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getImage(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetImage(p.Get("file").Str) return bot.CQGetImage(p.Get("file").Str)
} }
func getForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getForwardMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
id := p.Get("message_id").Str id := p.Get("message_id").Str
if id == "" { if id == "" {
id = p.Get("id").Str id = p.Get("id").Str
@ -180,11 +181,11 @@ func getForwardMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQGetForwardMessage(id) return bot.CQGetForwardMessage(id)
} }
func getMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetMessage(int32(p.Get("message_id").Int())) return bot.CQGetMessage(int32(p.Get("message_id").Int()))
} }
func downloadFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func downloadFile(bot *coolq.CQBot, p resultGetter) global.MSG {
headers := map[string]string{} headers := map[string]string{}
headersToken := p.Get("headers") headersToken := p.Get("headers")
if headersToken.IsArray() { if headersToken.IsArray() {
@ -207,11 +208,11 @@ func downloadFile(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQDownloadFile(p.Get("url").Str, headers, int(p.Get("thread_count").Int())) return bot.CQDownloadFile(p.Get("url").Str, headers, int(p.Get("thread_count").Int()))
} }
func getGroupHonorInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupHonorInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str) return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str)
} }
func setRestart(_ *coolq.CQBot, _ resultGetter) coolq.MSG { func setRestart(_ *coolq.CQBot, _ resultGetter) global.MSG {
/* /*
var delay int64 var delay int64
delay = p.Get("delay").Int() delay = p.Get("delay").Int()
@ -223,115 +224,115 @@ func setRestart(_ *coolq.CQBot, _ resultGetter) coolq.MSG {
Restart <- struct{}{} Restart <- struct{}{}
}(delay) }(delay)
*/ */
return coolq.MSG{"data": nil, "retcode": 99, "msg": "restart un-supported now", "wording": "restart函数暂不兼容", "status": "failed"} return global.MSG{"data": nil, "retcode": 99, "msg": "restart un-supported now", "wording": "restart函数暂不兼容", "status": "failed"}
} }
func canSendImage(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func canSendImage(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQCanSendImage() return bot.CQCanSendImage()
} }
func canSendRecord(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func canSendRecord(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQCanSendRecord() return bot.CQCanSendRecord()
} }
func getStrangerInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getStrangerInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetStrangerInfo(p.Get("user_id").Int()) return bot.CQGetStrangerInfo(p.Get("user_id").Int())
} }
func getStatus(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getStatus(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetStatus() return bot.CQGetStatus()
} }
func getVersionInfo(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getVersionInfo(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetVersionInfo() return bot.CQGetVersionInfo()
} }
func getGroupSystemMSG(bot *coolq.CQBot, _ resultGetter) coolq.MSG { func getGroupSystemMSG(bot *coolq.CQBot, _ resultGetter) global.MSG {
return bot.CQGetGroupSystemMessages() return bot.CQGetGroupSystemMessages()
} }
func getGroupFileSystemInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFileSystemInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupFileSystemInfo(p.Get("group_id").Int()) return bot.CQGetGroupFileSystemInfo(p.Get("group_id").Int())
} }
func getGroupRootFiles(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupRootFiles(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupRootFiles(p.Get("group_id").Int()) return bot.CQGetGroupRootFiles(p.Get("group_id").Int())
} }
func getGroupFilesByFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFilesByFolder(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupFilesByFolderID(p.Get("group_id").Int(), p.Get("folder_id").Str) return bot.CQGetGroupFilesByFolderID(p.Get("group_id").Int(), p.Get("folder_id").Str)
} }
func getGroupFileURL(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupFileURL(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupFileURL(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("busid").Int())) return bot.CQGetGroupFileURL(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("busid").Int()))
} }
func uploadGroupFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func uploadGroupFile(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQUploadGroupFile(p.Get("group_id").Int(), p.Get("file").Str, p.Get("name").Str, p.Get("folder").Str) return bot.CQUploadGroupFile(p.Get("group_id").Int(), p.Get("file").Str, p.Get("name").Str, p.Get("folder").Str)
} }
func groupFileCreateFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func groupFileCreateFolder(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileCreateFolder(p.Get("group_id").Int(), p.Get("folder_id").Str, p.Get("name").Str) return bot.CQGroupFileCreateFolder(p.Get("group_id").Int(), p.Get("folder_id").Str, p.Get("name").Str)
} }
func deleteGroupFolder(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteGroupFolder(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileDeleteFolder(p.Get("group_id").Int(), p.Get("folder_id").Str) return bot.CQGroupFileDeleteFolder(p.Get("group_id").Int(), p.Get("folder_id").Str)
} }
func deleteGroupFile(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteGroupFile(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGroupFileDeleteFile(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("bus_id").Int())) return bot.CQGroupFileDeleteFile(p.Get("group_id").Int(), p.Get("file_id").Str, int32(p.Get("bus_id").Int()))
} }
func getGroupMsgHistory(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupMsgHistory(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetGroupMessageHistory(p.Get("group_id").Int(), p.Get("message_seq").Int()) return bot.CQGetGroupMessageHistory(p.Get("group_id").Int(), p.Get("message_seq").Int())
} }
func getVipInfo(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getVipInfo(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetVipInfo(p.Get("user_id").Int()) return bot.CQGetVipInfo(p.Get("user_id").Int())
} }
func reloadEventFilter(_ *coolq.CQBot, p resultGetter) coolq.MSG { func reloadEventFilter(_ *coolq.CQBot, p resultGetter) global.MSG {
addFilter(p.Get("file").String()) addFilter(p.Get("file").String())
return coolq.OK(nil) return coolq.OK(nil)
} }
func getGroupAtAllRemain(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getGroupAtAllRemain(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetAtAllRemain(p.Get("group_id").Int()) return bot.CQGetAtAllRemain(p.Get("group_id").Int())
} }
func ocrImage(bot *coolq.CQBot, p resultGetter) coolq.MSG { func ocrImage(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQOcrImage(p.Get("image").Str) return bot.CQOcrImage(p.Get("image").Str)
} }
func getOnlineClients(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getOnlineClients(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetOnlineClients(p.Get("no_cache").Bool()) return bot.CQGetOnlineClients(p.Get("no_cache").Bool())
} }
func getWordSlices(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getWordSlices(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetWordSlices(p.Get("content").Str) return bot.CQGetWordSlices(p.Get("content").Str)
} }
func setGroupPortrait(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupPortrait(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetGroupPortrait(p.Get("group_id").Int(), p.Get("file").String(), p.Get("cache").String()) return bot.CQSetGroupPortrait(p.Get("group_id").Int(), p.Get("file").String(), p.Get("cache").String())
} }
func setEssenceMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setEssenceMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetEssenceMessage(int32(p.Get("message_id").Int())) return bot.CQSetEssenceMessage(int32(p.Get("message_id").Int()))
} }
func deleteEssenceMSG(bot *coolq.CQBot, p resultGetter) coolq.MSG { func deleteEssenceMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQDeleteEssenceMessage(int32(p.Get("message_id").Int())) return bot.CQDeleteEssenceMessage(int32(p.Get("message_id").Int()))
} }
func getEssenceMsgList(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getEssenceMsgList(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetEssenceMessageList(p.Get("group_id").Int()) return bot.CQGetEssenceMessageList(p.Get("group_id").Int())
} }
func checkURLSafely(bot *coolq.CQBot, p resultGetter) coolq.MSG { func checkURLSafely(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQCheckURLSafely(p.Get("url").String()) return bot.CQCheckURLSafely(p.Get("url").String())
} }
func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) global.MSG {
obj := p.Get("anonymous") obj := p.Get("anonymous")
flag := p.Get("anonymous_flag") flag := p.Get("anonymous_flag")
if !flag.Exists() { if !flag.Exists() {
@ -346,24 +347,24 @@ func setGroupAnonymousBan(bot *coolq.CQBot, p resultGetter) coolq.MSG {
return bot.CQSetGroupAnonymousBan(p.Get("group_id").Int(), flag.String(), int32(p.Get("duration").Int())) return bot.CQSetGroupAnonymousBan(p.Get("group_id").Int(), flag.String(), int32(p.Get("duration").Int()))
} }
func handleQuickOperation(bot *coolq.CQBot, p resultGetter) coolq.MSG { func handleQuickOperation(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation")) return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation"))
} }
func getModelShow(bot *coolq.CQBot, p resultGetter) coolq.MSG { func getModelShow(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQGetModelShow(p.Get("model").String()) return bot.CQGetModelShow(p.Get("model").String())
} }
func setModelShow(bot *coolq.CQBot, p resultGetter) coolq.MSG { func setModelShow(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQSetModelShow(p.Get("model").String(), p.Get("model_show").String()) return bot.CQSetModelShow(p.Get("model").String(), p.Get("model_show").String())
} }
func markMSGAsRead(bot *coolq.CQBot, p resultGetter) coolq.MSG { func markMSGAsRead(bot *coolq.CQBot, p resultGetter) global.MSG {
return bot.CQMarkMessageAsRead(int32(p.Get("message_id").Int())) return bot.CQMarkMessageAsRead(int32(p.Get("message_id").Int()))
} }
// API 是go-cqhttp当前支持的所有api的映射表 // API 是go-cqhttp当前支持的所有api的映射表
var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{ var API = map[string]func(*coolq.CQBot, resultGetter) global.MSG{
"get_login_info": getLoginInfo, "get_login_info": getLoginInfo,
"get_friend_list": getFriendList, "get_friend_list": getFriendList,
"get_unidirectional_friend_list": getUnidirectionalFriendList, "get_unidirectional_friend_list": getUnidirectionalFriendList,
@ -430,7 +431,7 @@ var API = map[string]func(*coolq.CQBot, resultGetter) coolq.MSG{
"mark_msg_as_read": markMSGAsRead, "mark_msg_as_read": markMSGAsRead,
} }
func (api *apiCaller) callAPI(action string, p resultGetter) coolq.MSG { func (api *apiCaller) callAPI(action string, p resultGetter) global.MSG {
for _, fn := range api.handlers { for _, fn := range api.handlers {
if ret := fn(action, p); ret != nil { if ret := fn(action, p); ret != nil {
return ret return ret

View File

@ -1,2 +1,13 @@
// Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体 // Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
package server package server
import "github.com/Mrs4s/go-cqhttp/modules/servers"
// 注册
func init() {
servers.Register("http", runHTTP)
servers.Register("ws", runWSServer)
servers.Register("ws-reverse", runWSClient)
servers.Register("pprof", runPprof)
servers.Register("lambda", runLambda)
}

View File

@ -8,20 +8,23 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"math/rand"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"strconv"
"strings" "strings"
"time" "time"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/guonaihong/gout"
"github.com/guonaihong/gout/dataflow"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
type httpServer struct { type httpServer struct {
@ -114,14 +117,21 @@ func (s *httpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request
return return
} }
action := strings.TrimPrefix(request.URL.Path, "/") var response global.MSG
action = strings.TrimSuffix(action, "_async") if base.AcceptOneBotV12HTTPEndPoint && request.URL.Path == "/" {
log.Debugf("HTTPServer接收到API调用: %v", action) action := strings.TrimSuffix(ctx.Get("action").Str, "_async")
ret := s.api.callAPI(action, &ctx) log.Debugf("HTTPServer接收到API调用: %v", action)
response = s.api.callAPI(action, ctx.Get("params"))
} else {
action := strings.TrimPrefix(request.URL.Path, "/")
action = strings.TrimSuffix(action, "_async")
log.Debugf("HTTPServer接收到API调用: %v", action)
response = s.api.callAPI(action, &ctx)
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8") writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(http.StatusOK) writer.WriteHeader(http.StatusOK)
_ = json.NewEncoder(writer).Encode(ret) _ = json.NewEncoder(writer).Encode(response)
} }
func checkAuth(req *http.Request, token string) int { func checkAuth(req *http.Request, token string) int {
@ -149,16 +159,19 @@ func checkAuth(req *http.Request, token string) int {
} }
} }
// RunHTTPServerAndClients 启动HTTP服务器与HTTP上报客户端 // runHTTP 启动HTTP服务器与HTTP上报客户端
func RunHTTPServerAndClients(bot *coolq.CQBot, conf *config.HTTPServer) { func runHTTP(bot *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.HTTPServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取http配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
var (
s = new(httpServer) var addr string
addr string s := &httpServer{accessToken: conf.AccessToken}
)
s.accessToken = conf.AccessToken
if conf.Host == "" || conf.Port == 0 { if conf.Host == "" || conf.Port == 0 {
goto client goto client
} }
@ -211,7 +224,6 @@ func (c HTTPClient) Run() {
} }
func (c *HTTPClient) onBotPushEvent(e *coolq.Event) { func (c *HTTPClient) onBotPushEvent(e *coolq.Event) {
var res string
if c.filter != "" { if c.filter != "" {
filter := findFilter(c.filter) filter := findFilter(c.filter)
if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) { if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) {
@ -220,40 +232,51 @@ func (c *HTTPClient) onBotPushEvent(e *coolq.Event) {
} }
} }
err := gout.POST(c.addr).SetJSON(e.JSONBytes()).BindBody(&res).SetHeader(func() gout.H { client := http.Client{Timeout: time.Second * time.Duration(c.timeout)}
h := gout.H{ req, _ := http.NewRequest("POST", c.addr, nil)
"X-Self-ID": c.bot.Client.Uin, req.Header.Set("X-Self-ID", strconv.FormatInt(c.bot.Client.Uin, 10))
"User-Agent": "CQHttp/4.15.0", req.Header.Set("User-Agent", "CQHttp/4.15.0")
if c.secret != "" {
mac := hmac.New(sha1.New, []byte(c.secret))
_, _ = mac.Write(e.JSONBytes())
req.Header.Set("X-Signature", "sha1="+hex.EncodeToString(mac.Sum(nil)))
}
if c.apiPort != 0 {
req.Header.Set("X-API-Port", strconv.FormatInt(int64(c.apiPort), 10))
}
var res *http.Response
var err error
const maxAttemptTimes = 5
for i := 0; i <= maxAttemptTimes; i++ {
res, err = client.Do(req)
if err == nil {
//goland:noinspection GoDeferInLoop
defer res.Body.Close()
break
} }
if c.secret != "" { if i != maxAttemptTimes {
mac := hmac.New(sha1.New, []byte(c.secret)) log.Warnf("上报 Event 数据到 %v 失败: %v 将进行第 %d 次重试", c.addr, err, i+1)
_, err := mac.Write(e.JSONBytes())
if err != nil {
log.Error(err)
return nil
}
h["X-Signature"] = "sha1=" + hex.EncodeToString(mac.Sum(nil))
} }
if c.apiPort != 0 { const maxWait = int64(time.Second * 3)
h["X-API-Port"] = c.apiPort const minWait = int64(time.Millisecond * 500)
} wait := rand.Int63n(maxWait-minWait) + minWait
return h time.Sleep(time.Duration(wait))
}()).SetTimeout(time.Second * time.Duration(c.timeout)).F().Retry().Attempt(5). }
WaitTime(time.Millisecond * 500).MaxWaitTime(time.Second * 5).
Func(func(con *dataflow.Context) error {
if con.Error != nil {
log.Warnf("上报Event到 HTTP 服务器 %v 时出现错误: %v 将重试.", c.addr, con.Error)
return con.Error
}
return nil
}).Do()
if err != nil { if err != nil {
log.Warnf("上报Event数据 %s 到 %v 失败: %v", e.JSONBytes(), c.addr, err) log.Warnf("上报Event数据 %s 到 %v 失败: %v", e.JSONBytes(), c.addr, err)
return return
} }
log.Debugf("上报Event数据 %s 到 %v", e.JSONBytes(), c.addr) log.Debugf("上报Event数据 %s 到 %v", e.JSONBytes(), c.addr)
if gjson.Valid(res) {
c.bot.CQHandleQuickOperation(gjson.Parse(e.JSONString()), gjson.Parse(res)) r, err := io.ReadAll(res.Body)
if err != nil {
return
}
if gjson.ValidBytes(r) {
c.bot.CQHandleQuickOperation(gjson.Parse(e.JSONString()), gjson.ParseBytes(r))
} }
} }

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"os" "os"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
@ -23,7 +22,7 @@ var (
func rateLimit(frequency float64, bucketSize int) handler { func rateLimit(frequency float64, bucketSize int) handler {
limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize) limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize)
return func(_ string, _ resultGetter) coolq.MSG { return func(_ string, _ resultGetter) global.MSG {
_ = limiter.Wait(context.Background()) _ = limiter.Wait(context.Background())
return nil return nil
} }
@ -71,12 +70,12 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
} }
cond.Signal() cond.Signal()
}) })
return func(action string, p resultGetter) coolq.MSG { return func(action string, p resultGetter) global.MSG {
if action != "get_updates" { if action != "get_updates" {
return nil return nil
} }
var ( var (
ok int32 once sync.Once
ch = make(chan []interface{}, 1) ch = make(chan []interface{}, 1)
timeout = time.Duration(p.Get("timeout").Int()) * time.Second timeout = time.Duration(p.Get("timeout").Int()) * time.Second
) )
@ -87,7 +86,7 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
if queue.Len() == 0 { if queue.Len() == 0 {
cond.Wait() cond.Wait()
} }
if atomic.CompareAndSwapInt32(&ok, 0, 1) { once.Do(func() {
limit := int(p.Get("limit").Int()) limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit { if limit <= 0 || queue.Len() < limit {
limit = queue.Len() limit = queue.Len()
@ -97,12 +96,12 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
ret[i] = queue.Remove(queue.Front()) ret[i] = queue.Remove(queue.Front())
} }
ch <- ret ch <- ret
} })
}() }()
if timeout != 0 { if timeout != 0 {
select { select {
case <-time.After(timeout): case <-time.After(timeout):
atomic.StoreInt32(&ok, 1) once.Do(func() {})
return coolq.OK([]interface{}{}) return coolq.OK([]interface{}{})
case ret := <-ch: case ret := <-ch:
return coolq.OK(ret) return coolq.OK(ret)

View File

@ -8,15 +8,23 @@ import (
"time" "time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/modules/config"
) )
// RunPprofServer 启动 pprof 性能分析服务器 // runPprof 启动 pprof 性能分析服务器
func RunPprofServer(conf *config.PprofServer) { func runPprof(_ *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.PprofServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取pprof配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port) addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index) mux.HandleFunc("/debug/pprof/", pprof.Index)

View File

@ -13,10 +13,11 @@ import (
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/modules/config"
) )
type lambdaClient struct { type lambdaClient struct {
@ -77,8 +78,17 @@ func (l *lambdaResponseWriter) WriteHeader(statusCode int) {
var cli *lambdaClient var cli *lambdaClient
// RunLambdaClient type: [scf,aws] // runLambda type: [scf,aws]
func RunLambdaClient(bot *coolq.CQBot, conf *config.LambdaServer) { func runLambda(bot *coolq.CQBot, node yaml.Node) {
var conf config.LambdaServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取lambda配置失败 :", err)
fallthrough
case conf.Disabled:
return
}
cli = &lambdaClient{ cli = &lambdaClient{
lambdaType: conf.Type, lambdaType: conf.Type,
client: http.Client{Timeout: 0}, client: http.Client{Timeout: 0},

View File

@ -10,9 +10,11 @@ import (
"sync" "sync"
"time" "time"
"gopkg.in/yaml.v3"
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/global/config" "github.com/Mrs4s/go-cqhttp/modules/config"
"github.com/Mrs4s/MiraiGo/utils" "github.com/Mrs4s/MiraiGo/utils"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
@ -54,14 +56,20 @@ var upgrader = websocket.Upgrader{
}, },
} }
// RunWebSocketServer 运行一个正向WS server // runWSServer 运行一个正向WS server
func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) { func runWSServer(b *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.WebsocketServer
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取正向Websocket配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
s := &webSocketServer{ s := &webSocketServer{
bot: b, bot: b,
conf: conf, conf: &conf,
token: conf.AccessToken, token: conf.AccessToken,
filter: conf.Filter, filter: conf.Filter,
} }
@ -80,14 +88,20 @@ func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) {
}() }()
} }
// RunWebSocketClient 运行一个向WS client // runWSClient 运行一个反向向WS client
func RunWebSocketClient(b *coolq.CQBot, conf *config.WebsocketReverse) { func runWSClient(b *coolq.CQBot, node yaml.Node) {
if conf.Disabled { var conf config.WebsocketReverse
switch err := node.Decode(&conf); {
case err != nil:
log.Warn("读取反向Websocket配置失败 :", err)
fallthrough
case conf.Disabled:
return return
} }
c := &websocketClient{ c := &websocketClient{
bot: b, bot: b,
conf: conf, conf: &conf,
token: conf.AccessToken, token: conf.AccessToken,
filter: conf.Filter, filter: conf.Filter,
} }