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

Compare commits

...

29 Commits

Author SHA1 Message Date
08567ec240 fix message history media. 2021-02-02 07:53:41 +08:00
08dea6dcf1 update MiraiGo. fix #604 2021-02-02 07:51:39 +08:00
252293afb9 update MiraiGo. fix #605 2021-02-02 07:22:38 +08:00
ca0b931fa4 update MiraiGo. 2021-02-02 07:13:42 +08:00
01dca0305c Merge branch 'master' into dev 2021-02-02 07:12:59 +08:00
6053918ee3 Merge branch 'dev' of https://github.com/Mrs4s/go-cqhttp into dev 2021-02-02 07:12:32 +08:00
e7547ed257 Merge pull request #601 from sam01101/patch-2
isFastStart setting appiled to config.hjson gen
2021-01-29 21:28:48 +08:00
96a036201d Move isFastStart outside 2021-01-29 15:16:31 +08:00
ccee8ac77a isFastStart setting appiled to config.hjson gen 2021-01-29 15:13:39 +08:00
ae806c53bb fix typo. 2021-01-28 20:54:38 +08:00
a9619b25bd Merge pull request #598 from wdvxdr1123/music_share
fix null json
2021-01-27 17:58:21 +08:00
69cda4e029 fix null json 2021-01-27 16:08:59 +08:00
dc18944a98 update MiraiGo. 2021-01-26 04:52:11 +08:00
717f816294 fix bugs. 2021-01-26 04:51:39 +08:00
430e734ff6 Merge pull request #591 from wdvxdr1123/music_share
simplify music share
2021-01-26 03:48:57 +08:00
21531fd70a Merge branch 'master' into dev 2021-01-26 03:47:42 +08:00
2214570c4f Merge pull request #590 from zkonge/master
增强保存密码安全性
2021-01-26 03:46:14 +08:00
18a839b699 update MiraiGo 2021-01-25 17:41:15 +08:00
23b90e288c better error 2021-01-25 17:34:23 +08:00
22c9a6728b Make golint happy 2021-01-25 17:05:51 +08:00
81ff71ee3b Merge pull request #580 from xuthus5/master
更加简明的logrus hook
2021-01-25 16:45:27 +08:00
bf65b576f3 update docs 2021-01-25 15:27:45 +08:00
817bb0e493 simplify music share
support Kugou,Kuwo custom
2021-01-25 15:06:30 +08:00
d2529a04c9 Enhance password security
No plain password left in memory, except first run
Attacker can't verify password correctness offline
2021-01-25 05:56:27 +08:00
13df58331c fix 2021-01-24 17:40:38 +08:00
61c9939f03 Merge remote-tracking branch 'upstream/master'
# Conflicts:
#	main.go
2021-01-24 17:29:26 +08:00
e19e797aac log support print report_line 2021-01-19 22:33:05 +08:00
aa54ed5610 reset default config log_level 2021-01-19 22:17:12 +08:00
360f7188e1 local log hook 2021-01-19 22:07:28 +08:00
13 changed files with 419 additions and 308 deletions

View File

