1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-06 12:03:50 +08:00

reduce base64 alloc

This commit is contained in:
wdvxdr 2021-04-15 11:45:15 +08:00
parent 773d2b77e6
commit 223a888a34
No known key found for this signature in database
GPG Key ID: 55FF1414A69CEBA6
15 changed files with 38 additions and 39 deletions

View File

@ -953,7 +953,7 @@ func (bot *CQBot) CQGetImage(file string) MSG {
local := path.Join(global.CachePath, file+"."+path.Ext(msg["filename"].(string)))
if !global.PathExists(local) {
if data, err := global.GetBytes(msg["url"].(string)); err == nil {
_ = ioutil.WriteFile(local, data, 0644)
_ = ioutil.WriteFile(local, data, 0o644)
}
}
msg["file"] = local

View File

@ -1136,6 +1136,13 @@ 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 := base64.StdEncoding.DecodeString(strings.TrimPrefix(f, "base64://"))
if err != nil {
return nil, err
}
return &LocalImageElement{Stream: bytes.NewReader(b)}, nil
}
rawPath := path.Join(global.ImagePath, f)
if video {
rawPath = path.Join(global.VideoPath, f)
@ -1156,13 +1163,6 @@ func (bot *CQBot) makeImageOrVideoElem(d map[string]string, video, group bool) (
}
return &LocalVideoElement{File: rawPath}, nil
}
if strings.HasPrefix(f, "base64") {
b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(f, "base64://"))
if err != nil {
return nil, err
}
return &LocalImageElement{Stream: bytes.NewReader(b)}, nil
}
exist := global.PathExists(rawPath)
if !exist && global.PathExists(path.Join(global.ImagePathOld, f)) {
exist = true

View File

@ -539,7 +539,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.Filename)
w.WriteString(i.Url)
}), 0644)
}), 0o644)
}
i.Filename = filename
case *message.GroupImageElement:
@ -550,7 +550,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(i.Size))
w.WriteString(filename)
w.WriteString(i.Url)
}), 0644)
}), 0o644)
}
case *message.FriendImageElement:
filename := hex.EncodeToString(i.Md5) + ".image"
@ -560,7 +560,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(0)) // 发送时会调用url, 大概没事
w.WriteString(filename)
w.WriteString(i.Url)
}), 0644)
}), 0o644)
}
case *message.GroupFlashImgElement:
filename := hex.EncodeToString(i.Md5) + ".image"
@ -570,7 +570,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.Filename)
w.WriteString("")
}), 0644)
}), 0o644)
}
i.Filename = filename
case *message.FriendFlashImgElement:
@ -581,7 +581,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(i.Size))
w.WriteString(i.Filename)
w.WriteString("")
}), 0644)
}), 0o644)
}
i.Filename = filename
case *message.VoiceElement:
@ -593,7 +593,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
log.Warnf("语音文件 %v 下载失败: %v", i.Name, err)
continue
}
_ = ioutil.WriteFile(path.Join(global.VoicePath, i.Name), b, 0644)
_ = ioutil.WriteFile(path.Join(global.VoicePath, i.Name), b, 0o644)
}
case *message.ShortVideoElement:
filename := hex.EncodeToString(i.Md5) + ".video"
@ -605,7 +605,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement) {
w.WriteUInt32(uint32(i.ThumbSize))
w.WriteString(i.Name)
w.Write(i.Uuid)
}), 0644)
}), 0o644)
}
i.Name = filename
i.Url = bot.Client.GetShortVideoUrl(i.Uuid, i.Md5)

View File

@ -47,7 +47,7 @@ func EncodeToSilk(record []byte, tempName string, useCache bool) (silkWav []byte
}
if useCache {
silkPath := path.Join(silkCachePath, tempName+".silk")
err = ioutil.WriteFile(silkPath, silkWav, 0666)
err = ioutil.WriteFile(silkPath, silkWav, 0o666)
}
return
}

View File

@ -181,7 +181,7 @@ func generateConfig() {
sb.WriteString(pprofDefault)
}
}
_ = os.WriteFile("config.yml", []byte(sb.String()), 0644)
_ = os.WriteFile("config.yml", []byte(sb.String()), 0o644)
fmt.Println("默认配置文件已生成,请修改 config.yml 后重新启动!")
_, _ = input.ReadString('\n')
}

View File

@ -61,7 +61,7 @@ func ReadAllText(path string) string {
// WriteAllText 将给定text写入给定path
func WriteAllText(path, text string) error {
return ioutil.WriteFile(path, utils.S2B(text), 0644)
return ioutil.WriteFile(path, utils.S2B(text), 0o644)
}
// Check 检测err是否为nil
@ -94,7 +94,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
return ioutil.ReadFile(cacheFile)
}
data, err = GetBytes(file)
_ = ioutil.WriteFile(cacheFile, data, 0644)
_ = ioutil.WriteFile(cacheFile, data, 0o644)
if err != nil {
return nil, err
}

View File

