Commit 21b9e2f3 authored by nanahira's avatar nanahira

Merge branch 'master' of github.com:Mrs4s/go-cqhttp

parents 5381a7ed 7f103a7f
Pipeline #668 passed with stages
in 4 minutes and 39 seconds
FROM golang:1.14.2-alpine AS builder FROM golang:1.14.7-alpine AS builder
ARG GO_CQHTTP_VERSION ARG GO_CQHTTP_VERSION
ENV GO_CQHTTP_VERSION ${GO_CQHTTP_VERSION:-v0.9.20-mycard} ENV GO_CQHTTP_VERSION ${GO_CQHTTP_VERSION:-v0.9.20-mycard}
......
...@@ -25,7 +25,7 @@ func (bot *CQBot) CQGetLoginInfo() MSG { ...@@ -25,7 +25,7 @@ func (bot *CQBot) CQGetLoginInfo() MSG {
// https://cqhttp.cc/docs/4.15/#/API?id=get_friend_list-%E8%8E%B7%E5%8F%96%E5%A5%BD%E5%8F%8B%E5%88%97%E8%A1%A8 // https://cqhttp.cc/docs/4.15/#/API?id=get_friend_list-%E8%8E%B7%E5%8F%96%E5%A5%BD%E5%8F%8B%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetFriendList() MSG { func (bot *CQBot) CQGetFriendList() MSG {
var fs []MSG fs := make([]MSG, 0)
for _, f := range bot.Client.FriendList { for _, f := range bot.Client.FriendList {
fs = append(fs, MSG{ fs = append(fs, MSG{
"nickname": f.Nickname, "nickname": f.Nickname,
...@@ -38,7 +38,7 @@ func (bot *CQBot) CQGetFriendList() MSG { ...@@ -38,7 +38,7 @@ func (bot *CQBot) CQGetFriendList() MSG {
// https://cqhttp.cc/docs/4.15/#/API?id=get_group_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%88%97%E8%A1%A8 // https://cqhttp.cc/docs/4.15/#/API?id=get_group_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetGroupList(noCache bool) MSG { func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
var gs []MSG gs := make([]MSG, 0)
if noCache { if noCache {
_ = bot.Client.ReloadGroupList() _ = bot.Client.ReloadGroupList()
} }
...@@ -73,7 +73,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupId int64) MSG { ...@@ -73,7 +73,7 @@ func (bot *CQBot) CQGetGroupMemberList(groupId int64) MSG {
if group == nil { if group == nil {
return Failed(100) return Failed(100)
} }
var members []MSG members := make([]MSG, 0)
for _, m := range group.Members { for _, m := range group.Members {
members = append(members, convertGroupMemberInfo(groupId, m)) members = append(members, convertGroupMemberInfo(groupId, m))
} }
...@@ -525,7 +525,7 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG { ...@@ -525,7 +525,7 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
if m == nil { if m == nil {
return Failed(100) return Failed(100)
} }
var r []MSG r := make([]MSG, 0)
for _, n := range m.Nodes { for _, n := range m.Nodes {
bot.checkMedia(n.Message) bot.checkMedia(n.Message)
r = append(r, MSG{ r = append(r, MSG{
......
...@@ -5,17 +5,19 @@ import ( ...@@ -5,17 +5,19 @@ import (
"encoding/gob" "encoding/gob"
"encoding/json" "encoding/json"
"fmt" "fmt"
"hash/crc32"
"path"
"sync"
"time"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client" "github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message" "github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/xujiajun/nutsdb" "github.com/xujiajun/nutsdb"
"hash/crc32"
"path"
"sync"
"time"
) )
type CQBot struct { type CQBot struct {
...@@ -27,6 +29,7 @@ type CQBot struct { ...@@ -27,6 +29,7 @@ type CQBot struct {
invitedReqCache sync.Map invitedReqCache sync.Map
joinReqCache sync.Map joinReqCache sync.Map
tempMsgCache sync.Map tempMsgCache sync.Map
oneWayMsgCache sync.Map
} }
type MSG map[string]interface{} type MSG map[string]interface{}
...@@ -67,15 +70,20 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot { ...@@ -67,15 +70,20 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
bot.Client.OnGroupInvited(bot.groupInvitedEvent) bot.Client.OnGroupInvited(bot.groupInvitedEvent)
bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent) bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent)
go func() { go func() {
i := conf.HeartbeatInterval
if i < 1 {
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
return
}
for { for {
time.Sleep(time.Second * 5) time.Sleep(time.Second * i)
bot.dispatchEventMessage(MSG{ bot.dispatchEventMessage(MSG{
"time": time.Now().Unix(), "time": time.Now().Unix(),
"self_id": bot.Client.Uin, "self_id": bot.Client.Uin,
"post_type": "meta_event", "post_type": "meta_event",
"meta_event_type": "heartbeat", "meta_event_type": "heartbeat",
"status": nil, "status": nil,
"interval": 5000, "interval": 1000 * i,
}) })
} }
}() }()
...@@ -159,12 +167,15 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in ...@@ -159,12 +167,15 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
if msg != nil { if msg != nil {
id = msg.Id id = msg.Id
} }
} else { } else if code, ok := bot.tempMsgCache.Load(target); ok {
if code, ok := bot.tempMsgCache.Load(target); ok {
msg := bot.Client.SendTempMessage(code.(int64), target, m) msg := bot.Client.SendTempMessage(code.(int64), target, m)
if msg != nil { if msg != nil {
id = msg.Id id = msg.Id
} }
} else if _, ok := bot.oneWayMsgCache.Load(target); ok {
msg := bot.Client.SendPrivateMessage(target, m)
if msg != nil {
id = msg.Id
} }
} }
if id == -1 { if id == -1 {
......
...@@ -367,12 +367,18 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message. ...@@ -367,12 +367,18 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
if group { if group {
rsp, err := bot.Client.QueryGroupImage(1, hash, size) rsp, err := bot.Client.QueryGroupImage(1, hash, size)
if err != nil { if err != nil {
if url != "" {
return bot.ToElement(t, map[string]string{"file": url}, group)
}
return nil, err return nil, err
} }
return rsp, nil return rsp, nil
} }
rsp, err := bot.Client.QueryFriendImage(1, hash, size) rsp, err := bot.Client.QueryFriendImage(1, hash, size)
if err != nil { if err != nil {
if url != "" {
return bot.ToElement(t, map[string]string{"file": url}, group)
}
return nil, err return nil, err
} }
return rsp, nil return rsp, nil
...@@ -452,7 +458,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message. ...@@ -452,7 +458,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
if len(aid) < 2 { if len(aid) < 2 {
return nil, errors.New("song error") return nil, errors.New("song error")
} }
xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="https://i.y.qq.com/v8/playsong.html?_wv=1&songid=%s&souce=qqshare&source=qqshare&ADTAG=qqshare" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="http://imgcache.qq.com/music/photo/album_500/%s/500_albumpic_%s_0.jpg" src="%s" /><title>%s</title><summary>%s</summary></item><source name="QQ音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`, xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="https://i.y.qq.com/v8/playsong.html?_wv=1&amp;songid=%s&amp;souce=qqshare&amp;source=qqshare&amp;ADTAG=qqshare" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="http://imgcache.qq.com/music/photo/album_500/%s/500_albumpic_%s_0.jpg" src="%s" /><title>%s</title><summary>%s</summary></item><source name="QQ音乐" icon="https://i.gtimg.cn/open/app_icon/01/07/98/56/1101079856_100_m.png" url="http://web.p.qq.com/qqmpmobile/aio/app.html?id=1101079856" action="app" a_actionData="com.tencent.qqmusic" i_actionData="tencent1101079856://" appid="1101079856" /></msg>`,
name, d["id"], aid[:len(aid)-2], aid, name, "", info.Get("track_info.singer.name").Str) name, d["id"], aid[:len(aid)-2], aid, name, "", info.Get("track_info.singer.name").Str)
return &message.ServiceElement{ return &message.ServiceElement{
Id: 60, Id: 60,
......
...@@ -32,6 +32,9 @@ func ToFormattedMessage(e []message.IMessageElement, code int64, raw ...bool) (r ...@@ -32,6 +32,9 @@ func ToFormattedMessage(e []message.IMessageElement, code int64, raw ...bool) (r
func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) { func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) {
bot.checkMedia(m.Elements) bot.checkMedia(m.Elements)
cqm := ToStringMessage(m.Elements, 0, true) cqm := ToStringMessage(m.Elements, 0, true)
if !m.Sender.IsFriend {
bot.oneWayMsgCache.Store(m.Sender.Uin, "")
}
log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm) log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm)
fm := MSG{ fm := MSG{
"post_type": "message", "post_type": "message",
......
...@@ -22,11 +22,15 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为: ...@@ -22,11 +22,15 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
"password_encrypted": "", "password_encrypted": "",
"enable_db": true, "enable_db": true,
"access_token": "", "access_token": "",
"relogin": false, "relogin": {
"relogin_delay": 0, "enabled": true,
"relogin_delay": 3,
"max_relogin_times": 0
},
"post_message_format": "string", "post_message_format": "string",
"ignore_invalid_cqcode": false, "ignore_invalid_cqcode": false,
"force_fragmented": true, "force_fragmented": true,
"heartbeat_interval": 5,
"http_config": { "http_config": {
"enabled": true, "enabled": true,
"host": "0.0.0.0", "host": "0.0.0.0",
...@@ -61,9 +65,11 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为: ...@@ -61,9 +65,11 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
| access_token | string | 同CQHTTP的 `access_token` 用于身份验证 | | access_token | string | 同CQHTTP的 `access_token` 用于身份验证 |
| relogin | bool | 是否自动重新登录 | | relogin | bool | 是否自动重新登录 |
| relogin_delay | int | 重登录延时(秒) | | relogin_delay | int | 重登录延时(秒) |
| max_relogin_times | uint | 最大重登录次数,若0则不设置上限 |
| post_message_format | string | 上报信息类型 | | post_message_format | string | 上报信息类型 |
| ignore_invalid_cqcode| bool | 是否忽略错误的CQ码 | | ignore_invalid_cqcode| bool | 是否忽略错误的CQ码 |
| force_fragmented | bool | 是否强制分片发送群长消息 | | force_fragmented | bool | 是否强制分片发送群长消息 |
| heartbeat_interval | int64 | 心跳间隔时间,单位秒,若0则关闭心跳 |
| http_config | object | HTTP API配置 | | http_config | object | HTTP API配置 |
| ws_config | object | Websocket API 配置 | | ws_config | object | Websocket API 配置 |
| ws_reverse_servers | object[] | 反向 Websocket API 配置 | | ws_reverse_servers | object[] | 反向 Websocket API 配置 |
...@@ -73,4 +79,6 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为: ...@@ -73,4 +79,6 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
> 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取. > 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取.
> 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥 > 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥
> 注2: 分片发送为原酷Q发送长消息的老方案, 发送速度更优/兼容性更好。关闭后将优先使用新方案, 能发送更长的消息, 但发送速度更慢,在部分老客户端将无法解析. > 注2: 分片发送为原酷Q发送长消息的老方案, 发送速度更优/兼容性更好,但在有发言频率限制的群里,可能无法发送。关闭后将优先使用新方案, 能发送更长的消息, 但发送速度更慢,在部分老客户端将无法解析.
\ No newline at end of file
> 注3:关闭心跳服务可能引起断线,请谨慎关闭
...@@ -2,6 +2,10 @@ package global ...@@ -2,6 +2,10 @@ package global
import ( import (
"encoding/json" "encoding/json"
"os"
"strconv"
"time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
...@@ -12,10 +16,14 @@ type JsonConfig struct { ...@@ -12,10 +16,14 @@ type JsonConfig struct {
PasswordEncrypted string `json:"password_encrypted"` PasswordEncrypted string `json:"password_encrypted"`
EnableDB bool `json:"enable_db"` EnableDB bool `json:"enable_db"`
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
ReLogin bool `json:"relogin"` ReLogin struct {
Enabled bool `json:"enabled"`
ReLoginDelay int `json:"relogin_delay"` ReLoginDelay int `json:"relogin_delay"`
MaxReloginTimes uint `json:"max_relogin_times"`
} `json:"relogin"`
IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"` IgnoreInvalidCQCode bool `json:"ignore_invalid_cqcode"`
ForceFragmented bool `json:"force_fragmented"` ForceFragmented bool `json:"force_fragmented"`
HeartbeatInterval time.Duration `json:"heartbeat_interval"`
HttpConfig *GoCQHttpConfig `json:"http_config"` HttpConfig *GoCQHttpConfig `json:"http_config"`
WSConfig *GoCQWebsocketConfig `json:"ws_config"` WSConfig *GoCQWebsocketConfig `json:"ws_config"`
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"` ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
...@@ -68,8 +76,15 @@ type GoCQReverseWebsocketConfig struct { ...@@ -68,8 +76,15 @@ type GoCQReverseWebsocketConfig struct {
func DefaultConfig() *JsonConfig { func DefaultConfig() *JsonConfig {
return &JsonConfig{ return &JsonConfig{
EnableDB: true, EnableDB: true,
ReLogin: true, ReLogin: struct {
Enabled bool `json:"enabled"`
ReLoginDelay int `json:"relogin_delay"`
MaxReloginTimes uint `json:"max_relogin_times"`
}{
Enabled: true,
ReLoginDelay: 3, ReLoginDelay: 3,
MaxReloginTimes: 0,
},
PostMessageFormat: "string", PostMessageFormat: "string",
ForceFragmented: true, ForceFragmented: true,
HttpConfig: &GoCQHttpConfig{ HttpConfig: &GoCQHttpConfig{
...@@ -104,6 +119,8 @@ func Load(p string) *JsonConfig { ...@@ -104,6 +119,8 @@ func Load(p string) *JsonConfig {
err := json.Unmarshal([]byte(ReadAllText(p)), &c) err := json.Unmarshal([]byte(ReadAllText(p)), &c)
if err != nil { if err != nil {
log.Warnf("尝试加载配置文件 %v 时出现错误: %v", p, err) log.Warnf("尝试加载配置文件 %v 时出现错误: %v", p, err)
log.Infoln("原文件已备份")
os.Rename(p, p+".backup"+strconv.FormatInt(time.Now().Unix(), 10))
return nil return nil
} }
return &c return &c
......
...@@ -3,22 +3,24 @@ module github.com/Mrs4s/go-cqhttp ...@@ -3,22 +3,24 @@ module github.com/Mrs4s/go-cqhttp
go 1.14 go 1.14
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20200825052841-d3b0f5f9e839 github.com/Mrs4s/MiraiGo v0.0.0-20200827182935-51e155ef20da
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/gin-gonic/gin v1.6.3 github.com/gin-gonic/gin v1.6.3
github.com/gorilla/websocket v1.4.2 github.com/gorilla/websocket v1.4.2
github.com/guonaihong/gout v0.1.1 github.com/guonaihong/gout v0.1.2
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jonboulle/clockwork v0.2.0 // indirect github.com/jonboulle/clockwork v0.2.0 // indirect
github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible
github.com/lestrrat-go/strftime v1.0.1 // indirect github.com/lestrrat-go/strftime v1.0.3 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.6.0 github.com/sirupsen/logrus v1.6.0
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
github.com/tebeka/strftime v0.1.5 // indirect github.com/tebeka/strftime v0.1.5 // indirect
github.com/tidwall/gjson v1.6.0 github.com/tidwall/gjson v1.6.1
github.com/xujiajun/nutsdb v0.5.0 github.com/xujiajun/nutsdb v0.5.0
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae // indirect golang.org/x/net v0.0.0-20200822124328-c89045814202 // indirect
golang.org/x/sys v0.0.0-20200828194041-157a740278f4 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
) )
This diff is collapsed.
...@@ -22,6 +22,7 @@ import ( ...@@ -22,6 +22,7 @@ import (
"github.com/Mrs4s/go-cqhttp/coolq" "github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/server" "github.com/Mrs4s/go-cqhttp/server"
rotatelogs "github.com/lestrrat-go/file-rotatelogs" rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook" "github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
...@@ -311,12 +312,22 @@ func main() { ...@@ -311,12 +312,22 @@ func main() {
log.Info("资源初始化完成, 开始处理信息.") log.Info("资源初始化完成, 开始处理信息.")
log.Info("アトリは、高性能ですから!") log.Info("アトリは、高性能ですから!")
cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) { cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) {
if conf.ReLogin { if conf.ReLogin.Enabled {
log.Warnf("Bot已离线 (%v),将在 %v 秒后尝试重连.", e.Message, conf.ReLoginDelay) var times uint = 1
time.Sleep(time.Second * time.Duration(conf.ReLoginDelay)) for {
if conf.ReLogin.MaxReloginTimes == 0 {
} else if times > conf.ReLogin.MaxReloginTimes {
break
}
log.Warnf("Bot已离线 (%v),将在 %v 秒后尝试重连. 重连次数:%v",
e.Message, conf.ReLogin.ReLoginDelay, times)
times++
time.Sleep(time.Second * time.Duration(conf.ReLogin.ReLoginDelay))
rsp, err := cli.Login() rsp, err := cli.Login()
if err != nil { if err != nil {
log.Fatalf("重连失败: %v", err) log.Errorf("重连失败: %v", err)
continue
} }
if !rsp.Success { if !rsp.Success {
switch rsp.Error { switch rsp.Error {
...@@ -325,10 +336,15 @@ func main() { ...@@ -325,10 +336,15 @@ func main() {
case client.UnsafeDeviceError: case client.UnsafeDeviceError:
log.Fatalf("重连失败: 设备锁") log.Fatalf("重连失败: 设备锁")
default: default:
log.Fatalf("重连失败: %v", rsp.ErrorMessage) log.Errorf("重连失败: %v", rsp.ErrorMessage)
continue
} }
} }
log.Info("重连成功")
return return
}
log.Fatal("重连失败: 重连次数达到设置的上限值")
} }
b.Release() b.Release()
log.Fatalf("Bot已离线:%v", e.Message) log.Fatalf("Bot已离线:%v", e.Message)
......
...@@ -206,11 +206,21 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) { ...@@ -206,11 +206,21 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) { func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) {
if s.token != "" { if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token { if auth := r.URL.Query().Get("access_token"); auth != s.token && auth != "" {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
} else if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) == 2 {
if auth[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr) log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401) w.WriteHeader(401)
return return
} }
} else {
log.Warnf("已拒绝 %v 的 Websocket 请求: 空Token或传入格式错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
...@@ -235,11 +245,21 @@ func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) { ...@@ -235,11 +245,21 @@ func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) {
func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) { func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) {
if s.token != "" { if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token { if auth := r.URL.Query().Get("access_token"); auth != s.token && auth != "" {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
} else if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) == 2 {
if auth[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr) log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401) w.WriteHeader(401)
return return
} }
} else {
log.Warnf("已拒绝 %v 的 Websocket 请求: 空Token或传入格式错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
...@@ -253,11 +273,21 @@ func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) { ...@@ -253,11 +273,21 @@ func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) {
func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) { func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) {
if s.token != "" { if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token { if auth := r.URL.Query().Get("access_token"); auth != s.token && auth != "" {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
} else if auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2); len(auth) == 2 {
if auth[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr) log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401) w.WriteHeader(401)
return return
} }
} else {
log.Warnf("已拒绝 %v 的 Websocket 请求: 空Token或传入格式错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
} }
c, err := upgrader.Upgrade(w, r, nil) c, err := upgrader.Upgrade(w, r, nil)
if err != nil { if err != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment