sub2clash/utils/sub.go

86 lines
1.7 KiB
Go
Raw Normal View History

2023-09-12 18:40:24 +08:00
package utils
import (
2023-09-17 15:52:37 +08:00
"crypto/sha256"
2023-09-12 18:40:24 +08:00
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
2023-09-13 13:47:22 +08:00
"sub2clash/config"
2023-09-13 00:46:17 +08:00
"sync"
2023-09-12 18:40:24 +08:00
"time"
)
var subsDir = "subs"
2023-09-13 00:46:17 +08:00
var fileLock sync.RWMutex
2023-09-12 18:40:24 +08:00
func LoadSubscription(url string, refresh bool) ([]byte, error) {
if refresh {
return FetchSubscriptionFromAPI(url)
}
2023-09-17 15:52:37 +08:00
hash := sha256.Sum224([]byte(url))
2023-09-13 00:46:17 +08:00
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
2023-09-12 18:40:24 +08:00
stat, err := os.Stat(fileName)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return FetchSubscriptionFromAPI(url)
}
lastGetTime := stat.ModTime().Unix() // 单位是秒
2023-09-13 13:47:22 +08:00
if lastGetTime+config.Default.CacheExpire > time.Now().Unix() {
2023-09-12 18:40:24 +08:00
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
2023-09-23 01:31:04 +08:00
if file != nil {
_ = file.Close()
}
2023-09-12 18:40:24 +08:00
}(file)
2023-09-13 00:46:17 +08:00
fileLock.RLock()
defer fileLock.RUnlock()
2023-09-12 18:40:24 +08:00
subContent, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return subContent, nil
}
return FetchSubscriptionFromAPI(url)
}
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
2023-09-17 15:52:37 +08:00
hash := sha256.Sum224([]byte(url))
2023-09-13 00:46:17 +08:00
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
resp, err := Get(url)
2023-09-12 18:40:24 +08:00
if err != nil {
return nil, err
}
2023-09-13 13:47:22 +08:00
defer func(Body io.ReadCloser) {
2023-09-23 01:31:04 +08:00
if Body != nil {
_ = Body.Close()
}
2023-09-13 13:47:22 +08:00
}(resp.Body)
2023-09-12 18:40:24 +08:00
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
file, err := os.Create(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
2023-09-23 01:31:04 +08:00
if file != nil {
_ = file.Close()
}
2023-09-12 18:40:24 +08:00
}(file)
2023-09-13 00:46:17 +08:00
fileLock.Lock()
defer fileLock.Unlock()
2023-09-12 18:40:24 +08:00
_, err = file.Write(data)
if err != nil {
return nil, fmt.Errorf("failed to write to sub.yaml: %w", err)
}
return data, nil
}