]> code.octet-stream.net Git - broadcaster/blob - server/files.go
Initial commit, basic functionality working
[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 )
11
12 type FileSpec struct {
13 Name string
14 Hash string
15 }
16
17 type AudioFiles struct {
18 path string
19 list []FileSpec
20 changeWait chan bool
21 }
22
23 var files AudioFiles
24
25 func InitAudioFiles(path string) {
26 files.changeWait = make(chan bool)
27 files.path = path
28 log.Println("initing audio files")
29 files.Refresh()
30 log.Println("done")
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.list = nil
40 for _, file := range entries {
41 f, err := os.Open(filepath.Join(r.path, file.Name()))
42 if err != nil {
43 log.Println("couldn't open", file.Name())
44 return
45 }
46 hash := sha256.New()
47 io.Copy(hash, f)
48 r.list = append(r.list, FileSpec{Name: file.Name(), Hash: hex.EncodeToString(hash.Sum(nil))})
49 }
50 log.Println("Files updated", r.list)
51 close(files.changeWait)
52 files.changeWait = make(chan bool)
53 }
54
55 func (r *AudioFiles) Path() string {
56 return r.path
57 }
58
59 func (r *AudioFiles) Files() []FileSpec {
60 return r.list
61 }
62
63 func (r *AudioFiles) Delete(filename string) {
64 path := filepath.Join(r.path, filepath.Base(filename))
65 if filepath.Clean(r.path) != filepath.Clean(path) {
66 os.Remove(path)
67 r.Refresh()
68 }
69 }
70
71 func (r *AudioFiles) ChangeChannel() chan bool {
72 return r.changeWait
73 }