@ -47,7 +47,7 @@ func (hook *LocalHook) pathWrite(entry *logrus.Entry) error {
return err
}
fd, err := os.OpenFile(hook.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
fd, err := os.OpenFile(hook.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
if err != nil {
return err
}

View File

@ -60,7 +60,7 @@ func GetBytes(url string) ([]byte, error) {
// DownloadFile 将给定URL对应的文件下载至给定Path
func DownloadFile(url, path string, limit int64, headers map[string]string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return err
}
@ -108,7 +108,7 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
// 初始化分块或直接下载
initOrDownload := func() error {
copyStream := func(s io.ReadCloser) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return err
}
@ -177,7 +177,7 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int,
// 下载分块
downloadBlock := func(block *BlockMetaData) error {
req, _ := http.NewRequest("GET", url, nil)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return err
}

View File

@ -51,7 +51,7 @@ func FromStream(updateWith io.Reader) (err error, errRecover error) {
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, 0755)
fp, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return
}

View File

@ -63,7 +63,7 @@ func qrcodeLogin() error {
if err != nil {
return err
}
_ = ioutil.WriteFile("qrcode.png", rsp.ImageData, 0644)
_ = ioutil.WriteFile("qrcode.png", rsp.ImageData, 0o644)
defer func() { _ = os.Remove("qrcode.png") }()
log.Infof("请使用手机QQ扫描二维码 (qrcode.png) : ")
time.Sleep(time.Second)
@ -132,7 +132,7 @@ func loginResponseProcessor(res *client.LoginResponse) error {
return qrcodeLogin()
case client.NeedCaptcha:
log.Warnf("登录需要验证码.")
_ = ioutil.WriteFile("captcha.jpg", res.CaptchaImage, 0644)
_ = ioutil.WriteFile("captcha.jpg", res.CaptchaImage, 0o644)
log.Warnf("请输入验证码 (captcha.jpg) (Enter 提交)")
text = readLine()
global.DelFile("captcha.jpg")

17
main.go
View File

@ -91,22 +91,22 @@ func init() {
log.AddHook(global.NewLocalHook(w, logFormatter, global.GetLogLevel(conf.Output.LogLevel)...))
if !global.PathExists(global.ImagePath) {
if err := os.MkdirAll(global.ImagePath, 0755); err != nil {
if err := os.MkdirAll(global.ImagePath, 0o755); err != nil {
log.Fatalf("创建图片缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VoicePath) {
if err := os.MkdirAll(global.VoicePath, 0755); err != nil {
if err := os.MkdirAll(global.VoicePath, 0o755); err != nil {
log.Fatalf("创建语音缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.VideoPath) {
if err := os.MkdirAll(global.VideoPath, 0755); err != nil {
if err := os.MkdirAll(global.VideoPath, 0o755); err != nil {
log.Fatalf("创建视频缓存文件夹失败: %v", err)
}
}
if !global.PathExists(global.CachePath) {
if err := os.MkdirAll(global.CachePath, 0755); err != nil {
if err := os.MkdirAll(global.CachePath, 0o755); err != nil {
log.Fatalf("创建发送图片缓存文件夹失败: %v", err)
}
}
@ -163,7 +163,7 @@ func main() {
if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
client.GenRandomDevice()
_ = ioutil.WriteFile("device.json", client.SystemDeviceInfo.ToJson(), 0644)
_ = ioutil.WriteFile("device.json", client.SystemDeviceInfo.ToJson(), 0o644)
log.Info("已生成设备信息并保存到 device.json 文件.")
} else {
log.Info("将使用 device.json 内的设备信息运行Bot.")
@ -182,7 +182,7 @@ func main() {
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)), 0644)
_ = os.WriteFile("password.encrypt", []byte(PasswordHashEncrypt(PasswordHash[:], byteKey)), 0o644)
log.Info("密码已加密,为了您的账号安全,请删除配置文件中的密码后重新启动.")
readLine()
os.Exit(0)
@ -278,7 +278,7 @@ func main() {
isTokenLogin := false
saveToken := func() {
AccountToken = cli.GenToken()
_ = ioutil.WriteFile("session.token", AccountToken, 0677)
_ = ioutil.WriteFile("session.token", AccountToken, 0o677)
}
if global.PathExists("session.token") {
token, err := ioutil.ReadFile("session.token")
@ -524,9 +524,8 @@ func selfUpdate(imageURL string) {
}(), func() string {
if runtime.GOOS == "windows" {
return "zip"
} else {
return "tar.gz"
}
return "tar.gz"
}())
var sum []byte
for {

View File

@ -387,7 +387,7 @@ func (c *webSocketConn) handleRequest(_ *coolq.CQBot, payload []byte) {
_ = c.Close()
}
}()
j := gjson.ParseBytes(payload)
j := gjson.Parse(utils.B2S(payload))
t := strings.ReplaceAll(j.Get("action").Str, "_async", "")
log.Debugf("WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw)
ret := c.apiCaller.callAPI(t, j.Get("params"))