m3u8d/cache.go

82 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-05-15 03:05:31 +00:00
package m3u8d
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/orestonce/cdb"
"io/ioutil"
"os"
"path/filepath"
2022-06-19 23:32:53 +00:00
"strconv"
2022-05-15 03:05:31 +00:00
)
type DbVideoInfo struct {
VideoId string
ContentHash string
FileSize int64 // 加快搜索速度
OriginReq RunDownload_Req
}
func (this *RunDownload_Req) getVideoId() (id string, err error) {
2022-06-19 23:32:53 +00:00
b, err := json.Marshal([]string{this.M3u8Url, strconv.Itoa(this.SkipTsCountFromHead)})
2022-05-15 03:05:31 +00:00
if err != nil {
return "", err
}
tmp1 := sha256.Sum256(b)
return hex.EncodeToString(tmp1[:]), nil
}
func cacheRead(dir string, id string) (info *DbVideoInfo, err error) {
2022-05-28 02:11:38 +00:00
value, err := cdb.FileGetValueString(filepath.Join(dir, "m3u8d_cache.cdb"), id)
2022-05-15 03:05:31 +00:00
if err != nil {
2022-05-28 02:11:38 +00:00
if err == cdb.ErrNoData {
return nil, nil
}
2022-05-15 03:05:31 +00:00
return nil, err
}
var obj DbVideoInfo
2022-05-28 02:11:38 +00:00
err = json.Unmarshal([]byte(value), &obj)
2022-05-15 03:05:31 +00:00
if err != nil {
return nil, err
}
info = &obj
return info, nil
}
func (this *DbVideoInfo) SearchVideoInDir(dir string) (latestNameFullPath string, found bool) {
fileList, err := ioutil.ReadDir(dir)
if err != nil {
return "", false
}
for _, one := range fileList {
if this.FileSize != one.Size() || !one.Mode().IsRegular() {
continue
}
tmp := filepath.Join(dir, one.Name())
if this.ContentHash == getFileSha256(tmp) {
return tmp, true
}
}
return "", false
}
func cacheWrite(dir string, id string, originReq RunDownload_Req, videoNameFullPath string, contentHash string) (err error) {
var info = &DbVideoInfo{
VideoId: id,
OriginReq: originReq,
ContentHash: contentHash,
FileSize: 0,
}
stat, err := os.Stat(videoNameFullPath)
if err != nil {
return err
}
info.FileSize = stat.Size()
content, err := json.MarshalIndent(info, "", " ")
if err != nil {
return err
}
2022-05-28 02:11:38 +00:00
return cdb.FileRewriteKeyValue(filepath.Join(dir, "m3u8d_cache.cdb"), id, string(content))
2022-05-15 03:05:31 +00:00
}