@ -867,6 +867,7 @@ func (bot *CQBot) CQGetGroupMessageHistory(groupId int64, seq int64) MSG {
var ms []MSG var ms []MSG
for _, m := range msg { for _, m := range msg {
id := m.Id id := m.Id
bot.checkMedia(m.Elements)
if bot.db != nil { if bot.db != nil {
id = bot.InsertGroupMessage(m) id = bot.InsertGroupMessage(m)
} }

View File

@ -201,61 +201,8 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
bot.Client.SendGroupGift(uint64(groupId), uint64(i.Target), i.GiftId) bot.Client.SendGroupGift(uint64(groupId), uint64(i.Target), i.GiftId)
return 0 return 0
} }
if i, ok := elem.(*QQMusicElement); ok { if i, ok := elem.(*message.MusicShareElement); ok {
var msgStyle uint32 = 4 ret, err := bot.Client.SendGroupMusicShare(groupId, i)
if i.MusicUrl == "" {
msgStyle = 0 // fix vip song
}
ret, err := bot.Client.SendGroupRichMessage(groupId, 100497308, 1, msgStyle, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "com.tencent.qqmusic",
Signature: "cbd27cd7c861227d013a25b2d10f0799",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
if err != nil {
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
return -1
}
return bot.InsertGroupMessage(ret)
}
if i, ok := elem.(*CloudMusicElement); ok {
ret, err := bot.Client.SendGroupRichMessage(groupId, 100495085, 1, 4, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "com.netease.cloudmusic",
Signature: "da6b069da1e2982db3e386233f68d76d",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
if err != nil {
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
return -1
}
return bot.InsertGroupMessage(ret)
}
if i, ok := elem.(*MiguMusicElement); ok {
ret, err := bot.Client.SendGroupRichMessage(groupId, 1101053067, 1, 4, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "cmccwm.mobilemusic",
Signature: "6cdc72a439cef99a3418d2a78aa28c73",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
if err != nil { if err != nil {
log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err) log.Warnf("警告: 群 %v 富文本消息发送失败: %v", groupId, err)
return -1 return -1
@ -312,53 +259,8 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
newElem = append(newElem, gv) newElem = append(newElem, gv)
continue continue
} }
if i, ok := elem.(*QQMusicElement); ok { if i, ok := elem.(*message.MusicShareElement); ok {
var msgStyle uint32 = 4 bot.Client.SendFriendMusicShare(target, i)
if i.MusicUrl == "" {
msgStyle = 0 // fix vip song
}
bot.Client.SendFriendRichMessage(target, 100497308, 1, msgStyle, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "com.tencent.qqmusic",
Signature: "cbd27cd7c861227d013a25b2d10f0799",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
return 0
}
if i, ok := elem.(*CloudMusicElement); ok {
bot.Client.SendFriendRichMessage(target, 100495085, 1, 4, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "com.netease.cloudmusic",
Signature: "da6b069da1e2982db3e386233f68d76d",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
return 0
}
if i, ok := elem.(*MiguMusicElement); ok {
bot.Client.SendFriendRichMessage(target, 1101053067, 1, 4, client.RichClientInfo{
Platform: 1,
SdkVersion: "0.0.0",
PackageName: "cmccwm.mobilemusic",
Signature: "6cdc72a439cef99a3418d2a78aa28c73",
}, &message.RichMessage{
Title: i.Title,
Summary: i.Summary,
Url: i.Url,
PictureUrl: i.PictureUrl,
MusicUrl: i.MusicUrl,
})
return 0 return 0
} }
newElem = append(newElem, elem) newElem = append(newElem, elem)

View File

@ -49,26 +49,6 @@ type GiftElement struct {
GiftId message.GroupGift GiftId message.GroupGift
} }
type MusicElement struct {
Title string
Summary string
Url string
PictureUrl string
MusicUrl string
}
type QQMusicElement struct {
MusicElement
}
type CloudMusicElement struct {
MusicElement
}
type MiguMusicElement struct {
MusicElement
}
type LocalImageElement struct { type LocalImageElement struct {
message.ImageElement message.ImageElement
Stream io.ReadSeeker Stream io.ReadSeeker
@ -90,10 +70,6 @@ func (e *GiftElement) Type() message.ElementType {
return message.At return message.At
} }
func (e *MusicElement) Type() message.ElementType {
return message.Service
}
var GiftId = [...]message.GroupGift{ var GiftId = [...]message.GroupGift{
message.SweetWink, message.SweetWink,
message.HappyCola, message.HappyCola,
@ -699,7 +675,7 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
return nil, errors.New("song not found") return nil, errors.New("song not found")
} }
aid := strconv.FormatInt(info.Get("track_info.album.id").Int(), 10) aid := strconv.FormatInt(info.Get("track_info.album.id").Int(), 10)
name := info.Get("track_info.name").Str + " - " + info.Get("track_info.singer.0.name").Str name := info.Get("track_info.name").Str
mid := info.Get("track_info.mid").Str mid := info.Get("track_info.mid").Str
albumMid := info.Get("track_info.album.mid").Str albumMid := info.Get("track_info.album.mid").Str
pinfo, _ := global.GetBytes("http://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=2034008533&uin=0&format=json&data={\"comm\":{\"ct\":23,\"cv\":0},\"url_mid\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"4311206557\",\"songmid\":[\"" + mid + "\"],\"songtype\":[0],\"uin\":\"0\",\"loginflag\":1,\"platform\":\"23\"}}}&_=1599039471576") pinfo, _ := global.GetBytes("http://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=2034008533&uin=0&format=json&data={\"comm\":{\"ct\":23,\"cv\":0},\"url_mid\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"guid\":\"4311206557\",\"songmid\":[\"" + mid + "\"],\"songtype\":[0],\"uin\":\"0\",\"loginflag\":1,\"platform\":\"23\"}}}&_=1599039471576")
@ -709,17 +685,18 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
if len(aid) < 2 { if len(aid) < 2 {
return nil, errors.New("song error") return nil, errors.New("song error")
} }
content := "来自go-cqhttp" content := info.Get("track_info.singer.0.name").Str
if d["content"] != "" { if d["content"] != "" {
content = d["content"] content = d["content"]
} }
return &QQMusicElement{MusicElement: MusicElement{ return &message.MusicShareElement{
MusicType: message.QQMusic,
Title: name, Title: name,
Summary: content, Summary: content,
Url: jumpUrl, Url: jumpUrl,
PictureUrl: preview, PictureUrl: preview,
MusicUrl: purl, MusicUrl: purl,
}}, nil }, nil
} }
if d["type"] == "163" { if d["type"] == "163" {
info, err := global.NeteaseMusicSongInfo(d["id"]) info, err := global.NeteaseMusicSongInfo(d["id"])
@ -737,41 +714,36 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
if info.Get("artists.0").Exists() { if info.Get("artists.0").Exists() {
artistName = info.Get("artists.0.name").Str artistName = info.Get("artists.0.name").Str
} }
return &CloudMusicElement{MusicElement{ return &message.MusicShareElement{
MusicType: message.CloudMusic,
Title: name, Title: name,
Summary: artistName, Summary: artistName,
Url: jumpUrl, Url: jumpUrl,
PictureUrl: picUrl, PictureUrl: picUrl,
MusicUrl: musicUrl, MusicUrl: musicUrl,
}}, nil }, nil
} }
if d["type"] == "custom" { if d["type"] == "custom" {
if d["subtype"] == "qq" { if d["subtype"] != "" {
return &QQMusicElement{MusicElement{ var subtype = map[string]int{
"qq": message.QQMusic,
"163": message.CloudMusic,
"migu": message.MiguMusic,
"kugou": message.KugouMusic,
"kuwo": message.KuwoMusic,
}
var musicType = 0
if tp, ok := subtype[d["subtype"]]; ok {
musicType = tp
}
return &message.MusicShareElement{
MusicType: musicType,
Title: d["title"], Title: d["title"],
Summary: d["content"], Summary: d["content"],
Url: d["url"], Url: d["url"],
PictureUrl: d["image"], PictureUrl: d["image"],
MusicUrl: d["purl"], MusicUrl: d["purl"],
}}, nil }, nil
}
if d["subtype"] == "163" {
return &CloudMusicElement{MusicElement{
Title: d["title"],
Summary: d["content"],
Url: d["url"],
PictureUrl: d["image"],
MusicUrl: d["purl"],
}}, nil
}
if d["subtype"] == "migu" {
return &MiguMusicElement{MusicElement{
Title: d["title"],
Summary: d["content"],
Url: d["url"],
PictureUrl: d["image"],
MusicUrl: d["purl"],
}}, nil
} }
xml := fmt.Sprintf(`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="2" templateID="1" action="web" brief="[分享] %s" sourceMsgId="0" url="%s" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="%s" src="%s"/><title>%s</title><summary>%s</summary></item><source name="音乐" 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="%s" flag="0" adverSign="0" multiMsgFlag="0"><item layout="2"><audio cover="%s" src="%s"/><title>%s</title><summary>%s</summary></item><source name="音乐" 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>`,
XmlEscape(d["title"]), d["url"], d["image"], d["audio"], XmlEscape(d["title"]), XmlEscape(d["content"])) XmlEscape(d["title"]), d["url"], d["image"], d["audio"], XmlEscape(d["title"]), XmlEscape(d["content"]))

View File

@ -111,6 +111,54 @@ Type : `reply`
\ \
自定义回复示例: `[CQ:reply,text=Hello World,qq=10086,time=3376656000]` 自定义回复示例: `[CQ:reply,text=Hello World,qq=10086,time=3376656000]`
### 音乐分享 <Badge text="发"/>
```json
{
"type": "music",
"data": {
"type": "163",
"id": "28949129"
}
}
```
```
[CQ:music,type=163,id=28949129]
```
| 参数名 | 收 | 发 | 可能的值 | 说明 |
| --- | --- | --- | --- | --- |
| `type` | | ✓ | `qq` `163` | 分别表示使用 QQ 音乐、网易云音乐 |
| `id` | | ✓ | - | 歌曲 ID |
### 音乐自定义分享 <Badge text="发"/>
```json
{
"type": "music",
"data": {
"type": "custom",
"url": "http://baidu.com",
"audio": "http://baidu.com/1.mp3",
"title": "音乐标题"
}
}
```
```
[CQ:music,type=custom,url=http://baidu.com,audio=http://baidu.com/1.mp3,title=音乐标题]
```
| 参数名 | 收 | 发 | 可能的值 | 说明 |
| --- | --- | --- | --- | --- |
| `type` | | ✓ | `custom` | 表示音乐自定义分享 |
| `subtype` | | ✓ | `qq,163,migu,kugou,kuwo` | 表示分享类型不填写发送为xml卡片推荐填写提高稳定性 |
| `url` | | ✓ | - | 点击后跳转目标 URL |
| `audio` | | ✓ | - | 音乐 URL |
| `title` | | ✓ | - | 标题 |
| `content` | | ✓ | - | 内容描述 |
| `image` | | ✓ | - | 图片 URL |
### 红包 ### 红包

View File

@ -2,13 +2,13 @@ package global
import ( import (
"crypto/md5" "crypto/md5"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os/exec" "os/exec"
"path" "path"
"github.com/Mrs4s/go-cqhttp/global/codec" "github.com/Mrs4s/go-cqhttp/global/codec"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -32,7 +32,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
h := md5.New() h := md5.New()
_, err := h.Write(data) _, err := h.Write(data)
if err != nil { if err != nil {
return nil, err return nil, errors.Wrap(err, "calc md5 failed")
} }
tempName := fmt.Sprintf("%x", h.Sum(nil)) tempName := fmt.Sprintf("%x", h.Sum(nil))
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) { if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
@ -40,7 +40,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
} }
slk, err := codec.EncodeToSilk(data, tempName, true) slk, err := codec.EncodeToSilk(data, tempName, true)
if err != nil { if err != nil {
return nil, err return nil, errors.Wrap(err, "encode silk failed")
} }
return slk, nil return slk, nil
} }
@ -51,7 +51,7 @@ func EncodeMP4(src string, dst string) error { // -y 覆盖文件
err := cmd1.Run() err := cmd1.Run()
if err != nil { if err != nil {
cmd2 := exec.Command("ffmpeg", "-i", src, "-y", "-c:v", "h264", "-c:a", "mp3", dst) cmd2 := exec.Command("ffmpeg", "-i", src, "-y", "-c:v", "h264", "-c:a", "mp3", dst)
return cmd2.Run() return errors.Wrap(cmd2.Run(), "convert mp4 failed")
} }
return err return err
} }
@ -59,5 +59,5 @@ func EncodeMP4(src string, dst string) error { // -y 覆盖文件
//ExtractCover 获取给定视频文件的Cover //ExtractCover 获取给定视频文件的Cover
func ExtractCover(src string, target string) error { func ExtractCover(src string, target string) error {
cmd := exec.Command("ffmpeg", "-i", src, "-y", "-r", "1", "-f", "image2", target) cmd := exec.Command("ffmpeg", "-i", src, "-y", "-r", "1", "-f", "image2", target)
return cmd.Run() return errors.Wrap(cmd.Run(), "extract video cover failed")
} }

View File

@ -4,7 +4,7 @@
package codec package codec
import ( import (
"errors" "github.com/pkg/errors"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os" "os"
@ -63,7 +63,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error)
rawPath := path.Join(silkCachePath, tempName+".wav") rawPath := path.Join(silkCachePath, tempName+".wav")
err := ioutil.WriteFile(rawPath, record, os.ModePerm) err := ioutil.WriteFile(rawPath, record, os.ModePerm)
if err != nil { if err != nil {
return nil, err return nil, errors.Wrap(err, "write temp file error")
} }
defer os.Remove(rawPath) defer os.Remove(rawPath)
@ -71,7 +71,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error)
pcmPath := path.Join(silkCachePath, tempName+".pcm") pcmPath := path.Join(silkCachePath, tempName+".pcm")
cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath) cmd := exec.Command("ffmpeg", "-i", rawPath, "-f", "s16le", "-ar", "24000", "-ac", "1", pcmPath)
if err = cmd.Run(); err != nil { if err = cmd.Run(); err != nil {
return nil, err return nil, errors.Wrap(err, "convert pcm file error")
} }
defer os.Remove(pcmPath) defer os.Remove(pcmPath)
@ -79,7 +79,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) ([]byte, error)
silkPath := path.Join(silkCachePath, tempName+".silk") silkPath := path.Join(silkCachePath, tempName+".silk")
cmd = exec.Command(getEncoderFilePath(), pcmPath, silkPath, "-rate", "24000", "-quiet", "-tencent") cmd = exec.Command(getEncoderFilePath(), pcmPath, silkPath, "-rate", "24000", "-quiet", "-tencent")
if err = cmd.Run(); err != nil { if err = cmd.Run(); err != nil {
return nil, err return nil, errors.Wrap(err, "convert silk file error")
} }
if !useCache { if !useCache {
defer os.Remove(silkPath) defer os.Remove(silkPath)

View File

@ -119,8 +119,8 @@ var DefaultConfigWithComments = `
use_sso_address: false use_sso_address: false
// 是否启用 DEBUG // 是否启用 DEBUG
debug: false debug: false
// 日志等级 // 日志等级 trace,debug,info,warn,error
log_level: "" log_level: "info"
// WebUi 设置 // WebUi 设置
web_ui: { web_ui: {
// 是否启用 WebUi // 是否启用 WebUi
@ -135,6 +135,9 @@ var DefaultConfigWithComments = `
} }
` `
//PasswordHash 存储QQ密码哈希供登录使用
var PasswordHash [16]byte
//JSONConfig Config对应的结构体 //JSONConfig Config对应的结构体
type JSONConfig struct { type JSONConfig struct {
Uin int64 `json:"uin"` Uin int64 `json:"uin"`
@ -274,8 +277,8 @@ func DefaultConfig() *JSONConfig {
} }
} }
//Load 加载配置文件 //LoadConfig 加载配置文件
func Load(p string) *JSONConfig { func LoadConfig(p string) *JSONConfig {
if !PathExists(p) { if !PathExists(p) {
log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p) log.Warnf("尝试加载配置文件 %v 失败: 文件不存在", p)
return nil return nil

View File

@ -25,12 +25,18 @@ func (m MSG) Get(s string) MSG {
} }
return MSG{"__str__": v} // 用这个名字应该没问题吧 return MSG{"__str__": v} // 用这个名字应该没问题吧
} }
return MSG{} return nil // 不存在为空
} }
//String 将消息Map转化为String。若Map存在key "__str__",则返回此key对应的值,否则将输出整张消息Map对应的JSON字符串 //String 将消息Map转化为String。若Map存在key "__str__",则返回此key对应的值,否则将输出整张消息Map对应的JSON字符串
func (m MSG) String() string { func (m MSG) String() string {
if m == nil {
return "" // 空 JSON
}
if str, ok := m["__str__"]; ok { if str, ok := m["__str__"]; ok {
if str == nil {
return "" // 空 JSON
}
return fmt.Sprint(str) return fmt.Sprint(str)
} }
str, _ := json.MarshalToString(m) str, _ := json.MarshalToString(m)

153
global/log_hook.go Normal file
View File

@ -0,0 +1,153 @@
package global
import (
"fmt"
"github.com/sirupsen/logrus"
"io"
"os"
"path/filepath"
"reflect"
"sync"
)
type LocalHook struct {
lock *sync.Mutex
levels []logrus.Level // hook级别
formatter logrus.Formatter // 格式
path string // 写入path
writer io.Writer // io
}
// ref: logrus/hooks.go. impl Hook interface
func (hook *LocalHook) Levels() []logrus.Level {
if len(hook.levels) == 0 {
return logrus.AllLevels
}
return hook.levels
}
func (hook *LocalHook) ioWrite(entry *logrus.Entry) error {
log, err := hook.formatter.Format(entry)
if err != nil {
return err
}
_, err = hook.writer.Write(log)
if err != nil {
return err
}
return nil
}
func (hook *LocalHook) pathWrite(entry *logrus.Entry) error {
dir := filepath.Dir(hook.path)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
fd, err := os.OpenFile(hook.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
defer fd.Close()
log, err := hook.formatter.Format(entry)
if err != nil {
return err
}
_, err = fd.Write(log)
return err
}
func (hook *LocalHook) Fire(entry *logrus.Entry) error {
hook.lock.Lock()
defer hook.lock.Unlock()
if hook.writer != nil {
return hook.ioWrite(entry)
}
if hook.path != "" {
return hook.pathWrite(entry)
}
return nil
}
func (hook *LocalHook) SetFormatter(formatter logrus.Formatter) {
hook.lock.Lock()
defer hook.lock.Unlock()
if formatter == nil {
// 用默认的
formatter = &logrus.TextFormatter{DisableColors: true}
} else {
switch f := formatter.(type) {
case *logrus.TextFormatter:
textFormatter := f
textFormatter.DisableColors = true
default:
// todo
}
}
logrus.SetFormatter(formatter)
hook.formatter = formatter
}
func (hook *LocalHook) SetWriter(writer io.Writer) {
hook.lock.Lock()
defer hook.lock.Unlock()
hook.writer = writer
}
func (hook *LocalHook) SetPath(path string) {
hook.lock.Lock()
defer hook.lock.Unlock()
hook.path = path
}
func NewLocalHook(args interface{}, formatter logrus.Formatter, levels ...logrus.Level) *LocalHook {
hook := &LocalHook{
lock: new(sync.Mutex),
}
hook.SetFormatter(formatter)
hook.levels = append(hook.levels, levels...)
switch arg := args.(type) {
case string:
hook.SetPath(arg)
case io.Writer:
hook.SetWriter(arg)
default:
panic(fmt.Sprintf("unsupported type: %v", reflect.TypeOf(args)))
}
return hook
}
func GetLogLevel(level string) []logrus.Level {
switch level {
case "trace":
return []logrus.Level{logrus.TraceLevel, logrus.DebugLevel,
logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel}
case "debug":
return []logrus.Level{logrus.DebugLevel, logrus.InfoLevel,
logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel}
case "info":
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
case "warn":
return []logrus.Level{logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel}
case "error":
return []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel,
logrus.PanicLevel}
default:
return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel,
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel}
}
}

5
go.mod
View File

@ -3,24 +3,25 @@ module github.com/Mrs4s/go-cqhttp
go 1.15 go 1.15
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20210124065645-9549a32d954a github.com/Mrs4s/MiraiGo v0.0.0-20210201234941-c69e578d0815
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/gin-contrib/pprof v1.3.0 github.com/gin-contrib/pprof v1.3.0
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.4 github.com/guonaihong/gout v0.1.4
github.com/hjson/hjson-go v3.1.0+incompatible github.com/hjson/hjson-go v3.1.0+incompatible
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/json-iterator/go v1.1.10 github.com/json-iterator/go v1.1.10
github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.4 // indirect github.com/lestrrat-go/strftime v1.0.4 // indirect
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.7.0 github.com/sirupsen/logrus v1.7.0
github.com/syndtr/goleveldb v1.0.0 github.com/syndtr/goleveldb v1.0.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/tidwall/gjson v1.6.7 github.com/tidwall/gjson v1.6.7
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/crypto v0.0.0-20190308221718-c2843e01d9a2
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 golang.org/x/time v0.0.0-20201208040808-7e3f01d25324
) )

