Skip to content

Commit

Permalink
refactor: 优化文件判断逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
Redmomn committed Nov 9, 2024
1 parent dfaf81a commit 1aa0c25
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 22 deletions.
8 changes: 4 additions & 4 deletions cmd/gocq/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func LoginInteract() {
}
}

if !global.PathExists("session.token") {
if !global.FileExists("session.token") {
log.Info("不存在会话缓存,使用二维码登录.")
if !base.FastStart {
log.Warn("将在 5秒 后继续.")
Expand All @@ -130,7 +130,7 @@ func LoginInteract() {
log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.")
}
if !global.PathExists("device.json") {
if !global.FileExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
device = auth.NewDeviceInfo(int(crypto.RandU32()))
_ = device.Save("device.json")
Expand Down Expand Up @@ -159,7 +159,7 @@ func LoginInteract() {
base.AccountToken, _ = cli.Sig().Marshal()
_ = os.WriteFile("session.token", base.AccountToken, 0o644)
}
if global.PathExists("session.token") {
if global.FileExists("session.token") {
token, _ := os.ReadFile("session.token")
sig, err := auth.UnmarshalSigInfo(token, true)
if err == nil {
Expand Down Expand Up @@ -316,7 +316,7 @@ func newClient(appInfo *auth.AppInfo) *client.QQClient {
// log.Infof("收到服务器地址更新通知, 将在下一次重连时应用. ")
// return true
//})
if global.PathExists("address.txt") {
if global.FileExists("address.txt") {
log.Infof("检测到 address.txt 文件. 将覆盖目标IP.")
addr := global.ReadAddrFile("address.txt")
if len(addr) > 0 {
Expand Down
10 changes: 5 additions & 5 deletions coolq/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) g
// https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6
// @route(upload_group_file)
func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) global.MSG {
if !global.PathExists(file) {
if !global.FileExists(file) {
log.Warnf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在")
}
Expand All @@ -289,7 +289,7 @@ func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) gl
//
// @route(upload_private_file)
func (bot *CQBot) CQUploadPrivateFile(userID int64, file, name string) global.MSG {
if !global.PathExists(file) {
if !global.FileExists(file) {
log.Warnf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在")
}
Expand Down Expand Up @@ -1141,7 +1141,7 @@ func (bot *CQBot) CQGetImage(file string) global.MSG {
}

if b == nil {
if !global.PathExists(path.Join(global.ImagePath, file)) {
if !global.FileExists(path.Join(global.ImagePath, file)) {
return Failed(100)
}
b, err = os.ReadFile(path.Join(global.ImagePath, file))
Expand All @@ -1156,7 +1156,7 @@ func (bot *CQBot) CQGetImage(file string) global.MSG {
"url": r.ReadStringWithLength("u32", true),
}
local := path.Join(global.CachePath, file+path.Ext(msg["filename"].(string)))
if !global.PathExists(local) {
if !global.FileExists(local) {
r := download.Request{URL: msg["url"].(string)}
if err := r.WriteToFile(local); err != nil {
log.Warnf("下载图片 %v 时出现错误: %v", msg["url"], err)
Expand Down Expand Up @@ -1195,7 +1195,7 @@ func (bot *CQBot) CQDownloadFile(url string, headers gjson.Result, threadCount i

hash := md5.Sum([]byte(url))
file := path.Join(global.CachePath, hex.EncodeToString(hash[:])+".cache")
if global.PathExists(file) {
if global.FileExists(file) {
if err := os.Remove(file); err != nil {
log.Warnf("删除缓存文件 %v 时出现错误: %v", file, err)
return Failed(100, "DELETE_FILE_ERROR", err.Error())
Expand Down
6 changes: 3 additions & 3 deletions coolq/cqcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,7 @@ func (bot *CQBot) ConvertElement(spec *onebot.Spec, elem msg.Element, sourceType
_, _ = video.Seek(0, io.SeekStart)
hash, _ := crypto.ComputeMd5AndLength(video)
cacheFile := path.Join(global.CachePath, hex.EncodeToString(hash)+".mp4")
if !(elem.Get("cache") == "" || elem.Get("cache") == "1") || !global.PathExists(cacheFile) {
if !(elem.Get("cache") == "" || elem.Get("cache") == "1") || !global.FileExists(cacheFile) {
err = global.EncodeMP4(v.File, cacheFile)
if err != nil {
return nil, err
Expand Down Expand Up @@ -893,7 +893,7 @@ func (bot *CQBot) makeImageOrVideoElem(elem msg.Element, video bool, sourceType
maxSize = maxVideoSize
}
thread, _ := strconv.Atoi(elem.Get("c"))
exist := global.PathExists(cacheFile)
exist := global.FileExists(cacheFile)
if exist && (elem.Get("cache") == "" || elem.Get("cache") == "1") {
goto useCacheFile
}
Expand Down Expand Up @@ -963,7 +963,7 @@ func (bot *CQBot) makeImageOrVideoElem(elem msg.Element, video bool, sourceType
}
}
rawPath = path.Join(global.VideoPath, f)
if !global.PathExists(rawPath) {
if !global.FileExists(rawPath) {
return nil, errors.New("invalid video")
}
if path.Ext(rawPath) != ".video" {
Expand Down
2 changes: 1 addition & 1 deletion coolq/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ func (bot *CQBot) checkMedia(e []message.IMessageElement, source message.Source)
// todo: don't download original file?
i.Name = strings.ReplaceAll(i.Name, "{", "")
i.Name = strings.ReplaceAll(i.Name, "}", "")
if !global.PathExists(path.Join(global.VoicePath, i.Name)) {
if !global.FileExists(path.Join(global.VoicePath, i.Name)) {
err := download.Request{URL: i.Url}.WriteToFile(path.Join(global.VoicePath, i.Name))
if err != nil {
log.Warnf("语音文件 %v 下载失败: %v", i.Name, err)
Expand Down
2 changes: 1 addition & 1 deletion global/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func EncoderSilk(data []byte) ([]byte, error) {
return nil, errors.Wrap(err, "calc md5 failed")
}
tempName := hex.EncodeToString(h.Sum(nil))
if silkPath := path.Join("data/cache", tempName+".silk"); PathExists(silkPath) {
if silkPath := path.Join("data/cache", tempName+".silk"); FileExists(silkPath) {
return os.ReadFile(silkPath)
}
slk, err := base.EncodeSilk(data, tempName)
Expand Down
16 changes: 8 additions & 8 deletions global/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,16 @@ const (
HeaderSilk = "\x02#!SILK_V3"
)

// PathExists 判断给定path是否存在
// PathExists 判断给定path是否存在且path为路径
func PathExists(path string) bool {
_, err := os.Stat(path)
return err == nil || errors.Is(err, os.ErrExist)
file, err := os.Stat(path)
return (err == nil || errors.Is(err, os.ErrExist)) && file.IsDir()
}

// FileExists 判断给定path是否为存在且path为文件
func FileExists(path string) bool {
fi, err := os.Stat(path)
return err == nil && !fi.IsDir()
file, err := os.Stat(path)
return (err == nil || errors.Is(err, os.ErrExist)) && !file.IsDir()
}

// ReadAllText 读取给定path对应文件,无法读取时返回空值
Expand All @@ -70,7 +70,7 @@ func WriteAllText(path, text string) error {
// Check 检测err是否为nil
func Check(err error, deleteSession bool) {
if err != nil {
if deleteSession && PathExists("session.token") {
if deleteSession && FileExists("session.token") {
_ = os.Remove("session.token")
}
log.Fatalf("遇到错误: %v", err)
Expand All @@ -90,7 +90,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
case strings.HasPrefix(file, "http"): // https also has prefix http
hash := md5.Sum([]byte(file))
cacheFile := path.Join(CachePath, hex.EncodeToString(hash[:])+".cache")
if (cache == "" || cache == "1") && PathExists(cacheFile) {
if (cache == "" || cache == "1") && FileExists(cacheFile) {
return os.ReadFile(cacheFile)
}
err = download.Request{URL: file}.WriteToFile(cacheFile)
Expand Down Expand Up @@ -122,7 +122,7 @@ func FindFile(file, cache, p string) (data []byte, err error) {
if err != nil {
return nil, err
}
case PathExists(path.Join(p, file)):
case FileExists(path.Join(p, file)):
data, err = os.ReadFile(path.Join(p, file))
if err != nil {
return nil, err
Expand Down

0 comments on commit 1aa0c25

Please sign in to comment.