-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
110 lines (103 loc) · 2.39 KB
/
files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"context"
"log"
"os"
"path/filepath"
"regexp"
"time"
"gopkg.in/yaml.v3"
)
type State struct {
LastData time.Time
}
func readState(file string) State {
def := func() State {
return State{
LastData: time.UnixMilli(0),
}
}
f, err := os.ReadFile(file)
if err != nil {
return def()
}
var state State
err = yaml.Unmarshal(f, &state)
if err != nil {
return def()
}
return state
}
func writeState(state State, file string) {
f, err := os.Create(file)
if err != nil {
log.Printf("failed to open state file for writing: %s\n", file)
return
}
bytes, err := yaml.Marshal(state)
if err != nil {
log.Println("failed to marshal data")
return
}
_, err = f.Write(bytes)
if err != nil {
log.Printf("failed to write state to: %s\n", file)
}
}
func findFiles(dir string, lastUpdated time.Time) ([]string, error) {
// get dirs
dateDirs, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
filteredFiles := make([]string, 0, 100)
// BRP: flow/pressure
// PLD: mask/press/leak/rep/tid/snbore/flowlim/etc
// EVE: annotations
regex := regexp.MustCompile(`^[^.].+(BRP|PLD|EVE).edf$`)
for _, dateDir := range dateDirs {
date, err := time.ParseInLocation("20060102", dateDir.Name(), time.Local)
if err != nil || date.Before(lastUpdated.Add(-time.Hour*48)) || !dateDir.IsDir() {
continue
}
files, err := os.ReadDir(filepath.Join(dir, dateDir.Name()))
for _, file := range files {
fileInfo, err := file.Info()
if err != nil {
panic(err)
}
if regex.MatchString(file.Name()) && fileInfo.Size() > 0 {
filteredFiles = append(filteredFiles, filepath.Join(dir, dateDir.Name(), file.Name()))
}
}
}
return filteredFiles, nil
}
// RunWhenMediaInserted calls f when file becomes available. If file becomes unavailable and then available again,
// f will be called each time.
func RunWhenMediaInserted(file string, ctx context.Context, f func()) {
fsFound := false
log.Printf("Watching media path: %s\n", file)
for {
fileInfo, err := os.Stat(file)
if fsFound {
if err != nil {
fsFound = false
log.Printf("Media removed: %s\n", file)
}
} else {
if err == nil && fileInfo.IsDir() {
fsFound = true
log.Printf("Media inserted: %s\n", file)
f()
}
}
select {
case <-ctx.Done():
log.Printf("Stopping watching path: %s\n", file)
return
case <-time.After(time.Second * 5):
// continue to watch
}
}
}