8
go.sum
View File

@ -1,7 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Mrs4s/MiraiGo v0.0.0-20210124065645-9549a32d954a h1:ov5QCDpZpsr+geKLVON7E63UqrpNF0oTiKuZwbKwEmo= github.com/Mrs4s/MiraiGo v0.0.0-20210201234941-c69e578d0815 h1:WW2YfA+0+LSa/0VlWVhnfrXXatcE09paHgPgfPxlIMk=
github.com/Mrs4s/MiraiGo v0.0.0-20210124065645-9549a32d954a/go.mod h1:9V7DdSwpEfCKQNvLZhRnFJFkelTU0tPLfwR5l6UFF1Y= github.com/Mrs4s/MiraiGo v0.0.0-20210201234941-c69e578d0815/go.mod h1:yhqA0NyKxUf7I/0HR/1OMchveFggX8wde04gqdGrNfU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -55,6 +55,7 @@ github.com/guonaihong/gout v0.1.4/go.mod h1:0rFYAYyzbcxEg11eY2qUbffJs7hHRPeugAnl
github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw= github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw=
github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio= github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@ -84,8 +85,6 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 h1:mZHayPoR0lNmnHyvtYjDeq0zlVHn9K/ZXoy17ylucdo=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5/go.mod h1:GEXHk5HgEKCvEIIrSpFI3ozzG5xOKA2DVlEX/gGnewM=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM= github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
@ -110,6 +109,7 @@ github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk= github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I= github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=

