-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayback.go
316 lines (270 loc) · 7.12 KB
/
playback.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Playback and queue management. Playback is delegated to mpv, which is
// allowed to run in a blocking manner for full keyboard control. As such,
// multiple instances of the program are to be expected, but only one instance
// can be running mpv; other instances can only add to queue, and terminate
// immediately.
//
// Scrobbling is out of scope of this program; consider
// https://github.com/Feqzz/mpv-lastfm-scrobbler
package main
import (
"bufio"
"fmt"
"io"
"io/fs"
"log"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"plaque/discogs"
)
const QueueCount = 5
func mpvRunning() bool {
// https://github.com/mitchellh/go-ps/blob/master/process_linux.go
running := false
_ = filepath.WalkDir("/proc", func(path string, d fs.DirEntry, err error) error {
if d.IsDir() || filepath.Base(path) != "stat" {
return nil
}
b, e := os.ReadFile(path)
if e != nil {
panic(e)
}
s := string(b)
start := strings.IndexRune(s, '(')
end := strings.IndexRune(s, ')')
if end < 0 {
return nil
}
if s[start+1:end] == "mpv" {
running = true
return fs.SkipAll
}
return nil
})
return running
}
func getResumes() *[]string {
// When mpv is quit with the `quit_watch_later` command, a file is
// written to this dir, containing the full path to the file.
if config == nil {
panic("init was not done")
}
var resumes []string
err := filepath.WalkDir(
config.Mpv.WatchLaterDir,
func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
fo, _ := os.Open(path)
defer fo.Close()
sc := bufio.NewScanner(fo)
sc.Scan() // only need to read 1st line
line := sc.Text()
file := line[2:] // # "# "
if fi, e := os.Stat(file); e == nil &&
!fi.IsDir() &&
strings.HasPrefix(file, config.Library.Root) {
rel, _ := filepath.Rel(config.Library.Root, filepath.Dir(file))
resumes = append(resumes, rel)
}
return nil
},
)
if err != nil {
panic(err)
}
if len(resumes) == 0 {
return nil
}
return &resumes
}
func willResume(relpath string) (resume bool) {
path := filepath.Join(config.Library.Root, relpath)
_ = filepath.WalkDir(config.Mpv.WatchLaterDir, func(p string, d fs.DirEntry, _ error) error {
if d.IsDir() {
return nil
}
b, err := os.ReadFile(p)
if err != nil {
panic(err)
}
if strings.Contains(string(b), path) {
resume = true
return fs.SkipAll
}
return nil
})
return resume
}
// Select n random items from the queue file (containing relpaths), and return
// them as fullpaths
//
// If n = 0, the entire queue is returned without shuffling
func getQueue(n int) []string {
if n < 0 {
panic("invalid")
}
// my queue file is about 8000, so it is worth doing some optimisation
// https://scribe.rip/golicious/comparing-ioutil-readfile-and-bufio-scanner-ddd8d6f18463
// according to a simple benchmark, os.ReadFile() is almost 2-3x as
// fast as bufio.NewScanner(). NewScanner can probably only be faster
// if we know how to stop scanning early (which we don't)
b, err := os.ReadFile(config.Library.Queue)
if err != nil {
panic(err)
}
relpaths := strings.Split(string(b), "\n")
// TODO: split off sampling
switch n {
case 0:
return relpaths
default:
var sel []string
idxs := rand.Perm(len(relpaths) - 1)
for _, idx := range idxs[:n] {
sel = append(sel, relpaths[idx])
}
return sel
}
}
func writeQueue(items []string) {
err := os.WriteFile(
config.Library.Queue,
[]byte(strings.Join(items, "\n")),
0666,
)
if err != nil {
panic(err)
}
}
// https://github.com/picosh/pico/blob/4632c9cd3d7bc37c9c0c92bdc3dc8a64928237d8/tui/senpai.go#L10
// wrapper to call functions in a blocking manner (via Run)
type postPlaybackCmd struct{ relpath string }
// required methods for tea.ExecCommand
func (c *postPlaybackCmd) Run() error {
if willResume(c.relpath) {
// we -could- propagate some error to tea.Exec, which can be
// handled there. for practical purposes, all we need to do is
// just return to Queue
log.Println("will resume:", c.relpath)
os.Exit(0)
return nil
// // TODO: figure out how to return a 'real' error
// return fmt.Errorf("resume")
}
log.Println("playback done")
q := getQueue(0)
nq := *remove(&q, c.relpath)
ensure(len(q)-len(nq) == 1)
writeQueue(nq)
log.Println("removed:", c.relpath)
if !discogsEnabled {
log.Println("no discogs key, skipping rate")
return nil
}
artist, album := filepath.Split(c.relpath)
// remove possible translation
if artist[len(artist)-1] == ')' {
i := strings.LastIndex(artist, "(")
artist = artist[:i-1]
}
// remove album suffix " (YYYY)"
if album[len(album)-1] == ')' {
album = album[:len(album)-7]
}
// aside from edge cases, only classical albums have " [performer, ...]" suffix
var res discogs.SearchResult
if album[len(album)-1] == ']' {
res = discogs.Search(movePerfsToArtist(artist, album))
} else {
res = discogs.Search(artist, album)
}
rel := res.Primary()
if rating, _ := rel.Rate(); rating == 1 &&
// guard rail to prevent deleting classical artists
album[len(album)-1] != ']' {
p := filepath.Join(config.Library.Root, artist)
if _, err := os.Stat(p); err != nil {
return nil
}
fmt.Printf("Delete %s? [y/N] ", artist)
var del string
_, _ = fmt.Scanln(&del)
if del == "y" {
_ = os.RemoveAll(p)
fmt.Println("Deleted", p)
}
return nil
}
// this is not terribly ergonomic; but wrapping the returned []Artist
// in a struct seems even more annoying
artists := discogs.SearchArtist(artist)
if len(artists) == 0 {
return nil
}
art := discogs.BrowseArtists(artists)
if art != nil {
return nil
}
// art.Rate(checkDir) // nonsensical api
// art.Rate() // sane api, but no checkDir
for _, rel := range art.Releases() {
// if !rel.IsRateable() || checkDir(artist, rel.Title) {
// continue
// }
if checkDir(artist, rel.Title) {
continue
}
// if errors.Is(err, discogs.ErrAlreadyRated) {
// continue
// }
_, err := rel.Rate()
switch err {
case discogs.ErrAlreadyRated, discogs.ErrNotRateable:
continue
}
break
}
return nil
}
func (c *postPlaybackCmd) SetStderr(io.Writer) {}
func (c *postPlaybackCmd) SetStdin(io.Reader) {}
func (c *postPlaybackCmd) SetStdout(io.Writer) {}
func play(relpath string) tea.Cmd {
timer := time.NewTimer(time.Second * 2)
defer timer.Stop()
go func() {
// fmt.Println("please wait...", <-timer.C)
// fmt won't work outside View
log.Println("please wait...", <-timer.C)
}()
// TODO: online mode (search ytm)
path := filepath.Join(config.Library.Root, relpath)
mpvCmd := exec.Command("mpv", append(strings.Fields(config.Mpv.Args), path)...)
log.Println("playing:", path)
return tea.Sequence(
tea.ExecProcess(mpvCmd, nil),
tea.Exec(
&postPlaybackCmd{relpath: relpath},
nil,
// // if you need to check/handle the error returned by
// // Run and turn that into a Cmd, you could; otherwise,
// // we just return to Queue
// func(err error) tea.Msg {
// // if err.Error() == "resume" {
// // log.Println("quitting and will resume")
// // return tea.Quit()
// // // return nil
// // }
// return nil
// },
),
tea.ClearScreen,
)
}