1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00

coolq: new package cqcode

move cqcode escape&unescape to new package
This commit is contained in:
wdvxdr 2022-02-16 01:13:02 +08:00
parent 197ca5a3ea
commit 2a66896d43
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6
11 changed files with 192 additions and 219 deletions

View File

@ -1984,8 +1984,7 @@ func OK(data interface{}) global.MSG {
// Failed 生成失败返回值
func Failed(code int, msg ...string) global.MSG {
m := ""
w := ""
m, w := "", ""
if len(msg) > 0 {
m = msg[0]
}

View File

@ -13,38 +13,32 @@ import (
)
func convertGroupMemberInfo(groupID int64, m *client.GroupMemberInfo) global.MSG {
sex := "unknown"
if m.Gender == 1 { // unknown = 0xff
sex = "female"
} else if m.Gender == 0 {
sex = "male"
}
role := "member"
switch m.Permission { // nolint:exhaustive
case client.Owner:
role = "owner"
case client.Administrator:
role = "admin"
}
return global.MSG{
"group_id": groupID,
"user_id": m.Uin,
"nickname": m.Nickname,
"card": m.CardName,
"sex": func() string {
if m.Gender == 1 {
return "female"
} else if m.Gender == 0 {
return "male"
}
// unknown = 0xff
return "unknown"
}(),
"group_id": groupID,
"user_id": m.Uin,
"nickname": m.Nickname,
"card": m.CardName,
"sex": sex,
"age": 0,
"area": "",
"join_time": m.JoinTime,
"last_sent_time": m.LastSpeakTime,
"shut_up_timestamp": m.ShutUpTimestamp,
"level": strconv.FormatInt(int64(m.Level), 10),
"role": func() string {
switch m.Permission {
case client.Owner:
return "owner"
case client.Administrator:
return "admin"
case client.Member:
return "member"
default:
return "member"
}
}(),
"role": role,
"unfriendly": false,
"title": m.SpecialTitle,
"title_expire_time": m.SpecialTitleExpireTime,
@ -71,6 +65,10 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) global.MSG {
PrimaryID: uint64(m.GroupCode),
}
cqm := ToStringMessage(m.Elements, source, true)
postType := "message"
if m.Sender.Uin == bot.Client.Uin {
postType = "message_sent"
}
gm := global.MSG{
"anonymous": nil,
"font": 0,
@ -78,14 +76,9 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) global.MSG {
"message": ToFormattedMessage(m.Elements, source, false),
"message_type": "group",
"message_seq": m.Id,
"post_type": func() string {
if m.Sender.Uin == bot.Client.Uin {
return "message_sent"
}
return "message"
}(),
"raw_message": cqm,
"self_id": bot.Client.Uin,
"post_type": postType,
"raw_message": cqm,
"self_id": bot.Client.Uin,
"sender": global.MSG{
"age": 0,
"area": "",
@ -122,16 +115,14 @@ func (bot *CQBot) formatGroupMessage(m *message.GroupMessage) global.MSG {
}
}
ms := gm["sender"].(global.MSG)
switch mem.Permission {
role := "member"
switch mem.Permission { // nolint:exhaustive
case client.Owner:
ms["role"] = "owner"
role = "owner"
case client.Administrator:
ms["role"] = "admin"
case client.Member:
ms["role"] = "member"
default:
ms["role"] = "member"
role = "admin"
}
ms["role"] = role
ms["nickname"] = mem.Nickname
ms["card"] = mem.CardName
ms["title"] = mem.SpecialTitle

View File

@ -22,6 +22,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/coolq/cqcode"
"github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
@ -289,7 +290,7 @@ func ToStringMessage(e []message.IMessageElement, source MessageSource, isRaw ..
write("[CQ:reply,id=%d,seq=%d,qq=%d,time=%d,text=%s]",
db.ToGlobalID(rid, replyElem.ReplySeq),
replyElem.ReplySeq, replyElem.Sender, replyElem.Time,
CQCodeEscapeValue(ToStringMessage(replyElem.Elements, source)))
cqcode.EscapeValue(ToStringMessage(replyElem.Elements, source)))
} else {
write("[CQ:reply,id=%d]", db.ToGlobalID(rid, replyElem.ReplySeq))
}
@ -304,7 +305,7 @@ func ToStringMessage(e []message.IMessageElement, source MessageSource, isRaw ..
}
}
case *message.TextElement:
sb.WriteString(CQCodeEscapeText(o.Content))
sb.WriteString(cqcode.EscapeText(o.Content))
case *message.AtElement:
if o.Target == 0 {
write("[CQ:at,qq=all]")
@ -321,13 +322,13 @@ func ToStringMessage(e []message.IMessageElement, source MessageSource, isRaw ..
if ur {
write(`[CQ:record,file=%s]`, o.Name)
} else {
write(`[CQ:record,file=%s,url=%s]`, o.Name, CQCodeEscapeValue(o.Url))
write(`[CQ:record,file=%s,url=%s]`, o.Name, cqcode.EscapeValue(o.Url))
}
case *message.ShortVideoElement:
if ur {
write(`[CQ:video,file=%s]`, o.Name)
} else {
write(`[CQ:video,file=%s,url=%s]`, o.Name, CQCodeEscapeValue(o.Url))
write(`[CQ:video,file=%s,url=%s]`, o.Name, cqcode.EscapeValue(o.Url))
}
case *message.GroupImageElement:
var arg string
@ -340,7 +341,7 @@ func ToStringMessage(e []message.IMessageElement, source MessageSource, isRaw ..
if ur {
write("[CQ:image,file=%s%s]", hex.EncodeToString(o.Md5)+".image", arg)
} else {
write("[CQ:image,file=%s,url=%s%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeValue(o.Url), arg)
write("[CQ:image,file=%s,url=%s%s]", hex.EncodeToString(o.Md5)+".image", cqcode.EscapeValue(o.Url), arg)
}
case *message.FriendImageElement:
var arg string
@ -350,22 +351,22 @@ func ToStringMessage(e []message.IMessageElement, source MessageSource, isRaw ..
if ur {
write("[CQ:image,file=%s%s]", hex.EncodeToString(o.Md5)+".image", arg)
} else {
write("[CQ:image,file=%s,url=%s%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeValue(o.Url), arg)
write("[CQ:image,file=%s,url=%s%s]", hex.EncodeToString(o.Md5)+".image", cqcode.EscapeValue(o.Url), arg)
}
case *message.GuildImageElement:
write("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", CQCodeEscapeValue(o.Url))
write("[CQ:image,file=%s,url=%s]", hex.EncodeToString(o.Md5)+".image", cqcode.EscapeValue(o.Url))
case *message.DiceElement:
write("[CQ:dice,value=%v]", o.Value)
case *message.MarketFaceElement:
sb.WriteString(o.Name)
case *message.ServiceElement:
if isOk := strings.Contains(o.Content, "<?xml"); isOk {
write(`[CQ:xml,data=%s,resid=%d]`, CQCodeEscapeValue(o.Content), o.Id)
write(`[CQ:xml,data=%s,resid=%d]`, cqcode.EscapeValue(o.Content), o.Id)
} else {
write(`[CQ:json,data=%s,resid=%d]`, CQCodeEscapeValue(o.Content), o.Id)
write(`[CQ:json,data=%s,resid=%d]`, cqcode.EscapeValue(o.Content), o.Id)
}
case *message.LightAppElement:
write(`[CQ:json,data=%s]`, CQCodeEscapeValue(o.Content))
write(`[CQ:json,data=%s]`, cqcode.EscapeValue(o.Content))
case *message.AnimatedSticker:
write(`[CQ:face,id=%d,type=sticker]`, o.ID)
}
@ -609,11 +610,11 @@ func (bot *CQBot) ConvertStringMessage(raw string, sourceType MessageSourceType)
}
if i > 0 {
if base.SplitURL {
for _, txt := range param.SplitURL(CQCodeUnescapeText(raw[:i])) {
for _, txt := range param.SplitURL(cqcode.UnescapeText(raw[:i])) {
r = append(r, message.NewText(txt))
}
} else {
r = append(r, message.NewText(CQCodeUnescapeText(raw[:i])))
r = append(r, message.NewText(cqcode.UnescapeText(raw[:i])))
}
}
@ -658,7 +659,7 @@ func (bot *CQBot) ConvertStringMessage(raw string, sourceType MessageSourceType)
if i+1 > len(raw) {
return
}
d[key] = CQCodeUnescapeValue(raw[:i])
d[key] = cqcode.UnescapeValue(raw[:i])
raw = raw[i:]
i = 0
}
@ -1060,7 +1061,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, sourceType MessageSou
return message.NewDice(int32(i)), nil
case "xml":
resID := d["resid"]
template := CQCodeEscapeValue(d["data"])
template := cqcode.EscapeValue(d["data"])
i, _ := strconv.ParseInt(resID, 10, 64)
msg := message.NewRichXml(template, i)
return msg, nil
@ -1146,101 +1147,6 @@ func (bot *CQBot) ToElement(t string, d map[string]string, sourceType MessageSou
}
}
/*CQCodeEscapeText 将字符串raw中部分字符转义
& -> &amp;
[ -> &#91;
] -> &#93;
*/
func CQCodeEscapeText(s string) string {
count := strings.Count(s, "&")
count += strings.Count(s, "[")
count += strings.Count(s, "]")
if count == 0 {
return s
}
// Apply replacements to buffer.
var b strings.Builder
b.Grow(len(s) + count*4)
start := 0
for i := 0; i < count; i++ {
j := start
for index, r := range s[start:] {
if r == '&' || r == '[' || r == ']' {
j += index
break
}
}
b.WriteString(s[start:j])
switch s[j] {
case '&':
b.WriteString("&amp;")
case '[':
b.WriteString("&#91;")
case ']':
b.WriteString("&#93;")
}
start = j + 1
}
b.WriteString(s[start:])
return b.String()
}
/*CQCodeEscapeValue 将字符串value中部分字符转义
, -> &#44;
& -> &amp;
[ -> &#91;
] -> &#93;
*/
func CQCodeEscapeValue(value string) string {
ret := CQCodeEscapeText(value)
ret = strings.ReplaceAll(ret, ",", "&#44;")
return ret
}
/*CQCodeUnescapeText 将字符串content中部分字符反转义
&amp; -> &
&#91; -> [
&#93; -> ]
*/
func CQCodeUnescapeText(content string) string {
ret := content
ret = strings.ReplaceAll(ret, "&#91;", "[")
ret = strings.ReplaceAll(ret, "&#93;", "]")
ret = strings.ReplaceAll(ret, "&amp;", "&")
return ret
}
/*CQCodeUnescapeValue 将字符串content中部分字符反转义
&#44; -> ,
&amp; -> &
&#91; -> [
&#93; -> ]
*/
func CQCodeUnescapeValue(content string) string {
ret := strings.ReplaceAll(content, "&#44;", ",")
ret = CQCodeUnescapeText(ret)
return ret
}
// makeImageOrVideoElem 图片 elem 生成器,单独拎出来,用于公用
func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video bool, sourceType MessageSourceType) (message.IMessageElement, error) {
f := d["file"]

97
coolq/cqcode/escape.go Normal file
View File

@ -0,0 +1,97 @@
// Package cqcode provides CQCode util functions.
package cqcode
import "strings"
/*EscapeText 将字符串raw中部分字符转义
& -> &amp;
[ -> &#91;
] -> &#93;
*/
func EscapeText(s string) string {
count := strings.Count(s, "&")
count += strings.Count(s, "[")
count += strings.Count(s, "]")
if count == 0 {
return s
}
// Apply replacements to buffer.
var b strings.Builder
b.Grow(len(s) + count*4)
start := 0
for i := 0; i < count; i++ {
j := start
for index, r := range s[start:] {
if r == '&' || r == '[' || r == ']' {
j += index
break
}
}
b.WriteString(s[start:j])
switch s[j] {
case '&':
b.WriteString("&amp;")
case '[':
b.WriteString("&#91;")
case ']':
b.WriteString("&#93;")
}
start = j + 1
}
b.WriteString(s[start:])
return b.String()
}
/*EscapeValue 将字符串value中部分字符转义
, -> &#44;
& -> &amp;
[ -> &#91;
] -> &#93;
*/
func EscapeValue(value string) string {
ret := EscapeText(value)
return strings.ReplaceAll(ret, ",", "&#44;")
}
/*UnescapeText 将字符串content中部分字符反转义
&amp; -> &
&#91; -> [
&#93; -> ]
*/
func UnescapeText(content string) string {
ret := content
ret = strings.ReplaceAll(ret, "&#91;", "[")
ret = strings.ReplaceAll(ret, "&#93;", "]")
ret = strings.ReplaceAll(ret, "&amp;", "&")
return ret
}
/*UnescapeValue 将字符串content中部分字符反转义
&#44; -> ,
&amp; -> &
&#91; -> [
&#93; -> ]
*/
func UnescapeValue(content string) string {
ret := strings.ReplaceAll(content, "&#44;", ",")
return UnescapeText(ret)
}

View File

@ -8,6 +8,8 @@ import (
"github.com/Mrs4s/MiraiGo/utils"
"github.com/stretchr/testify/assert"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/coolq/cqcode"
)
var bot = CQBot{}
@ -41,7 +43,7 @@ const bText = `123456789[]&987654321[]&987654321[]&987654321[]&987654321[]&98765
func BenchmarkCQCodeEscapeText(b *testing.B) {
for i := 0; i < b.N; i++ {
ret := bText
CQCodeEscapeText(ret)
cqcode.EscapeText(ret)
}
}
@ -61,6 +63,6 @@ func TestCQCodeEscapeText(t *testing.T) {
ret = strings.ReplaceAll(ret, "&", "&amp;")
ret = strings.ReplaceAll(ret, "[", "&#91;")
ret = strings.ReplaceAll(ret, "]", "&#93;")
assert.Equal(t, ret, CQCodeEscapeText(rs))
assert.Equal(t, ret, cqcode.EscapeText(rs))
}
}

View File

@ -44,36 +44,13 @@ type reader struct {
func (r *reader) coder() coder { o, _ := r.data.ReadByte(); return coder(o) }
func (r *reader) varint() int64 { return r.data.varint() }
func (r *reader) uvarint() uint64 { return r.data.uvarint() }
func (r *reader) int32() int32 { return int32(r.varint()) }
func (r *reader) int64() int64 { return r.varint() }
func (r *reader) uint64() uint64 { return r.uvarint() }
func (r *reader) sync(c coder) {
if coder := r.coder(); coder != c {
panic("db/leveldb: bad sync expected " + strconv.Itoa(int(c)) + " but got " + strconv.Itoa(int(coder)))
}
}
func (r *reader) int() int {
return int(r.varint())
}
func (r *reader) uint() uint {
return uint(r.uvarint())
}
func (r *reader) int32() int32 {
return int32(r.varint())
}
func (r *reader) uint32() uint32 {
return uint32(r.uvarint())
}
func (r *reader) int64() int64 {
return r.varint()
}
func (r *reader) uint64() uint64 {
return r.uvarint()
}
// func (r *reader) uint32() uint32 { return uint32(r.uvarint()) }
// func (r *reader) int() int { return int(r.varint()) }
// func (r *reader) uint() uint { return uint(r.uvarint()) }
func (r *reader) string() string {
off := r.data.uvarint()

View File

@ -48,30 +48,12 @@ func (w *writer) coder(o coder) { w.data.WriteByte(byte(o)) }
func (w *writer) varint(x int64) { w.data.varint(x) }
func (w *writer) uvarint(x uint64) { w.data.uvarint(x) }
func (w *writer) nil() { w.coder(coderNil) }
func (w *writer) int(i int) {
w.varint(int64(i))
}
func (w *writer) uint(i uint) {
w.uvarint(uint64(i))
}
func (w *writer) int32(i int32) {
w.varint(int64(i))
}
func (w *writer) uint32(i uint32) {
w.uvarint(uint64(i))
}
func (w *writer) int64(i int64) {
w.varint(i)
}
func (w *writer) uint64(i uint64) {
w.uvarint(i)
}
func (w *writer) int(i int) { w.varint(int64(i)) }
func (w *writer) uint(i uint) { w.uvarint(uint64(i)) }
func (w *writer) int32(i int32) { w.varint(int64(i)) }
func (w *writer) uint32(i uint32) { w.uvarint(uint64(i)) }
func (w *writer) int64(i int64) { w.varint(i) }
func (w *writer) uint64(i uint64) { w.uvarint(i) }
func (w *writer) string(s string) {
off, ok := w.stringIndex[s]

2
go.mod
View File

@ -6,10 +6,8 @@ require (
github.com/Microsoft/go-winio v0.5.1
github.com/Mrs4s/MiraiGo v0.0.0-20220214082717-0e68a1e7b715
github.com/RomiChan/websocket v1.4.3-0.20220123145318-307a86b127bc
github.com/dustin/go-humanize v1.0.0
github.com/fumiama/go-hide-param v0.1.4
github.com/gabriel-vasile/mimetype v1.4.0
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/mattn/go-colorable v0.1.12
github.com/pkg/errors v0.9.1

11
go.sum
View File

@ -9,8 +9,6 @@ github.com/RomiChan/websocket v1.4.3-0.20220123145318-307a86b127bc/go.mod h1:OMm
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
@ -29,6 +27,7 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
@ -41,8 +40,6 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
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.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
@ -93,6 +90,7 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
github.com/tidwall/gjson v1.11.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.14.0 h1:6aeJ0bzojgWLa82gDQHcx3S0Lr/O51I9bJ5nv6JFx5w=
github.com/tidwall/gjson v1.14.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
@ -125,6 +123,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9 h1:0qxwC5n+ttVOINCBeRHO0nq9X7uy8SDsPoi5OaCdIEI=
golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -147,8 +146,10 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220111092808-5a964db01320 h1:0jf+tOCoZ3LyutmCOWpVni1chK4VfFLhRsDK7MhqGRY=
golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
@ -174,6 +175,8 @@ google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQ
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -7,13 +7,12 @@ import (
"fmt"
"hash"
"io"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/dustin/go-humanize"
"github.com/kardianos/osext"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
@ -147,13 +146,33 @@ func (wc *writeSumCounter) Write(p []byte) (int, error) {
wc.total += uint64(n)
wc.hash.Write(p)
fmt.Printf("\r ")
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.total))
fmt.Printf("\rDownloading... %s complete", humanBytes(wc.total))
return n, nil
}
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
func humanBytes(s uint64) string {
sizes := []string{"B", "kB", "MB", "GB"} // GB对于go-cqhttp来说已经够用了
if s < 10 {
return fmt.Sprintf("%d B", s)
}
e := math.Floor(logn(float64(s), 1000))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(1000, e)*10+0.5) / 10
f := "%.0f %s"
if val < 10 {
f = "%.1f %s"
}
return fmt.Sprintf(f, val, suffix)
}
// FromStream copy form getlantern/go-update
func fromStream(updateWith io.Reader) (err error, errRecover error) {
updatePath, err := osext.Executable()
updatePath, err := os.Executable()
updatePath = filepath.Clean(updatePath)
if err != nil {
return
}

View File

@ -51,7 +51,6 @@ type httpServerPost struct {
}
type httpServer struct {
HTTP *http.Server
api *api.Caller
accessToken string
}
@ -259,11 +258,11 @@ func runHTTP(bot *coolq.CQBot, node yaml.Node) {
go func() {
log.Infof("CQ HTTP 服务器已启动: %v", addr)
s.HTTP = &http.Server{
server := &http.Server{
Addr: addr,
Handler: s,
}
if err := s.HTTP.ListenAndServe(); err != nil && err != http.ErrServerClosed {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error(err)
log.Infof("HTTP 服务启动失败, 请检查端口是否被占用.")
log.Warnf("将在五秒后退出.")