]> code.octet-stream.net Git - broadcaster/blob - server/files.go
Clean up log entries
[broadcaster] / server / files.go
1 package main
2
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "io"
7 "log"
8 "os"
9 "path/filepath"
10 "sync"
11 )
12
13 type FileSpec struct {
14 Name string
15 Hash string
16 }
17
18 type AudioFiles struct {
19 path string
20 list []FileSpec
21 changeWait chan bool
22 filesMutex sync.Mutex
23 }
24
25 var files AudioFiles
26
27 func InitAudioFiles(path string) {
28 files.changeWait = make(chan bool)
29 files.path = path
30 files.Refresh()
31 }
32
33 func (r *AudioFiles) Refresh() {
34 entries, err := os.ReadDir(r.path)
35 if err != nil {
36 log.Println("Couldn't read dir", r.path)
37 return
38 }
39 r.filesMutex.Lock()
40 defer r.filesMutex.Unlock()
41 r.list = nil
42 for _, file := range entries {
43 f, err := os.Open(filepath.Join(r.path, file.Name()))
44 if err != nil {
45 log.Println("Couldn't open", file.Name())
46 return
47 }
48 hash := sha256.New()
49 io.Copy(hash, f)
50 r.list = append(r.list, FileSpec{Name: file.Name(), Hash: hex.EncodeToString(hash.Sum(nil))})
51 }
52 log.Println("Files updated", r.list)
53 close(files.changeWait)
54 files.changeWait = make(chan bool)
55 }
56
57 func (r *AudioFiles) Path() string {
58 return r.path
59 }
60
61 func (r *AudioFiles) Files() []FileSpec {
62 r.filesMutex.Lock()
63 defer r.filesMutex.Unlock()
64 return r.list
65 }
66
67 func (r *AudioFiles) Delete(filename string) {
68 path := filepath.Join(r.path, filepath.Base(filename))
69 if filepath.Clean(r.path) != filepath.Clean(path) {
70 os.Remove(path)
71 r.Refresh()
72 }
73 }
74
75 func (r *AudioFiles) WatchForChanges() ([]FileSpec, chan bool) {
76 r.filesMutex.Lock()
77 defer r.filesMutex.Unlock()
78 return r.list, r.changeWait
79 }