293
main.go
View File

@ -2,8 +2,11 @@ package main
import ( import (
"bufio" "bufio"
"crypto/aes"
"crypto/md5" "crypto/md5"
"crypto/sha1"
"encoding/base64" "encoding/base64"
"encoding/hex"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -22,6 +25,7 @@ import (
"github.com/Mrs4s/go-cqhttp/server" "github.com/Mrs4s/go-cqhttp/server"
"github.com/guonaihong/gout" "github.com/guonaihong/gout"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/term" "golang.org/x/term"
"github.com/Mrs4s/MiraiGo/binary" "github.com/Mrs4s/MiraiGo/binary"
@ -30,42 +34,15 @@ import (
"github.com/Mrs4s/go-cqhttp/global" "github.com/Mrs4s/go-cqhttp/global"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
rotatelogs "github.com/lestrrat-go/file-rotatelogs" rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
easy "github.com/t-tomalak/logrus-easy-formatter" easy "github.com/t-tomalak/logrus-easy-formatter"
) )
var json = jsoniter.ConfigCompatibleWithStandardLibrary var json = jsoniter.ConfigCompatibleWithStandardLibrary
var conf *global.JSONConfig
var isFastStart = false
func init() { func init() {
log.SetFormatter(&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
})
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotatelogs.WithRotationTime(time.Hour*24))
if err == nil {
log.SetOutput(io.MultiWriter(os.Stderr, w))
}
if !global.PathExists(global.ImagePath) {
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
log.Fatalf("创建图片缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VoicePath) {
if err := os.MkdirAll(global.VoicePath, 0755); err != nil {
log.Fatalf("创建语音缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VideoPath) {
if err := os.MkdirAll(global.VideoPath, 0755); err != nil {
log.Fatalf("创建视频缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.CachePath) {
if err := os.MkdirAll(global.CachePath, 0755); err != nil {
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
}
}
if global.PathExists("cqhttp.json") { if global.PathExists("cqhttp.json") {
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.") log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.hjson 文件.") log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.hjson 文件.")
@ -95,12 +72,54 @@ func init() {
} }
_ = os.Remove("cqhttp.json") _ = os.Remove("cqhttp.json")
} }
conf = getConfig()
if conf == nil {
os.Exit(1)
}
logFormatter := &easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
}
w, err := rotatelogs.New(path.Join("logs", "%Y-%m-%d.log"), rotatelogs.WithRotationTime(time.Hour*24))
if err != nil {
log.Errorf("rotatelogs init err: %v", err)
panic(err)
}
// 在debug模式下,将在标准输出中打印当前执行行数
if conf.Debug {
log.SetReportCaller(true)
}
log.AddHook(global.NewLocalHook(w, logFormatter, global.GetLogLevel(conf.LogLevel)...))
if !global.PathExists(global.ImagePath) {
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
log.Fatalf("创建图片缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VoicePath) {
if err := os.MkdirAll(global.VoicePath, 0755); err != nil {
log.Fatalf("创建语音缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VideoPath) {
if err := os.MkdirAll(global.VideoPath, 0755); err != nil {
log.Fatalf("创建视频缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.CachePath) {
if err := os.MkdirAll(global.CachePath, 0755); err != nil {
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
}
}
} }
func main() { func main() {
var byteKey []byte var byteKey []byte
var isFastStart = false
arg := os.Args arg := os.Args
if len(arg) > 1 { if len(arg) > 1 {
for i := range arg { for i := range arg {
@ -122,91 +141,12 @@ func main() {
} }
} }
var conf *global.JSONConfig
if global.PathExists("config.json") {
conf = global.Load("config.json")
_ = conf.Save("config.hjson")
_ = os.Remove("config.json")
} else if os.Getenv("UIN") != "" {
log.Infof("将从环境变量加载配置.")
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
pwd := os.Getenv("PASS")
post := os.Getenv("HTTP_POST")
conf = &global.JSONConfig{
Uin: uin,
Password: pwd,
HTTPConfig: &global.GoCQHTTPConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 5700,
PostUrls: map[string]string{},
},
WSConfig: &global.GoCQWebSocketConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 6700,
},
PostMessageFormat: "string",
Debug: os.Getenv("DEBUG") == "true",
}
if post != "" {
conf.HTTPConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
}
} else {
conf = global.Load("config.hjson")
}
if conf == nil {
err := global.WriteAllText("config.hjson", global.DefaultConfigWithComments)
if err != nil {
log.Fatalf("创建默认配置文件时出现错误: %v", err)
return
}
log.Infof("默认配置文件已生成, 请编辑 config.hjson 后重启程序.")
time.Sleep(time.Second * 5)
return
}
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") { if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
log.Warnf("请修改 config.hjson 以添加账号密码.") log.Warnf("请修改 config.hjson 以添加账号密码.")
time.Sleep(time.Second * 5) if (!isFastStart) {
return time.Sleep(time.Second * 5)
}
// log classified by level
// Collect all records up to the specified level (default level: warn)
logLevel := conf.LogLevel
if logLevel != "" {
date := time.Now().Format("2006-01-02")
var logPathMap lfshook.PathMap
switch conf.LogLevel {
case "warn":
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
case "error":
logPathMap = lfshook.PathMap{
log.ErrorLevel: path.Join("logs", date+"-error.log"),
log.FatalLevel: path.Join("logs", date+"-error.log"),
log.PanicLevel: path.Join("logs", date+"-error.log"),
}
default:
logPathMap = lfshook.PathMap{
log.WarnLevel: path.Join("logs", date+"-warn.log"),
log.ErrorLevel: path.Join("logs", date+"-warn.log"),
log.FatalLevel: path.Join("logs", date+"-warn.log"),
log.PanicLevel: path.Join("logs", date+"-warn.log"),
}
} }
return
log.AddHook(lfshook.NewHook(
logPathMap,
&easy.Formatter{
TimestampFormat: "2006-01-02 15:04:05",
LogFormat: "[%time%] [%lvl%]: %msg% \n",
},
))
} }
log.Info("当前版本:", coolq.Version) log.Info("当前版本:", coolq.Version)
@ -233,15 +173,11 @@ func main() {
} }
if conf.EncryptPassword && conf.PasswordEncrypted == "" { if conf.EncryptPassword && conf.PasswordEncrypted == "" {
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)") log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
byteKey, _ := term.ReadPassword(int(os.Stdin.Fd())) byteKey, _ = term.ReadPassword(int(os.Stdin.Fd()))
key := md5.Sum(byteKey) global.PasswordHash = md5.Sum([]byte(conf.Password))
if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" { conf.Password = ""
conf.Password = "" conf.PasswordEncrypted = "AES:" + PasswordHashEncrypt(global.PasswordHash[:], byteKey)
conf.PasswordEncrypted = encrypted _ = conf.Save("config.hjson")
_ = conf.Save("config.hjson")
} else {
log.Warnf("加密时出现问题.")
}
} }
if conf.PasswordEncrypted != "" { if conf.PasswordEncrypted != "" {
if len(byteKey) == 0 { if len(byteKey) == 0 {
@ -262,8 +198,25 @@ func main() {
} else { } else {
log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.") log.Infof("密码加密已启用, 使用运行时传递的参数进行解密,按 Ctrl+C 取消.")
} }
key := md5.Sum(byteKey)
conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:]) //升级客户端密码加密方案MD5+TEA 加密密码 -> PBKDF2+AES 加密 MD5
//升级后的 PasswordEncrypted 字符串以"AES:"开始,其后为 Hex 编码的16字节加密 MD5
if !strings.HasPrefix(conf.PasswordEncrypted, "AES:") {
password := OldPasswordDecrypt(conf.PasswordEncrypted, byteKey)
passwordHash := md5.Sum([]byte(password))
newPasswordHash := PasswordHashEncrypt(passwordHash[:], byteKey)
conf.PasswordEncrypted = "AES:" + newPasswordHash
_ = conf.Save("config.hjson")
log.Debug("密码加密方案升级完成")
}
ph, err := PasswordHashDecrypt(conf.PasswordEncrypted[4:], byteKey)
if err != nil {
log.Fatalf("加密存储的密码损坏,请尝试重新配置密码")
}
copy(global.PasswordHash[:], ph)
} else {
global.PasswordHash = md5.Sum([]byte(conf.Password))
} }
if !isFastStart { if !isFastStart {
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.") log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
@ -283,7 +236,7 @@ func main() {
} }
return "未知" return "未知"
}()) }())
cli := client.NewClient(conf.Uin, conf.Password) cli := client.NewClientMd5(conf.Uin, global.PasswordHash)
cli.OnLog(func(c *client.QQClient, e *client.LogEvent) { cli.OnLog(func(c *client.QQClient, e *client.LogEvent) {
switch e.Type { switch e.Type {
case "INFO": case "INFO":
@ -340,27 +293,50 @@ func main() {
} }
} }
//EncryptPwd 通过给定key加密给定pwd // PasswordHashEncrypt 使用key加密给定passwordHash
func EncryptPwd(pwd string, key []byte) string { func PasswordHashEncrypt(passwordHash []byte, key []byte) string {
tea := binary.NewTeaCipher(key) if len(passwordHash) != 16 {
if tea == nil { panic("密码加密参数错误")
return ""
} }
return base64.StdEncoding.EncodeToString(tea.Encrypt([]byte(pwd)))
key = pbkdf2.Key(key, key, 114514, 32, sha1.New)
cipher, _ := aes.NewCipher(key)
result := make([]byte, 16)
cipher.Encrypt(result, passwordHash)
return hex.EncodeToString(result)
} }
//DecryptPwd 通过给定key解密给定ePwd // PasswordHashDecrypt 使用key解密给定passwordHash
func DecryptPwd(ePwd string, key []byte) string { func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, error) {
ciphertext, err := hex.DecodeString(encryptedPasswordHash)
if err != nil {
return nil, err
}
key = pbkdf2.Key(key, key, 114514, 32, sha1.New)
cipher, _ := aes.NewCipher(key)
result := make([]byte, 16)
cipher.Decrypt(result, ciphertext)
return result, nil
}
// OldPasswordDecrypt 使用key解密老password仅供兼容使用
func OldPasswordDecrypt(encryptedPassword string, key []byte) string {
defer func() { defer func() {
if pan := recover(); pan != nil { if pan := recover(); pan != nil {
log.Fatalf("密码解密失败: %v", pan) log.Fatalf("密码解密失败: %v", pan)
} }
}() }()
encrypted, err := base64.StdEncoding.DecodeString(ePwd) encKey := md5.Sum(key)
encrypted, err := base64.StdEncoding.DecodeString(encryptedPassword)
if err != nil { if err != nil {
panic(err) panic(err)
} }
tea := binary.NewTeaCipher(key) tea := binary.NewTeaCipher(encKey[:])
if tea == nil { if tea == nil {
panic("密钥错误") panic("密钥错误")
} }
@ -491,3 +467,52 @@ func restart(Args []string) {
} }
_ = cmd.Start() _ = cmd.Start()
} }
func getConfig() *global.JSONConfig {
var conf *global.JSONConfig
if global.PathExists("config.json") {
conf = global.LoadConfig("config.json")
_ = conf.Save("config.hjson")
_ = os.Remove("config.json")
} else if os.Getenv("UIN") != "" {
log.Infof("将从环境变量加载配置.")
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
pwd := os.Getenv("PASS")
post := os.Getenv("HTTP_POST")
conf = &global.JSONConfig{
Uin: uin,
Password: pwd,
HTTPConfig: &global.GoCQHTTPConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 5700,
PostUrls: map[string]string{},
},
WSConfig: &global.GoCQWebSocketConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 6700,
},
PostMessageFormat: "string",
Debug: os.Getenv("DEBUG") == "true",
}
if post != "" {
conf.HTTPConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
}
} else {
conf = global.LoadConfig("config.hjson")
}
if conf == nil {
err := global.WriteAllText("config.hjson", global.DefaultConfigWithComments)
if err != nil {
log.Fatalf("创建默认配置文件时出现错误: %v", err)
return nil
}
log.Infof("默认配置文件已生成, 请编辑 config.hjson 后重启程序.")
if (!isFastStart) {
time.Sleep(time.Second * 5)
}
return nil
}
return conf
}

View File

@ -333,7 +333,7 @@ func GetConf() *global.JSONConfig {
if JSONConfig != nil { if JSONConfig != nil {
return JSONConfig return JSONConfig
} }
conf := global.Load("config.hjson") conf := global.LoadConfig("config.hjson")
return conf return conf
} }