mt-multiserver-proxy/mediacache.go

53 lines
1.1 KiB
Go
Raw Permalink Normal View History

2021-09-13 10:44:44 -07:00
package proxy
import (
"crypto/sha1"
2022-04-21 12:06:55 -07:00
"encoding/base64"
2021-09-13 10:44:44 -07:00
"os"
2022-04-21 12:06:55 -07:00
"strings"
2021-09-13 10:44:44 -07:00
)
func (cc *contentConn) fromCache(filename, base64SHA1 string) bool {
os.Mkdir(Path("cache"), 0777)
// convert to filename safe b64
2022-04-21 12:06:55 -07:00
base64SHA1Filesafe := strings.Replace(base64SHA1, "/", "_", -1)
base64SHA1Filesafe = strings.Replace(base64SHA1Filesafe, "+", "-", -1)
2021-09-13 10:44:44 -07:00
2022-04-21 12:06:55 -07:00
data, err := os.ReadFile(Path("cache/", base64SHA1Filesafe))
if err != nil {
2022-04-21 12:06:55 -07:00
if !os.IsNotExist(err) {
cc.log("->", "cache", err)
}
2022-04-21 12:12:32 -07:00
2021-09-13 10:44:44 -07:00
return false
}
cc.media = append(cc.media, mediaFile{
name: filename,
base64SHA1: base64SHA1,
2021-09-13 10:44:44 -07:00
data: data,
})
return true
}
func (cc *contentConn) updateCache() {
os.Mkdir(Path("cache"), 0777)
for _, f := range cc.media {
// convert to filename safe b64
2022-04-21 12:06:55 -07:00
base64SHA1Filesafe := strings.Replace(f.base64SHA1, "/", "_", -1)
base64SHA1Filesafe = strings.Replace(base64SHA1Filesafe, "+", "-", -1)
2022-04-21 12:06:55 -07:00
os.WriteFile(Path("cache/", base64SHA1Filesafe), f.data, 0666)
2021-09-13 10:44:44 -07:00
}
}
func cacheMedia(f mediaFile) {
hash := sha1.Sum(f.data)
2022-04-21 12:06:55 -07:00
sum := base64.RawStdEncoding.EncodeToString(hash[:])
os.WriteFile(Path("cache/", sum), f.data, 0666)
2021-09-13 10:44:44 -07:00
}