mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-06-29 19:43:24 +00:00
Compare commits
23 Commits
v1.0.0-bet
...
dev.ws
Author | SHA1 | Date | |
---|---|---|---|
47cdc20d45 | |||
1771cda11c | |||
67f0ea914d | |||
446f624a37 | |||
19fd331c46 | |||
b8c7941dc8 | |||
ce944539c1 | |||
4b99f64b56 | |||
1337d3f1f3 | |||
ddd51e6ca3 | |||
35b7b8909e | |||
cf21e81016 | |||
cd141d7d37 | |||
1a195278cf | |||
5acb01c1a3 | |||
883fca089d | |||
110982651d | |||
2cf136d031 | |||
f2ed46d6ce | |||
87754111ce | |||
1db219fce0 | |||
5cafaea082 | |||
60d5f4d386 |
@ -27,7 +27,7 @@ builds:
|
||||
flags:
|
||||
- -trimpath
|
||||
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
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
|
@ -14,6 +14,8 @@ RUN set -ex \
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk add --no-cache ffmpeg
|
||||
|
||||
COPY --from=builder /build/cqhttp /usr/bin/cqhttp
|
||||
RUN chmod +x /usr/bin/cqhttp
|
||||
|
||||
|
24
coolq/api.go
24
coolq/api.go
@ -10,7 +10,6 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@ -23,21 +22,10 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"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 获取登录号信息
|
||||
//
|
||||
// https://git.io/Jtz1I
|
||||
@ -958,7 +946,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) global
|
||||
reply := operation.Get("reply")
|
||||
|
||||
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"
|
||||
if at && reply.IsArray() {
|
||||
// 在 reply 数组头部插入CQ码
|
||||
@ -1388,8 +1376,8 @@ func (bot *CQBot) CQGetVersionInfo() global.MSG {
|
||||
wd, _ := os.Getwd()
|
||||
return OK(global.MSG{
|
||||
"app_name": "go-cqhttp",
|
||||
"app_version": Version,
|
||||
"app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", Version, runtime.GOOS, runtime.GOARCH, runtime.Version()),
|
||||
"app_version": base.Version,
|
||||
"app_full_name": fmt.Sprintf("go-cqhttp-%s_%s_%s-%s", base.Version, runtime.GOOS, runtime.GOARCH, runtime.Version()),
|
||||
"protocol_version": "v11",
|
||||
"coolq_directory": wd,
|
||||
"coolq_edition": "pro",
|
||||
@ -1399,7 +1387,7 @@ func (bot *CQBot) CQGetVersionInfo() global.MSG {
|
||||
"plugin_build_configuration": "release",
|
||||
"runtime_version": runtime.Version(),
|
||||
"runtime_os": runtime.GOOS,
|
||||
"version": Version,
|
||||
"version": base.Version,
|
||||
"protocol": func() int {
|
||||
switch client.SystemDeviceInfo.Protocol {
|
||||
case client.IPad:
|
||||
|
78
coolq/bot.go
78
coolq/bot.go
@ -14,8 +14,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gabriel-vasile/mimetype"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
"github.com/Mrs4s/MiraiGo/client"
|
||||
"github.com/Mrs4s/MiraiGo/message"
|
||||
@ -26,7 +24,8 @@ import (
|
||||
"github.com/syndtr/goleveldb/leveldb/opt"
|
||||
|
||||
"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实例相关配置
|
||||
@ -69,42 +68,13 @@ func (e *Event) JSONString() string {
|
||||
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实例
|
||||
func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
|
||||
func NewQQBot(cli *client.QQClient) *CQBot {
|
||||
bot := &CQBot{
|
||||
Client: cli,
|
||||
}
|
||||
enableLevelDB := false
|
||||
node, ok := conf.Database["leveldb"]
|
||||
node, ok := base.Database["leveldb"]
|
||||
if ok {
|
||||
lconf := new(config.LevelDBConfig)
|
||||
_ = node.Decode(lconf)
|
||||
@ -126,7 +96,7 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
|
||||
}
|
||||
bot.Client.OnPrivateMessage(bot.privateMessageEvent)
|
||||
bot.Client.OnGroupMessage(bot.groupMessageEvent)
|
||||
if conf.Message.ReportSelfMessage {
|
||||
if base.ReportSelfMessage {
|
||||
bot.Client.OnSelfPrivateMessage(bot.privateMessageEvent)
|
||||
bot.Client.OnSelfGroupMessage(bot.groupMessageEvent)
|
||||
}
|
||||
@ -151,15 +121,11 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
|
||||
bot.Client.OnOtherClientStatusChanged(bot.otherClientStatusChangedEvent)
|
||||
bot.Client.OnGroupDigest(bot.groupEssenceMsg)
|
||||
go func() {
|
||||
i := conf.Heartbeat.Interval
|
||||
if i < 0 || conf.Heartbeat.Disabled {
|
||||
if base.HeartbeatInterval == 0 {
|
||||
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
|
||||
return
|
||||
}
|
||||
if i == 0 {
|
||||
i = 5
|
||||
}
|
||||
t := time.NewTicker(time.Second * time.Duration(i))
|
||||
t := time.NewTicker(base.HeartbeatInterval)
|
||||
for {
|
||||
<-t.C
|
||||
bot.dispatchEventMessage(global.MSG{
|
||||
@ -168,7 +134,7 @@ func NewQQBot(cli *client.QQClient, conf *config.Config) *CQBot {
|
||||
"post_type": "meta_event",
|
||||
"meta_event_type": "heartbeat",
|
||||
"status": bot.CQGetStatus()["data"],
|
||||
"interval": 1000 * i,
|
||||
"interval": base.HeartbeatInterval.Milliseconds(),
|
||||
})
|
||||
}
|
||||
}()
|
||||
@ -208,7 +174,7 @@ func (bot *CQBot) UploadLocalImageAsGroup(groupCode int64, img *LocalImageElemen
|
||||
defer func() { _ = f.Close() }()
|
||||
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)
|
||||
}
|
||||
i, err = bot.Client.UploadGroupImage(groupCode, img.Stream)
|
||||
@ -243,7 +209,7 @@ func (bot *CQBot) UploadLocalImageAsPrivate(userID int64, img *LocalImageElement
|
||||
defer func() { _ = f.Close() }()
|
||||
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)
|
||||
}
|
||||
i, err = bot.Client.UploadPrivateImage(userID, img.Stream)
|
||||
@ -296,7 +262,7 @@ func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) int
|
||||
}
|
||||
m.Elements = 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 {
|
||||
log.Warnf("群消息发送失败: 账号可能被风控.")
|
||||
return -1
|
||||
@ -614,25 +580,3 @@ func (bot *CQBot) uploadMedia(raw message.IMessageElement, target int64, group b
|
||||
}
|
||||
return nil, errors.New("unsupported message element type")
|
||||
}
|
||||
|
||||
// IsLawfulImage 判断给定流是否为合法图片
|
||||
// 返回 是否合法, 实际Mime
|
||||
// 判断后会自动将 Stream Seek 至 0
|
||||
func IsLawfulImage(r io.ReadSeeker) (bool, string) {
|
||||
if SkipMimeScan {
|
||||
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()
|
||||
}
|
||||
|
@ -20,12 +20,12 @@ import (
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
"github.com/Mrs4s/MiraiGo/message"
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
"github.com/gabriel-vasile/mimetype"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"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/param"
|
||||
)
|
||||
|
||||
/*
|
||||
@ -34,18 +34,6 @@ var typeReg = regexp.MustCompile(`\[CQ:(\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 (
|
||||
maxImageSize = 1024 * 1024 * 30 // 30MB
|
||||
maxVideoSize = 1024 * 1024 * 100 // 100MB
|
||||
@ -137,7 +125,7 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []global.MSG)
|
||||
if rid == 0 {
|
||||
rid = replyElem.Sender
|
||||
}
|
||||
if ExtraReplyData {
|
||||
if base.ExtraReplyData {
|
||||
r = append(r, global.MSG{
|
||||
"type": "reply",
|
||||
"data": map[string]string{
|
||||
@ -159,7 +147,7 @@ func ToArrayMessage(e []message.IMessageElement, groupID int64) (r []global.MSG)
|
||||
var m global.MSG
|
||||
switch o := elem.(type) {
|
||||
case *message.ReplyElement:
|
||||
if RemoveReplyAt && i+1 < len(e) {
|
||||
if base.RemoveReplyAt && i+1 < len(e) {
|
||||
elem, ok := e[i+1].(*message.AtElement)
|
||||
if ok && elem.Target == o.Sender {
|
||||
e[i+1] = nil
|
||||
@ -279,7 +267,7 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
|
||||
if rid == 0 {
|
||||
rid = replyElem.Sender
|
||||
}
|
||||
if ExtraReplyData {
|
||||
if base.ExtraReplyData {
|
||||
write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]",
|
||||
toGlobalID(rid, replyElem.ReplySeq),
|
||||
replyElem.ReplySeq, replyElem.Sender, replyElem.Time,
|
||||
@ -291,7 +279,7 @@ func ToStringMessage(e []message.IMessageElement, groupID int64, isRaw ...bool)
|
||||
for i, elem := range e {
|
||||
switch o := elem.(type) {
|
||||
case *message.ReplyElement:
|
||||
if RemoveReplyAt && len(e) > i+1 {
|
||||
if base.RemoveReplyAt && len(e) > i+1 {
|
||||
elem, ok := e[i+1].(*message.AtElement)
|
||||
if ok && elem.Target == o.Sender {
|
||||
e[i+1] = nil
|
||||
@ -454,7 +442,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
|
||||
org += "," + k + "=" + v
|
||||
}
|
||||
org += "]"
|
||||
if !IgnoreInvalidCQCode {
|
||||
if !base.IgnoreInvalidCQCode {
|
||||
log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err)
|
||||
r = append(r, message.NewText(org))
|
||||
} else {
|
||||
@ -476,8 +464,8 @@ func (bot *CQBot) ConvertStringMessage(raw string, isGroup bool) (r []message.IM
|
||||
i++
|
||||
}
|
||||
if i > 0 {
|
||||
if SplitURL {
|
||||
for _, txt := range global.SplitURL(CQCodeUnescapeText(raw[:i])) {
|
||||
if base.SplitURL {
|
||||
for _, txt := range param.SplitURL(CQCodeUnescapeText(raw[:i])) {
|
||||
r = append(r, message.NewText(txt))
|
||||
}
|
||||
} else {
|
||||
@ -662,9 +650,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) {
|
||||
switch t {
|
||||
case "text":
|
||||
if SplitURL {
|
||||
if base.SplitURL {
|
||||
var ret []message.IMessageElement
|
||||
for _, text := range global.SplitURL(d["text"]) {
|
||||
for _, text := range param.SplitURL(d["text"]) {
|
||||
ret = append(ret, message.NewText(text))
|
||||
}
|
||||
return ret, nil
|
||||
@ -725,7 +713,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &message.VoiceElement{Data: codec.RecodeTo24K(data)}, nil
|
||||
return &message.VoiceElement{Data: base.ResampleSilk(data)}, nil
|
||||
case "record":
|
||||
f := d["file"]
|
||||
data, err := global.FindFile(f, d["cache"], global.VoicePath)
|
||||
@ -735,17 +723,10 @@ func (bot *CQBot) ToElement(t string, d map[string]string, isGroup bool) (m inte
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !SkipMimeScan && !global.IsAMRorSILK(data) {
|
||||
mt := mimetype.Detect(data)
|
||||
lawful := false
|
||||
for _, lt := range lawfulAudioTypes {
|
||||
if mt.Is(lt) {
|
||||
lawful = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !global.IsAMRorSILK(data) {
|
||||
lawful, mt := base.IsLawfulAudio(bytes.NewReader(data))
|
||||
if !lawful {
|
||||
return nil, errors.New("audio type error: " + mt.String())
|
||||
return nil, errors.New("audio type error: " + mt)
|
||||
}
|
||||
}
|
||||
if !global.IsAMRorSILK(data) {
|
||||
@ -1117,7 +1098,7 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
|
||||
return &LocalImageElement{File: fu.Path}, nil
|
||||
}
|
||||
if strings.HasPrefix(f, "base64") && !video {
|
||||
b, err := global.Base64DecodeString(strings.TrimPrefix(f, "base64://"))
|
||||
b, err := param.Base64DecodeString(strings.TrimPrefix(f, "base64://"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/internal/base"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/binary"
|
||||
"github.com/Mrs4s/MiraiGo/client"
|
||||
@ -16,18 +17,11 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var format = "string"
|
||||
|
||||
// SetMessageFormat 设置消息上报格式,默认为string
|
||||
func SetMessageFormat(f string) {
|
||||
format = f
|
||||
}
|
||||
|
||||
// ToFormattedMessage 将给定[]message.IMessageElement转换为通过coolq.SetMessageFormat所定义的消息上报格式
|
||||
func ToFormattedMessage(e []message.IMessageElement, groupID int64, isRaw ...bool) (r interface{}) {
|
||||
if format == "string" {
|
||||
if base.PostFormat == "string" {
|
||||
r = ToStringMessage(e, groupID, isRaw...)
|
||||
} else if format == "array" {
|
||||
} else if base.PostFormat == "array" {
|
||||
r = ToArrayMessage(e, groupID)
|
||||
}
|
||||
return
|
||||
|
@ -154,7 +154,7 @@ database: # 数据库相关设置
|
||||
|
||||
> 注4:关闭心跳服务可能引起断线,请谨慎关闭
|
||||
|
||||
> 注5:关于MINE扫描, 详见[MINE](file.md#MINE)
|
||||
> 注5:关于MIME扫描, 详见[MIME](file.md#MIME)
|
||||
|
||||
## 在线状态
|
||||
|
||||
|
@ -39,11 +39,11 @@ go-cqhttp 默认生成的文件树如下所示:
|
||||
| 0x14 | string | 图片原名(QQ内部ID) |
|
||||
| 0x14 + 原名长度 | string | 图片下载链接 |
|
||||
|
||||
# MINE
|
||||
# MIME
|
||||
|
||||
启用MINE检查可以及时发现媒体资源格式错误引起的上传失败(通常表现为,请求网页图片,但服务端返回404.html)
|
||||
|
||||
在配置文件中设置 `skip-mine-scan: false`后 ,go-cqhttp 会在上传媒体资源(视频暂不支持)前对MINE进行检查,
|
||||
在配置文件中设置 `skip-mine-scan: false`后 ,go-cqhttp 会在上传媒体资源(视频暂不支持)前对MIME进行检查,
|
||||
详细允许类型如下所示:
|
||||
|
||||
图片:
|
||||
|
@ -7,9 +7,9 @@ import (
|
||||
"os/exec"
|
||||
"path"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global/codec"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/internal/base"
|
||||
)
|
||||
|
||||
// EncoderSilk 将音频编码为Silk
|
||||
@ -23,7 +23,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
|
||||
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
|
||||
return os.ReadFile(silkPath)
|
||||
}
|
||||
slk, err := codec.EncodeToSilk(data, tempName, true)
|
||||
slk, err := base.EncodeSilk(data, tempName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "encode silk failed")
|
||||
}
|
||||
|
@ -1,2 +0,0 @@
|
||||
// Package codec Slik编码核心模块
|
||||
package codec
|
@ -1,4 +0,0 @@
|
||||
package codec
|
||||
|
||||
// Debug mode controls the ffmpeg output.
|
||||
var Debug bool
|
@ -15,6 +15,8 @@ import (
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/internal/param"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -97,7 +99,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
|
||||
return nil, err
|
||||
}
|
||||
case strings.HasPrefix(file, "base64"):
|
||||
data, err = Base64DecodeString(strings.TrimPrefix(file, "base64://"))
|
||||
data, err = param.Base64DecodeString(strings.TrimPrefix(file, "base64://"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -12,22 +12,22 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/guonaihong/gout"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/internal/base"
|
||||
)
|
||||
|
||||
var (
|
||||
client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: func(request *http.Request) (u *url.URL, e error) {
|
||||
if Proxy == "" {
|
||||
if base.Proxy == "" {
|
||||
return http.ProxyFromEnvironment(request)
|
||||
}
|
||||
return url.Parse(Proxy)
|
||||
return url.Parse(base.Proxy)
|
||||
},
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxConnsPerHost: 0,
|
||||
@ -36,9 +36,6 @@ var (
|
||||
},
|
||||
}
|
||||
|
||||
// Proxy 存储Config.proxy_rewrite,用于设置代理
|
||||
Proxy string
|
||||
|
||||
// ErrOverSize 响应主体过大时返回此错误
|
||||
ErrOverSize = errors.New("oversize")
|
||||
|
||||
@ -249,22 +246,6 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
|
||||
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音乐上查找曲目信息
|
||||
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¬ice=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}}`)
|
||||
|
123
global/param.go
123
global/param.go
@ -1,64 +1,15 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
"github.com/segmentio/asm/base64"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// MSG 消息Map
|
||||
type MSG map[string]interface{}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// VersionNameCompare 检查版本名是否需要更新, 仅适用于 go-cqhttp 的版本命名规则
|
||||
//
|
||||
// 例: v0.9.29-fix2 == v0.9.29-fix2 -> false
|
||||
@ -93,77 +44,3 @@ func VersionNameCompare(current, remote string) bool {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
@ -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
|
||||
}
|
8
go.mod
8
go.mod
@ -9,9 +9,8 @@ require (
|
||||
github.com/Microsoft/go-winio v0.5.0
|
||||
github.com/Mrs4s/MiraiGo v0.0.0-20210916113136-0238b2382b82
|
||||
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/gorilla/websocket v1.4.2
|
||||
github.com/guonaihong/gout v0.2.4
|
||||
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
|
||||
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
|
||||
github.com/pkg/errors v0.9.1
|
||||
@ -26,13 +25,16 @@ require (
|
||||
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
|
||||
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
|
||||
nhooyr.io/websocket v1.8.7
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db // indirect
|
||||
github.com/google/uuid v1.1.1 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/jonboulle/clockwork v0.2.2 // indirect
|
||||
github.com/klauspost/compress v1.10.3 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.0.6 // indirect
|
||||
github.com/lestrrat-go/strftime v1.0.5 // indirect
|
||||
github.com/maruel/rs v0.0.0-20150922171536-2c81c4312fe4 // indirect
|
||||
@ -44,12 +46,10 @@ require (
|
||||
github.com/tidwall/match v1.0.3 // indirect
|
||||
github.com/tidwall/pretty v1.1.0 // indirect
|
||||
github.com/willf/bitset v1.2.0 // indirect
|
||||
golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125 // indirect
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // 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/mathutil v1.2.2 // indirect
|
||||
modernc.org/memory v1.0.4 // indirect
|
||||
|
31
go.sum
31
go.sum
@ -18,24 +18,33 @@ 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/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/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/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU=
|
||||
github.com/gin-gonic/gin v1.7.0/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
|
||||
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
|
||||
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
|
||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0=
|
||||
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
|
||||
github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=
|
||||
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=
|
||||
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
|
||||
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/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.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk=
|
||||
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.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
@ -57,10 +66,9 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
|
||||
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/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
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/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/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
|
||||
@ -69,6 +77,8 @@ github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGn
|
||||
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/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8=
|
||||
github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eTO0Q8=
|
||||
github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
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/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||
@ -132,12 +142,9 @@ github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLY
|
||||
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=
|
||||
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-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ=
|
||||
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/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-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
@ -146,8 +153,6 @@ golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73r
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/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-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-20210505024714-0287a6fb4125 h1:Ugb8sMTWuWRC3+sz5WeN/4kejDx9BvIwnPUiJBjJE+8=
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
@ -160,7 +165,6 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/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-20190412213103-97732733099d/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-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@ -178,6 +182,7 @@ 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.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs=
|
||||
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@ -228,3 +233,5 @@ modernc.org/mathutil v1.2.2 h1:+yFk8hBprV+4c0U9GjFtL+dV3N8hOJ8JCituQcMShFY=
|
||||
modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||
modernc.org/memory v1.0.4 h1:utMBrFcpnQDdNsmM6asmyH/FM9TqLPS7XF7otpJmrwM=
|
||||
modernc.org/memory v1.0.4/go.mod h1:nV2OApxradM3/OVbs2/0OsP6nPfakXpi50C7dcoHXlc=
|
||||
nhooyr.io/websocket v1.8.7 h1:usjR2uOr/zjjkVMy0lW+PPohFok7PCow5sDjLgX4P4g=
|
||||
nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0=
|
||||
|
37
internal/base/feature.go
Normal file
37
internal/base/feature.go
Normal 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
148
internal/base/flag.go
Normal 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
16
internal/base/version.go
Normal 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
|
||||
}
|
||||
}
|
130
internal/param/param.go
Normal file
130
internal/param/param.go
Normal 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)
|
||||
}
|
206
internal/selfupdate/update.go
Normal file
206
internal/selfupdate/update.go
Normal 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
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package update
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
@ -14,21 +14,21 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Update go-cqhttp自我更新
|
||||
func Update(url string, sum []byte) error {
|
||||
// update go-cqhttp自我更新
|
||||
func update(url string, sum []byte) error {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
wc := WriteSumCounter{
|
||||
Hash: sha256.New(),
|
||||
wc := writeSumCounter{
|
||||
hash: sha256.New(),
|
||||
}
|
||||
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(wc.Hash.Sum(nil), sum) {
|
||||
if !bytes.Equal(wc.hash.Sum(nil), sum) {
|
||||
return errors.New("文件已损坏")
|
||||
}
|
||||
gr, err := gzip.NewReader(bytes.NewReader(rsp))
|
||||
@ -42,7 +42,7 @@ func Update(url string, sum []byte) error {
|
||||
return err
|
||||
}
|
||||
if header.Name == "go-cqhttp" {
|
||||
err, _ := FromStream(tr)
|
||||
err, _ := fromStream(tr)
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return err
|
@ -1,4 +1,4 @@
|
||||
package update
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
@ -10,21 +10,21 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Update go-cqhttp自我更新
|
||||
func Update(url string, sum []byte) error {
|
||||
// update go-cqhttp自我更新
|
||||
func update(url string, sum []byte) error {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
wc := WriteSumCounter{
|
||||
Hash: sha256.New(),
|
||||
wc := writeSumCounter{
|
||||
hash: sha256.New(),
|
||||
}
|
||||
rsp, err := io.ReadAll(io.TeeReader(resp.Body, &wc))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(wc.Hash.Sum(nil), sum) {
|
||||
if !bytes.Equal(wc.hash.Sum(nil), sum) {
|
||||
return errors.New("文件已损坏")
|
||||
}
|
||||
reader, _ := zip.NewReader(bytes.NewReader(rsp), resp.ContentLength)
|
||||
@ -32,7 +32,7 @@ func Update(url string, sum []byte) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err, _ = FromStream(file)
|
||||
err, _ = fromStream(file)
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return err
|
4
login.go
4
login.go
@ -18,13 +18,13 @@ import (
|
||||
|
||||
var console = bufio.NewReader(os.Stdin)
|
||||
|
||||
var readLine = func() (str string) {
|
||||
func readLine() (str string) {
|
||||
str, _ = console.ReadString('\n')
|
||||
str = strings.TrimSpace(str)
|
||||
return
|
||||
}
|
||||
|
||||
var readLineTimeout = func(t time.Duration, de string) (str string) {
|
||||
func readLineTimeout(t time.Duration, de string) (str string) {
|
||||
r := make(chan string)
|
||||
go func() {
|
||||
select {
|
||||
|
409
main.go
409
main.go
@ -1,107 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/aes"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"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/client"
|
||||
"github.com/guonaihong/gout"
|
||||
para "github.com/fumiama/go-hide-param"
|
||||
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
"golang.org/x/term"
|
||||
|
||||
_ "github.com/Mrs4s/go-cqhttp/modules/mime" // mime检查模块
|
||||
"github.com/Mrs4s/go-cqhttp/modules/servers"
|
||||
_ "github.com/Mrs4s/go-cqhttp/modules/silk" // silk编码模块
|
||||
|
||||
"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/selfupdate"
|
||||
"github.com/Mrs4s/go-cqhttp/server"
|
||||
)
|
||||
|
||||
var (
|
||||
conf *config.Config
|
||||
isFastStart = false
|
||||
// PasswordHash 存储QQ密码哈希供登录使用
|
||||
PasswordHash [16]byte
|
||||
|
||||
// AccountToken 存储AccountToken供登录使用
|
||||
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,
|
||||
}
|
||||
)
|
||||
// 允许通过配置文件设置的状态列表
|
||||
var 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() {
|
||||
c := flag.String("c", config.DefaultConfigFile, "configuration filename")
|
||||
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()
|
||||
|
||||
base.Parse()
|
||||
switch {
|
||||
case *h:
|
||||
help()
|
||||
case *d:
|
||||
case base.LittleH:
|
||||
base.Help()
|
||||
case base.LittleD:
|
||||
server.Daemon()
|
||||
case *wd != "":
|
||||
resetWorkDir(*wd)
|
||||
}
|
||||
|
||||
// 通过-c 参数替换 配置文件路径
|
||||
config.DefaultConfigFile = *c
|
||||
conf = config.Get()
|
||||
if *debug {
|
||||
conf.Output.Debug = true
|
||||
}
|
||||
if conf.Output.Debug {
|
||||
log.SetReportCaller(true)
|
||||
codec.Debug = true
|
||||
case base.LittleWD != "":
|
||||
base.ResetWorkingDir()
|
||||
}
|
||||
base.Init()
|
||||
|
||||
rotateOptions := []rotatelogs.Option{
|
||||
rotatelogs.WithRotationTime(time.Hour * 24),
|
||||
}
|
||||
|
||||
if conf.Output.LogAging > 0 {
|
||||
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.WithMaxAge(base.LogAging))
|
||||
if base.LogForceNew {
|
||||
rotateOptions = append(rotateOptions, rotatelogs.ForceNewFile())
|
||||
}
|
||||
|
||||
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotateOptions...)
|
||||
if err != nil {
|
||||
log.Errorf("rotatelogs init err: %v", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(conf.Output.LogLevel)...))
|
||||
log.AddHook(global.NewLocalHook(w, global.LogFormat{}, global.GetLogLevel(base.LogLevel)...))
|
||||
|
||||
mkCacheDir := func(path string, _type string) {
|
||||
if !global.PathExists(path) {
|
||||
@ -122,20 +84,23 @@ func main() {
|
||||
switch arg[i] {
|
||||
case "update":
|
||||
if len(arg) > i+1 {
|
||||
selfUpdate(arg[i+1])
|
||||
selfupdate.SelfUpdate(arg[i+1])
|
||||
} else {
|
||||
selfUpdate("")
|
||||
selfupdate.SelfUpdate("")
|
||||
}
|
||||
case "key":
|
||||
if len(arg) > i+1 {
|
||||
byteKey = []byte(arg[i+1])
|
||||
p := i + 1
|
||||
if len(arg) > p {
|
||||
byteKey = []byte(arg[p])
|
||||
para.Hide(p)
|
||||
}
|
||||
case "faststart":
|
||||
isFastStart = true
|
||||
base.FastStart = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if terminal.RunningByDoubleClick() && !isFastStart {
|
||||
|
||||
if !base.FastStart && terminal.RunningByDoubleClick() {
|
||||
err := terminal.NoMoreDoubleClick()
|
||||
if err != nil {
|
||||
log.Errorf("遇到错误: %v", err)
|
||||
@ -144,17 +109,18 @@ func main() {
|
||||
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("账号密码未配置, 将使用二维码登录.")
|
||||
if !isFastStart {
|
||||
if !base.FastStart {
|
||||
log.Warn("将在 5秒 后继续.")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("当前版本:", coolq.Version)
|
||||
if conf.Output.Debug {
|
||||
log.Info("当前版本:", base.Version)
|
||||
if base.Debug {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
log.SetReportCaller(true)
|
||||
log.Warnf("已开启Debug模式.")
|
||||
log.Debugf("开发交流群: 192548878")
|
||||
}
|
||||
@ -171,22 +137,22 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
if conf.Account.Encrypt {
|
||||
if base.Account.Encrypt {
|
||||
if !global.PathExists("password.encrypt") {
|
||||
if conf.Account.Password == "" {
|
||||
if base.Account.Password == "" {
|
||||
log.Error("无法进行加密,请在配置文件中的添加密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
}
|
||||
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
|
||||
byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
|
||||
PasswordHash = md5.Sum([]byte(conf.Account.Password))
|
||||
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(PasswordHash[:], byteKey)), 0o644)
|
||||
base.PasswordHash = md5.Sum([]byte(base.Account.Password))
|
||||
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(base.PasswordHash[:], byteKey)), 0o644)
|
||||
log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
} else {
|
||||
if conf.Account.Password != "" {
|
||||
if base.Account.Password != "" {
|
||||
log.Error("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
|
||||
readLine()
|
||||
os.Exit(0)
|
||||
@ -218,12 +184,12 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
|
||||
}
|
||||
copy(PasswordHash[:], ph)
|
||||
copy(base.PasswordHash[:], ph)
|
||||
}
|
||||
} else {
|
||||
PasswordHash = md5.Sum([]byte(conf.Account.Password))
|
||||
} else if len(base.Account.Password) > 0 {
|
||||
base.PasswordHash = md5.Sum([]byte(base.Account.Password))
|
||||
}
|
||||
if !isFastStart {
|
||||
if !base.FastStart {
|
||||
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
@ -244,21 +210,20 @@ func main() {
|
||||
return "未知"
|
||||
}())
|
||||
cli = newClient()
|
||||
global.Proxy = conf.Message.ProxyRewrite
|
||||
isQRCodeLogin := (conf.Account.Uin == 0 || len(conf.Account.Password) == 0) && !conf.Account.Encrypt
|
||||
isQRCodeLogin := (base.Account.Uin == 0 || len(base.Account.Password) == 0) && !base.Account.Encrypt
|
||||
isTokenLogin := false
|
||||
saveToken := func() {
|
||||
AccountToken = cli.GenToken()
|
||||
_ = os.WriteFile("session.token", AccountToken, 0o644)
|
||||
base.AccountToken = cli.GenToken()
|
||||
_ = os.WriteFile("session.token", base.AccountToken, 0o644)
|
||||
}
|
||||
if global.PathExists("session.token") {
|
||||
token, err := os.ReadFile("session.token")
|
||||
if err == nil {
|
||||
if conf.Account.Uin != 0 {
|
||||
if base.Account.Uin != 0 {
|
||||
r := binary.NewReader(token)
|
||||
cu := r.ReadInt64()
|
||||
if cu != conf.Account.Uin {
|
||||
log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", conf.Account.Uin, cu)
|
||||
if cu != base.Account.Uin {
|
||||
log.Warnf("警告: 配置文件内的QQ号 (%v) 与缓存内的QQ号 (%v) 不相同", base.Account.Uin, cu)
|
||||
log.Warnf("1. 使用会话缓存继续.")
|
||||
log.Warnf("2. 删除会话缓存并重启.")
|
||||
log.Warnf("请选择: (5秒后自动选1)")
|
||||
@ -282,9 +247,9 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if conf.Account.Uin != 0 && PasswordHash != [16]byte{} {
|
||||
cli.Uin = conf.Account.Uin
|
||||
cli.PasswordMd5 = PasswordHash
|
||||
if base.Account.Uin != 0 && base.PasswordHash != [16]byte{} {
|
||||
cli.Uin = base.Account.Uin
|
||||
cli.PasswordMd5 = base.PasswordHash
|
||||
}
|
||||
if !isTokenLogin {
|
||||
if !isQRCodeLogin {
|
||||
@ -307,19 +272,19 @@ func main() {
|
||||
return
|
||||
}
|
||||
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 {
|
||||
if conf.Account.ReLogin.Disabled {
|
||||
if base.Reconnect.Disabled {
|
||||
log.Warnf("未启用自动重连, 将退出.")
|
||||
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重连次数超过限制, 停止")
|
||||
}
|
||||
times++
|
||||
if conf.Account.ReLogin.Interval > 0 {
|
||||
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", conf.Account.ReLogin.Interval, times, conf.Account.ReLogin.MaxTimes)
|
||||
time.Sleep(time.Second * time.Duration(conf.Account.ReLogin.Interval))
|
||||
if base.Reconnect.Interval > 0 {
|
||||
log.Warnf("将在 %v 秒后尝试重连. 重连次数:%v/%v", base.Reconnect.Interval, times, base.Reconnect.MaxTimes)
|
||||
time.Sleep(time.Second * time.Duration(base.Reconnect.Interval))
|
||||
} else {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
@ -328,7 +293,7 @@ func main() {
|
||||
break
|
||||
}
|
||||
log.Warnf("尝试重连...")
|
||||
err := cli.TokenLogin(AccountToken)
|
||||
err := cli.TokenLogin(base.AccountToken)
|
||||
if err == nil {
|
||||
saveToken()
|
||||
return
|
||||
@ -356,70 +321,16 @@ func main() {
|
||||
log.Infof("开始加载群列表...")
|
||||
global.Check(cli.ReloadGroupList(), true)
|
||||
log.Infof("共加载 %v 个群.", len(cli.GroupList))
|
||||
if conf.Account.Status >= int32(len(allowStatus)) || conf.Account.Status < 0 {
|
||||
conf.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)
|
||||
}
|
||||
}
|
||||
if uint(base.Account.Status) >= uint(len(allowStatus)) {
|
||||
base.Account.Status = 0
|
||||
}
|
||||
cli.SetOnlineStatus(allowStatus[base.Account.Status])
|
||||
|
||||
servers.Run(coolq.NewQQBot(cli))
|
||||
log.Info("资源初始化完成, 开始处理信息.")
|
||||
log.Info("アトリは、高性能ですから!")
|
||||
|
||||
go checkUpdate()
|
||||
go selfupdate.CheckUpdate()
|
||||
|
||||
<-global.SetupMainSignalHandler()
|
||||
}
|
||||
@ -455,178 +366,10 @@ func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, erro
|
||||
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 {
|
||||
c := client.NewClientEmpty()
|
||||
c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool {
|
||||
if !conf.Account.UseSSOAddress {
|
||||
if !base.UseSSOAddress {
|
||||
log.Infof("收到服务器地址更新通知, 根据配置文件已忽略.")
|
||||
return false
|
||||
}
|
||||
|
@ -6,12 +6,10 @@ import (
|
||||
_ "embed" // embed the default config file
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/internal/param"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
@ -21,27 +19,27 @@ import (
|
||||
//go:embed default_config.yml
|
||||
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 默认配置文件路径
|
||||
var DefaultConfigFile = path.Join(currentPath, "config.yml")
|
||||
// Account 账号配置
|
||||
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 总配置文件
|
||||
type Config struct {
|
||||
Account struct {
|
||||
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"`
|
||||
|
||||
Account *Account `yaml:"account"`
|
||||
Heartbeat struct {
|
||||
Disabled bool `yaml:"disabled"`
|
||||
Interval int `yaml:"interval"`
|
||||
@ -49,10 +47,10 @@ type Config struct {
|
||||
|
||||
Message struct {
|
||||
PostFormat string `yaml:"post-format"`
|
||||
ProxyRewrite string `yaml:"proxy-rewrite"`
|
||||
IgnoreInvalidCQCode bool `yaml:"ignore-invalid-cqcode"`
|
||||
ForceFragment bool `yaml:"force-fragment"`
|
||||
FixURL bool `yaml:"fix-url"`
|
||||
ProxyRewrite string `yaml:"proxy-rewrite"`
|
||||
ReportSelfMessage bool `yaml:"report-self-message"`
|
||||
RemoveReplyAt bool `yaml:"remove-reply-at"`
|
||||
ExtraReplyData bool `yaml:"extra-reply-data"`
|
||||
@ -139,113 +137,97 @@ type LevelDBConfig struct {
|
||||
Enable bool `yaml:"enable"`
|
||||
}
|
||||
|
||||
var (
|
||||
config *Config
|
||||
once sync.Once
|
||||
)
|
||||
// Parse 从默认配置文件路径中获取
|
||||
func Parse(path string) *Config {
|
||||
fromEnv := os.Getenv("GCQ_UIN") != ""
|
||||
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
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
|
||||
func getCurrentPath() string {
|
||||
cwd, e := os.Getwd()
|
||||
if e != nil {
|
||||
panic(e)
|
||||
} 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 生成配置文件
|
70
modules/mime/mime.go
Normal file
70
modules/mime/mime.go
Normal 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) // nolint
|
||||
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[:])
|
||||
}
|
31
modules/servers/servers.go
Normal file
31
modules/servers/servers.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -4,7 +4,7 @@
|
||||
// +build !race
|
||||
// +build !nosilk
|
||||
|
||||
package codec
|
||||
package silk
|
||||
|
||||
import (
|
||||
"os"
|
||||
@ -13,12 +13,14 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/wdvxdr1123/go-silk"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/internal/base"
|
||||
)
|
||||
|
||||
const silkCachePath = "data/cache"
|
||||
|
||||
// EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte, err error) {
|
||||
// encode 将音频编码为Silk
|
||||
func encode(record []byte, tempName string) (silkWav []byte, err error) {
|
||||
// 1. 写入缓存文件
|
||||
rawPath := path.Join(silkCachePath, tempName+".wav")
|
||||
err = os.WriteFile(rawPath, record, os.ModePerm)
|
||||
@ -30,7 +32,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
|
||||
// 2.转换pcm
|
||||
pcmPath := path.Join(silkCachePath, tempName+".pcm")
|
||||
cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath)
|
||||
if Debug {
|
||||
if base.Debug {
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
}
|
||||
@ -48,15 +50,13 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "silk encode error")
|
||||
}
|
||||
if useCache {
|
||||
silkPath := path.Join(silkCachePath, tempName+".silk")
|
||||
err = os.WriteFile(silkPath, silkWav, 0o666)
|
||||
}
|
||||
silkPath := path.Join(silkCachePath, tempName+".silk")
|
||||
err = os.WriteFile(silkPath, silkWav, 0o666)
|
||||
return
|
||||
}
|
||||
|
||||
// RecodeTo24K 将silk重新编码为 24000 bit rate
|
||||
func RecodeTo24K(data []byte) []byte {
|
||||
// resample 将silk重新编码为 24000 bit rate
|
||||
func resample(data []byte) []byte {
|
||||
pcm, err := silk.DecodeSilkBuffToPcm(data, 24000)
|
||||
if err != nil {
|
||||
panic(err)
|
@ -1,16 +1,16 @@
|
||||
//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
|
||||
|
||||
package codec
|
||||
package silk
|
||||
|
||||
import "errors"
|
||||
|
||||
// EncodeToSilk 将音频编码为Silk
|
||||
func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error) {
|
||||
// encode 将音频编码为Silk
|
||||
func encode(record []byte, tempName string) ([]byte, error) {
|
||||
return nil, errors.New("not supported now")
|
||||
}
|
||||
|
||||
// RecodeTo24K 将silk重新编码为 24000 bit rate
|
||||
func RecodeTo24K(data []byte) []byte {
|
||||
// resample 将silk重新编码为 24000 bit rate
|
||||
func resample(data []byte) []byte {
|
||||
return data
|
||||
}
|
11
modules/silk/stubs.go
Normal file
11
modules/silk/stubs.go
Normal 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
|
||||
}
|
@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/internal/param"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
@ -63,7 +64,7 @@ func getGroupMemberInfo(bot *coolq.CQBot, p resultGetter) global.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" {
|
||||
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("group_id").Int(), p.Get("message"), autoEscape)
|
||||
}
|
||||
@ -81,7 +82,7 @@ func sendMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
|
||||
|
||||
func sendGroupMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
|
||||
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) global.MSG {
|
||||
@ -90,7 +91,7 @@ func sendGroupForwardMSG(bot *coolq.CQBot, p resultGetter) global.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"),
|
||||
global.EnsureBool(p.Get("auto_escape"), false))
|
||||
param.EnsureBool(p.Get("auto_escape"), false))
|
||||
}
|
||||
|
||||
func deleteMSG(bot *coolq.CQBot, p resultGetter) global.MSG {
|
||||
|
@ -1,2 +1,13 @@
|
||||
// Package server 包含HTTP,WebSocket,反向WebSocket请求处理的相关函数与结构体
|
||||
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)
|
||||
}
|
||||
|
111
server/http.go
111
server/http.go
@ -8,20 +8,23 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
"github.com/guonaihong/gout"
|
||||
"github.com/guonaihong/gout/dataflow"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"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 {
|
||||
@ -114,14 +117,21 @@ func (s *httpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
action := strings.TrimPrefix(request.URL.Path, "/")
|
||||
action = strings.TrimSuffix(action, "_async")
|
||||
log.Debugf("HTTPServer接收到API调用: %v", action)
|
||||
ret := s.api.callAPI(action, &ctx)
|
||||
var response global.MSG
|
||||
if base.AcceptOneBotV12HTTPEndPoint && request.URL.Path == "/" {
|
||||
action := strings.TrimSuffix(ctx.Get("action").Str, "_async")
|
||||
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.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(writer).Encode(ret)
|
||||
_ = json.NewEncoder(writer).Encode(response)
|
||||
}
|
||||
|
||||
func checkAuth(req *http.Request, token string) int {
|
||||
@ -149,16 +159,19 @@ func checkAuth(req *http.Request, token string) int {
|
||||
}
|
||||
}
|
||||
|
||||
// RunHTTPServerAndClients 启动HTTP服务器与HTTP上报客户端
|
||||
func RunHTTPServerAndClients(bot *coolq.CQBot, conf *config.HTTPServer) {
|
||||
if conf.Disabled {
|
||||
// runHTTP 启动HTTP服务器与HTTP上报客户端
|
||||
func runHTTP(bot *coolq.CQBot, node yaml.Node) {
|
||||
var conf config.HTTPServer
|
||||
switch err := node.Decode(&conf); {
|
||||
case err != nil:
|
||||
log.Warn("读取http配置失败 :", err)
|
||||
fallthrough
|
||||
case conf.Disabled:
|
||||
return
|
||||
}
|
||||
var (
|
||||
s = new(httpServer)
|
||||
addr string
|
||||
)
|
||||
s.accessToken = conf.AccessToken
|
||||
|
||||
var addr string
|
||||
s := &httpServer{accessToken: conf.AccessToken}
|
||||
if conf.Host == "" || conf.Port == 0 {
|
||||
goto client
|
||||
}
|
||||
@ -211,7 +224,6 @@ func (c HTTPClient) Run() {
|
||||
}
|
||||
|
||||
func (c *HTTPClient) onBotPushEvent(e *coolq.Event) {
|
||||
var res string
|
||||
if c.filter != "" {
|
||||
filter := findFilter(c.filter)
|
||||
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 {
|
||||
h := gout.H{
|
||||
"X-Self-ID": c.bot.Client.Uin,
|
||||
"User-Agent": "CQHttp/4.15.0",
|
||||
client := http.Client{Timeout: time.Second * time.Duration(c.timeout)}
|
||||
req, _ := http.NewRequest("POST", c.addr, nil)
|
||||
req.Header.Set("X-Self-ID", strconv.FormatInt(c.bot.Client.Uin, 10))
|
||||
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 != "" {
|
||||
mac := hmac.New(sha1.New, []byte(c.secret))
|
||||
_, err := mac.Write(e.JSONBytes())
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return nil
|
||||
}
|
||||
h["X-Signature"] = "sha1=" + hex.EncodeToString(mac.Sum(nil))
|
||||
if i != maxAttemptTimes {
|
||||
log.Warnf("上报 Event 数据到 %v 失败: %v 将进行第 %d 次重试", c.addr, err, i+1)
|
||||
}
|
||||
if c.apiPort != 0 {
|
||||
h["X-API-Port"] = c.apiPort
|
||||
}
|
||||
return h
|
||||
}()).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()
|
||||
const maxWait = int64(time.Second * 3)
|
||||
const minWait = int64(time.Millisecond * 500)
|
||||
wait := rand.Int63n(maxWait-minWait) + minWait
|
||||
time.Sleep(time.Duration(wait))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Warnf("上报Event数据 %s 到 %v 失败: %v", e.JSONBytes(), c.addr, err)
|
||||
return
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
@ -76,7 +75,7 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
|
||||
return nil
|
||||
}
|
||||
var (
|
||||
ok int32
|
||||
once sync.Once
|
||||
ch = make(chan []interface{}, 1)
|
||||
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 {
|
||||
cond.Wait()
|
||||
}
|
||||
if atomic.CompareAndSwapInt32(&ok, 0, 1) {
|
||||
once.Do(func() {
|
||||
limit := int(p.Get("limit").Int())
|
||||
if limit <= 0 || queue.Len() < limit {
|
||||
limit = queue.Len()
|
||||
@ -97,12 +96,12 @@ func longPolling(bot *coolq.CQBot, maxSize int) handler {
|
||||
ret[i] = queue.Remove(queue.Front())
|
||||
}
|
||||
ch <- ret
|
||||
}
|
||||
})
|
||||
}()
|
||||
if timeout != 0 {
|
||||
select {
|
||||
case <-time.After(timeout):
|
||||
atomic.StoreInt32(&ok, 1)
|
||||
once.Do(func() {})
|
||||
return coolq.OK([]interface{}{})
|
||||
case ret := <-ch:
|
||||
return coolq.OK(ret)
|
||||
|
@ -8,15 +8,23 @@ import (
|
||||
"time"
|
||||
|
||||
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 性能分析服务器
|
||||
func RunPprofServer(conf *config.PprofServer) {
|
||||
if conf.Disabled {
|
||||
// runPprof 启动 pprof 性能分析服务器
|
||||
func runPprof(_ *coolq.CQBot, node yaml.Node) {
|
||||
var conf config.PprofServer
|
||||
switch err := node.Decode(&conf); {
|
||||
case err != nil:
|
||||
log.Warn("读取pprof配置失败 :", err)
|
||||
fallthrough
|
||||
case conf.Disabled:
|
||||
return
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||
|
@ -13,10 +13,11 @@ import (
|
||||
|
||||
"github.com/Mrs4s/MiraiGo/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"github.com/Mrs4s/go-cqhttp/global"
|
||||
"github.com/Mrs4s/go-cqhttp/global/config"
|
||||
"github.com/Mrs4s/go-cqhttp/modules/config"
|
||||
)
|
||||
|
||||
type lambdaClient struct {
|
||||
@ -77,8 +78,17 @@ func (l *lambdaResponseWriter) WriteHeader(statusCode int) {
|
||||
|
||||
var cli *lambdaClient
|
||||
|
||||
// RunLambdaClient type: [scf,aws]
|
||||
func RunLambdaClient(bot *coolq.CQBot, conf *config.LambdaServer) {
|
||||
// runLambda type: [scf,aws]
|
||||
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{
|
||||
lambdaType: conf.Type,
|
||||
client: http.Client{Timeout: 0},
|
||||
|
@ -2,6 +2,8 @@ package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
@ -10,12 +12,14 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
"nhooyr.io/websocket"
|
||||
|
||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||
"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/gorilla/websocket"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
@ -24,11 +28,12 @@ type webSocketServer struct {
|
||||
bot *coolq.CQBot
|
||||
conf *config.WebsocketServer
|
||||
|
||||
eventConn []*webSocketConn
|
||||
eventConnMutex sync.Mutex
|
||||
token string
|
||||
handshake string
|
||||
filter string
|
||||
mu sync.Mutex
|
||||
eventConn []*wsConn
|
||||
|
||||
token string
|
||||
handshake string
|
||||
filter string
|
||||
}
|
||||
|
||||
// websocketClient WebSocket客户端实例
|
||||
@ -36,32 +41,33 @@ type websocketClient struct {
|
||||
bot *coolq.CQBot
|
||||
conf *config.WebsocketReverse
|
||||
|
||||
universalConn *webSocketConn
|
||||
eventConn *webSocketConn
|
||||
token string
|
||||
filter string
|
||||
mu sync.Mutex
|
||||
|
||||
universal *wsConn
|
||||
event *wsConn
|
||||
token string
|
||||
filter string
|
||||
}
|
||||
|
||||
type webSocketConn struct {
|
||||
type wsConn struct {
|
||||
*websocket.Conn
|
||||
sync.Mutex
|
||||
apiCaller *apiCaller
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
// RunWebSocketServer 运行一个正向WS server
|
||||
func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) {
|
||||
if conf.Disabled {
|
||||
// runWSServer 运行一个正向WS server
|
||||
func runWSServer(b *coolq.CQBot, node yaml.Node) {
|
||||
var conf config.WebsocketServer
|
||||
switch err := node.Decode(&conf); {
|
||||
case err != nil:
|
||||
log.Warn("读取正向Websocket配置失败 :", err)
|
||||
fallthrough
|
||||
case conf.Disabled:
|
||||
return
|
||||
}
|
||||
|
||||
s := &webSocketServer{
|
||||
bot: b,
|
||||
conf: conf,
|
||||
conf: &conf,
|
||||
token: conf.AccessToken,
|
||||
filter: conf.Filter,
|
||||
}
|
||||
@ -80,137 +86,89 @@ func RunWebSocketServer(b *coolq.CQBot, conf *config.WebsocketServer) {
|
||||
}()
|
||||
}
|
||||
|
||||
// RunWebSocketClient 运行一个正向WS client
|
||||
func RunWebSocketClient(b *coolq.CQBot, conf *config.WebsocketReverse) {
|
||||
if conf.Disabled {
|
||||
// runWSClient 运行一个反向向WS client
|
||||
func runWSClient(b *coolq.CQBot, node yaml.Node) {
|
||||
var conf config.WebsocketReverse
|
||||
switch err := node.Decode(&conf); {
|
||||
case err != nil:
|
||||
log.Warn("读取反向Websocket配置失败 :", err)
|
||||
fallthrough
|
||||
case conf.Disabled:
|
||||
return
|
||||
}
|
||||
|
||||
c := &websocketClient{
|
||||
bot: b,
|
||||
conf: conf,
|
||||
conf: &conf,
|
||||
token: conf.AccessToken,
|
||||
filter: conf.Filter,
|
||||
}
|
||||
addFilter(c.filter)
|
||||
if c.conf.Universal != "" {
|
||||
c.connectUniversal()
|
||||
c.connect("Universal", conf.Universal, &c.universal)
|
||||
} else {
|
||||
if c.conf.API != "" {
|
||||
c.connectAPI()
|
||||
c.connect("API", conf.API, nil)
|
||||
}
|
||||
if c.conf.Event != "" {
|
||||
c.connectEvent()
|
||||
c.connect("Event", conf.Event, &c.event)
|
||||
}
|
||||
}
|
||||
c.bot.OnEventPush(c.onBotPushEvent)
|
||||
}
|
||||
|
||||
func (c *websocketClient) connectAPI() {
|
||||
log.Infof("开始尝试连接到反向WebSocket API服务器: %v", c.conf.API)
|
||||
func (c *websocketClient) connect(typ, url string, conptr **wsConn) {
|
||||
log.Infof("开始尝试连接到反向WebSocket %s服务器: %v", typ, c.conf.API)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"API"},
|
||||
"X-Client-Role": []string{typ},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
"User-Agent": []string{"CQHttp/4.15.0"},
|
||||
}
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.API, header) // nolint
|
||||
conn, _, err := websocket.Dial(context.Background(), url, &websocket.DialOptions{HTTPHeader: header}) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket API服务器 %v 时出现错误: %v", c.conf.API, err)
|
||||
log.Warnf("连接到反向WebSocket %s服务器 %v 时出现错误: %v", typ, c.conf.API, err)
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectAPI()
|
||||
c.connect(typ, url, conptr)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Infof("已连接到反向WebSocket API服务器 %v", c.conf.API)
|
||||
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
|
||||
|
||||
switch typ {
|
||||
case "Event", "Universal":
|
||||
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`, c.bot.Client.Uin, time.Now().Unix())
|
||||
err = conn.Write(context.Background(), websocket.MessageText, []byte(handshake))
|
||||
if err != nil {
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("已连接到反向WebSocket %s服务器 %v", typ, c.conf.API)
|
||||
wrappedConn := &wsConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
|
||||
if c.conf.RateLimit.Enabled {
|
||||
wrappedConn.apiCaller.use(rateLimit(c.conf.RateLimit.Frequency, c.conf.RateLimit.Bucket))
|
||||
}
|
||||
go c.listenAPI(wrappedConn, false)
|
||||
}
|
||||
|
||||
func (c *websocketClient) connectEvent() {
|
||||
log.Infof("开始尝试连接到反向WebSocket Event服务器: %v", c.conf.Event)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"Event"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
"User-Agent": []string{"CQHttp/4.15.0"},
|
||||
}
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Event, header) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket Event服务器 %v 时出现错误: %v", c.conf.Event, err)
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectEvent()
|
||||
}
|
||||
return
|
||||
if conptr != nil {
|
||||
*conptr = wrappedConn
|
||||
}
|
||||
|
||||
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
|
||||
c.bot.Client.Uin, time.Now().Unix())
|
||||
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
|
||||
if err != nil {
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("已连接到反向WebSocket Event服务器 %v", c.conf.Event)
|
||||
if c.eventConn == nil {
|
||||
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
|
||||
c.eventConn = wrappedConn
|
||||
} else {
|
||||
c.eventConn.Conn = conn
|
||||
switch typ {
|
||||
case "API":
|
||||
go c.listenAPI(wrappedConn, false)
|
||||
case "Universal":
|
||||
go c.listenAPI(wrappedConn, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *websocketClient) connectUniversal() {
|
||||
log.Infof("开始尝试连接到反向WebSocket Universal服务器: %v", c.conf.Universal)
|
||||
header := http.Header{
|
||||
"X-Client-Role": []string{"Universal"},
|
||||
"X-Self-ID": []string{strconv.FormatInt(c.bot.Client.Uin, 10)},
|
||||
"User-Agent": []string{"CQHttp/4.15.0"},
|
||||
}
|
||||
if c.token != "" {
|
||||
header["Authorization"] = []string{"Token " + c.token}
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(c.conf.Universal, header) // nolint
|
||||
if err != nil {
|
||||
log.Warnf("连接到反向WebSocket Universal服务器 %v 时出现错误: %v", c.conf.Universal, err)
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
c.connectUniversal()
|
||||
}
|
||||
return
|
||||
}
|
||||
handshake := fmt.Sprintf(`{"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
|
||||
c.bot.Client.Uin, time.Now().Unix())
|
||||
err = conn.WriteMessage(websocket.TextMessage, []byte(handshake))
|
||||
if err != nil {
|
||||
log.Warnf("反向WebSocket 握手时出现错误: %v", err)
|
||||
}
|
||||
|
||||
if c.universalConn == nil {
|
||||
wrappedConn := &webSocketConn{Conn: conn, apiCaller: newAPICaller(c.bot)}
|
||||
if c.conf.RateLimit.Enabled {
|
||||
wrappedConn.apiCaller.use(rateLimit(c.conf.RateLimit.Frequency, c.conf.RateLimit.Bucket))
|
||||
}
|
||||
c.universalConn = wrappedConn
|
||||
} else {
|
||||
c.universalConn.Conn = conn
|
||||
}
|
||||
go c.listenAPI(c.universalConn, true)
|
||||
}
|
||||
|
||||
func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
func (c *websocketClient) listenAPI(conn *wsConn, u bool) {
|
||||
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
||||
for {
|
||||
buffer := global.NewBuffer()
|
||||
t, reader, err := conn.NextReader()
|
||||
t, reader, err := conn.Conn.Reader(context.Background())
|
||||
if err != nil {
|
||||
log.Warnf("监听反向WS API时出现错误: %v", err)
|
||||
break
|
||||
@ -220,7 +178,7 @@ func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
log.Warnf("监听反向WS API时出现错误: %v", err)
|
||||
break
|
||||
}
|
||||
if t == websocket.TextMessage {
|
||||
if t == websocket.MessageText {
|
||||
go func(buffer *bytes.Buffer) {
|
||||
defer global.PutBuffer(buffer)
|
||||
conn.handleRequest(c.bot, buffer.Bytes())
|
||||
@ -232,7 +190,7 @@ func (c *websocketClient) listenAPI(conn *webSocketConn, u bool) {
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
if !u {
|
||||
go c.connectAPI()
|
||||
go c.connect("API", c.conf.API, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -243,25 +201,34 @@ func (c *websocketClient) onBotPushEvent(e *coolq.Event) {
|
||||
log.Debugf("上报Event %s 到 WS服务器 时被过滤.", e.JSONBytes())
|
||||
return
|
||||
}
|
||||
push := func(conn *webSocketConn, reconnect func()) {
|
||||
log.Debugf("向WS服务器 %v 推送Event: %s", conn.RemoteAddr().String(), e.JSONBytes())
|
||||
conn.Lock()
|
||||
defer conn.Unlock()
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(time.Second * 15))
|
||||
if err := conn.WriteMessage(websocket.TextMessage, e.JSONBytes()); err != nil {
|
||||
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", conn.RemoteAddr().String(), err)
|
||||
_ = conn.Close()
|
||||
push := func(conn *wsConn, reconnect func()) {
|
||||
log.Debugf("向WS服务器推送Event: %s", e.JSONBytes())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
|
||||
defer cancel()
|
||||
if err := conn.Write(ctx, websocket.MessageText, e.JSONBytes()); err != nil {
|
||||
log.Warnf("向WS服务器推送 Event 时出现错误: %v", err)
|
||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||
if c.conf.ReconnectInterval != 0 {
|
||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReconnectInterval))
|
||||
reconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.eventConn != nil {
|
||||
push(c.eventConn, c.connectEvent)
|
||||
|
||||
connect := func(typ, url string, conptr **wsConn) func() {
|
||||
return func() {
|
||||
c.connect(typ, url, conptr)
|
||||
}
|
||||
}
|
||||
if c.universalConn != nil {
|
||||
push(c.universalConn, c.connectUniversal)
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if c.event != nil {
|
||||
push(c.event, connect("Event", c.conf.Event, &c.event))
|
||||
}
|
||||
if c.universal != nil {
|
||||
push(c.universal, connect("Universal", c.conf.Universal, &c.universal))
|
||||
}
|
||||
}
|
||||
|
||||
@ -272,25 +239,25 @@ func (s *webSocketServer) event(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
|
||||
err = c.Write(context.Background(), websocket.MessageText, []byte(s.handshake))
|
||||
if err != nil {
|
||||
log.Warnf("WebSocket 握手时出现错误: %v", err)
|
||||
_ = c.Close()
|
||||
_ = c.Close(websocket.StatusNormalClosure, "")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("接受 WebSocket 连接: %v (/event)", r.RemoteAddr)
|
||||
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
|
||||
s.eventConnMutex.Lock()
|
||||
s.mu.Lock()
|
||||
s.eventConn = append(s.eventConn, conn)
|
||||
s.eventConnMutex.Unlock()
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
|
||||
@ -300,13 +267,13 @@ func (s *webSocketServer) api(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
log.Infof("接受 WebSocket 连接: %v (/api)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
if s.conf.RateLimit.Enabled {
|
||||
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
|
||||
}
|
||||
@ -320,33 +287,33 @@ func (s *webSocketServer) any(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
log.Warnf("处理 WebSocket 请求时出现错误: %v", err)
|
||||
return
|
||||
}
|
||||
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
|
||||
err = c.Write(context.Background(), websocket.MessageText, []byte(s.handshake))
|
||||
if err != nil {
|
||||
log.Warnf("WebSocket 握手时出现错误: %v", err)
|
||||
_ = c.Close()
|
||||
_ = c.Close(websocket.StatusNormalClosure, "")
|
||||
return
|
||||
}
|
||||
log.Infof("接受 WebSocket 连接: %v (/)", r.RemoteAddr)
|
||||
conn := &webSocketConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
conn := &wsConn{Conn: c, apiCaller: newAPICaller(s.bot)}
|
||||
if s.conf.RateLimit.Enabled {
|
||||
conn.apiCaller.use(rateLimit(s.conf.RateLimit.Frequency, s.conf.RateLimit.Bucket))
|
||||
}
|
||||
s.eventConnMutex.Lock()
|
||||
s.mu.Lock()
|
||||
s.eventConn = append(s.eventConn, conn)
|
||||
s.eventConnMutex.Unlock()
|
||||
s.mu.Unlock()
|
||||
s.listenAPI(conn)
|
||||
}
|
||||
|
||||
func (s *webSocketServer) listenAPI(c *webSocketConn) {
|
||||
defer func() { _ = c.Close() }()
|
||||
func (s *webSocketServer) listenAPI(c *wsConn) {
|
||||
defer func() { _ = c.Close(websocket.StatusNormalClosure, "") }()
|
||||
for {
|
||||
buffer := global.NewBuffer()
|
||||
t, reader, err := c.NextReader()
|
||||
t, reader, err := c.Reader(context.Background())
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
@ -355,7 +322,7 @@ func (s *webSocketServer) listenAPI(c *webSocketConn) {
|
||||
break
|
||||
}
|
||||
|
||||
if t == websocket.TextMessage {
|
||||
if t == websocket.MessageText {
|
||||
go func(buffer *bytes.Buffer) {
|
||||
defer global.PutBuffer(buffer)
|
||||
c.handleRequest(s.bot, buffer.Bytes())
|
||||
@ -366,11 +333,11 @@ func (s *webSocketServer) listenAPI(c *webSocketConn) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
|
||||
func (c *wsConn) handleRequest(_ *coolq.CQBot, payload []byte) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("处置WS命令时发生无法恢复的异常:%v\n%s", err, debug.Stack())
|
||||
_ = c.Close()
|
||||
_ = c.Close(websocket.StatusInternalError, fmt.Sprint(err))
|
||||
}
|
||||
}()
|
||||
j := gjson.Parse(utils.B2S(payload))
|
||||
@ -380,27 +347,27 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
|
||||
if j.Get("echo").Exists() {
|
||||
ret["echo"] = j.Get("echo").Value()
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
_ = c.WriteJSON(ret)
|
||||
writer, _ := c.Writer(context.Background(), websocket.MessageText)
|
||||
_ = json.NewEncoder(writer).Encode(ret)
|
||||
_ = writer.Close()
|
||||
}
|
||||
|
||||
func (s *webSocketServer) onBotPushEvent(e *coolq.Event) {
|
||||
s.eventConnMutex.Lock()
|
||||
defer s.eventConnMutex.Unlock()
|
||||
|
||||
filter := findFilter(s.filter)
|
||||
if filter != nil && !filter.Eval(gjson.Parse(e.JSONString())) {
|
||||
log.Debugf("上报Event %s 到 WS客户端 时被过滤.", e.JSONBytes())
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
j := 0
|
||||
for i := 0; i < len(s.eventConn); i++ {
|
||||
conn := s.eventConn[i]
|
||||
log.Debugf("向WS客户端 %v 推送Event: %s", conn.RemoteAddr().String(), e.JSONBytes())
|
||||
conn.Lock()
|
||||
if err := conn.WriteMessage(websocket.TextMessage, e.JSONBytes()); err != nil {
|
||||
_ = conn.Close()
|
||||
log.Debugf("向WS客户端推送Event: %s", e.JSONBytes())
|
||||
if err := conn.Write(context.Background(), websocket.MessageText, e.JSONBytes()); err != nil {
|
||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||
conn = nil
|
||||
continue
|
||||
}
|
||||
@ -409,7 +376,6 @@ func (s *webSocketServer) onBotPushEvent(e *coolq.Event) {
|
||||
// use a in-place removal to avoid copying.
|
||||
s.eventConn[j] = conn
|
||||
}
|
||||
conn.Unlock()
|
||||
j++
|
||||
}
|
||||
s.eventConn = s.eventConn[:j]
|
||||
|
Reference in New Issue
Block a user