]>
code.octet-stream.net Git - broadcaster/blob - radio/files_machine.go
12 "code.octet-stream.net/broadcaster/internal/protocol"
15 type FilesMachine
struct {
16 specs
[]protocol
.FileSpec
21 func NewFilesMachine(cachePath
string) FilesMachine
{
22 if err
:= os
.MkdirAll(cachePath
, 0750); err
!= nil {
30 func (m
*FilesMachine
) UpdateSpecs(specs
[]protocol
.FileSpec
) {
35 func (m
*FilesMachine
) RefreshMissing() {
36 // Delete any files in the cache dir who are not in the spec
37 entries
, err
:= os
.ReadDir(m
.cachePath
)
41 okay
:= make([]string, 0)
42 for _
, file
:= range entries
{
44 for _
, spec
:= range m
.specs
{
45 if file
.Name() == spec
.Name
{
50 // if we have an extraneous file, delete it
52 log
.Println("Deleting extraneous cached audio file:", file
.Name())
53 os
.Remove(filepath
.Join(m
.cachePath
, file
.Name()))
56 // if the hash isn't right, delete it
57 f
, err
:= os
.Open(filepath
.Join(m
.cachePath
, file
.Name()))
61 hasher
:= sha256
.New()
63 if hex
.EncodeToString(hasher
.Sum(nil)) != hash
{
64 log
.Println("Deleting cached audio file with incorrect hash:", file
.Name())
65 os
.Remove(filepath
.Join(m
.cachePath
, file
.Name()))
67 okay
= append(okay
, file
.Name())
71 for _
, spec
:= range m
.specs
{
73 for _
, file
:= range okay
{
74 if spec
.Name
== file
{
79 m
.missing
= append(m
.missing
, spec
.Name
)
82 if len(m
.missing
) > 1 {
83 log
.Println(len(m
.missing
), "missing files")
84 } else if len(m
.missing
) == 1 {
85 log
.Println("1 missing file")
87 log
.Println("All files are in sync with server")
89 statusCollector
.FilesInSync
<- len(m
.missing
) == 0
92 func (m
*FilesMachine
) IsCacheComplete() bool {
93 return len(m
.missing
) == 0
96 func (m
*FilesMachine
) NextFile() string {
97 next
, remainder
:= m
.missing
[0], m
.missing
[1:]
102 func (m
*FilesMachine
) DownloadSingle(filename
string, downloadResult
chan<- error
) {
103 log
.Println("Downloading", filename
)
104 out
, err
:= os
.Create(filepath
.Join(m
.cachePath
, filename
))
106 downloadResult
<- err
110 resp
, err
:= http
.Get(config
.ServerURL
+ "/file-downloads/" + filename
)
112 downloadResult
<- err
115 defer resp
.Body
.Close()
116 _
, err
= io
.Copy(out
, resp
.Body
)
117 downloadResult
<- err