]>
code.octet-stream.net Git - broadcaster/blob - radio/files_machine.go
ea2f77530e7346df5ba6894237664582f320d1c3
4 "code.octet-stream.net/broadcaster/protocol"
14 type FilesMachine
struct {
15 specs
[]protocol
.FileSpec
20 func NewFilesMachine(cachePath
string) FilesMachine
{
21 if err
:= os
.MkdirAll(cachePath
, 0750); err
!= nil {
29 func (m
*FilesMachine
) UpdateSpecs(specs
[]protocol
.FileSpec
) {
34 func (m
*FilesMachine
) RefreshMissing() {
35 // Delete any files in the cache dir who are not in the spec
36 entries
, err
:= os
.ReadDir(m
.cachePath
)
40 okay
:= make([]string, 0)
41 for _
, file
:= range entries
{
43 for _
, spec
:= range m
.specs
{
44 if file
.Name() == spec
.Name
{
49 // if we have an extraneous file, delete it
51 log
.Println("Deleting extraneous cached audio file:", file
.Name())
52 os
.Remove(filepath
.Join(m
.cachePath
, file
.Name()))
55 // if the hash isn't right, delete it
56 f
, err
:= os
.Open(filepath
.Join(m
.cachePath
, file
.Name()))
60 hasher
:= sha256
.New()
62 if hex
.EncodeToString(hasher
.Sum(nil)) != hash
{
63 log
.Println("Deleting cached audio file with incorrect hash:", file
.Name())
64 os
.Remove(filepath
.Join(m
.cachePath
, file
.Name()))
66 okay
= append(okay
, file
.Name())
70 for _
, spec
:= range m
.specs
{
72 for _
, file
:= range okay
{
73 if spec
.Name
== file
{
78 m
.missing
= append(m
.missing
, spec
.Name
)
81 if len(m
.missing
) > 1 {
82 log
.Println(len(m
.missing
), "missing files")
83 } else if len(m
.missing
) == 1 {
84 log
.Println("1 missing file")
86 log
.Println("All files are in sync with server")
88 statusCollector
.FilesInSync
<- len(m
.missing
) == 0
91 func (m
*FilesMachine
) IsCacheComplete() bool {
92 return len(m
.missing
) == 0
95 func (m
*FilesMachine
) NextFile() string {
96 next
, remainder
:= m
.missing
[0], m
.missing
[1:]
101 func (m
*FilesMachine
) DownloadSingle(filename
string, downloadResult
chan<- error
) {
102 log
.Println("Downloading", filename
)
103 out
, err
:= os
.Create(filepath
.Join(m
.cachePath
, filename
))
105 downloadResult
<- err
109 resp
, err
:= http
.Get(config
.ServerURL
+ "/audio-files/" + filename
)
111 downloadResult
<- err
114 defer resp
.Body
.Close()
115 _
, err
= io
.Copy(out
, resp
.Body
)
116 downloadResult
<- err