-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
314 lines (284 loc) · 8.14 KB
/
main.go
File metadata and controls
314 lines (284 loc) · 8.14 KB
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
// Command lofi-player is a TUI player for lofi/chillhop/ambient internet
// radio streams. See the project plan in plans/lofi-player-plan.md.
package main
import (
"context"
"flag"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/iRootPro/lofi-player/internal/audio"
"github.com/iRootPro/lofi-player/internal/config"
sharepkg "github.com/iRootPro/lofi-player/internal/share"
"github.com/iRootPro/lofi-player/internal/state"
"github.com/iRootPro/lofi-player/internal/tui"
)
const mpvStartupTimeout = 5 * time.Second
// version is overridden at build time via -ldflags "-X main.version=...".
// Goreleaser injects the tag; `go install` and ad-hoc builds keep "dev".
var version = "dev"
func main() {
var (
statusline bool
showVersion bool
exportAll bool
exportStation string
importPath string
)
flag.BoolVar(&statusline, "statusline", false, "print one status-line snapshot to stdout and exit (no TUI)")
flag.BoolVar(&showVersion, "version", false, "print version and exit")
flag.BoolVar(&showVersion, "v", false, "print version and exit (shorthand)")
flag.BoolVar(&exportAll, "export-all", false, "print all stations as a shareable YAML snippet and exit")
flag.StringVar(&exportStation, "export-station", "", "print one station by name as a shareable YAML snippet and exit")
flag.StringVar(&importPath, "import", "", "import stations from a YAML snippet file, or '-' for stdin, and exit")
flag.Parse()
if showVersion {
fmt.Println("lofi-player", version)
return
}
if statusline {
if err := runStatusline(); err != nil {
fmt.Fprintf(os.Stderr, "lofi-player: %v\n", err)
os.Exit(1)
}
return
}
if exportAll || exportStation != "" {
if err := runExport(exportAll, exportStation); err != nil {
fmt.Fprintf(os.Stderr, "lofi-player: %v\n", err)
os.Exit(1)
}
return
}
if importPath != "" {
if err := runImport(importPath); err != nil {
fmt.Fprintf(os.Stderr, "lofi-player: %v\n", err)
os.Exit(1)
}
return
}
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "lofi-player: %v\n", err)
os.Exit(1)
}
}
func run() error {
cfg, err := config.Load()
if err != nil {
return err
}
if _, err := exec.LookPath("mpv"); err != nil {
fmt.Fprint(os.Stderr, "\n", tui.RenderMissingDependency(
"mpv", "audio engine, required for all playback",
[]tui.InstallCmd{
{Platform: "macOS", Cmd: "brew install mpv"},
{Platform: "Linux", Cmd: "apt install mpv · pacman -S mpv · dnf install mpv"},
}), "\n")
os.Exit(1)
}
youtubeWarning := preflightYouTube(cfg.Stations)
st := state.Load()
opts := tui.Options{
Theme: st.Theme,
Volume: st.Volume,
AutoplayStation: stationIndex(cfg.Stations, st.LastStationName),
ShowStreamInfo: st.ShowStreamInfo,
StartupWarning: youtubeWarning,
YouTubeReady: youtubeWarning == "",
}
effectiveVolume := cfg.Volume
if opts.Volume > 0 {
effectiveVolume = opts.Volume
}
ctx, cancel := context.WithTimeout(context.Background(), mpvStartupTimeout)
defer cancel()
player, err := audio.NewPlayer(ctx, audio.Options{
InitialVolume: effectiveVolume,
BufferSeconds: cfg.BufferSeconds,
InitialBufferSeconds: cfg.InitialBufferSeconds,
})
if err != nil {
return fmt.Errorf("starting mpv: %w", err)
}
defer player.Close()
mixer := audio.NewAmbientMixer()
if err := mixer.Init(); err != nil {
// Init failure is non-fatal: the main station keeps working,
// the mixer modal just renders its rows as 'unavailable'.
fmt.Fprintf(os.Stderr, "lofi-player: ambient mixer init failed: %v\n", err)
} else {
for id, v := range st.Ambient {
_ = mixer.SetVolume(id, v)
}
}
defer mixer.Close()
opts.SaveAmbient = func(snap map[string]int) error {
current := state.Load()
current.Ambient = snap
return state.Save(current)
}
p := tea.NewProgram(tui.NewModel(cfg, player, mixer, opts), tea.WithAltScreen())
finalModel, err := p.Run()
if err != nil {
return err
}
if m, ok := finalModel.(tui.Model); ok {
// Persistence is best-effort — write failure logs to stderr (now
// that the alt-screen is restored) and never aborts shutdown.
showInfo := m.ShowStreamInfo()
next := &state.State{
Theme: m.ThemeName(),
Volume: m.Volume(),
LastStationName: m.LastStationName(),
Ambient: mixer.Volumes(),
ShowStreamInfo: &showInfo,
}
if err := state.Save(next); err != nil {
fmt.Fprintf(os.Stderr, "lofi-player: state save failed: %v\n", err)
}
}
return nil
}
func runExport(all bool, stationName string) error {
cfg, err := config.Load()
if err != nil {
return err
}
var snippet string
if all {
snippet, err = sharepkg.MarshalStations(cfg.Stations)
} else {
st, ok := findStationByName(cfg.Stations, stationName)
if !ok {
return fmt.Errorf("station %q not found", stationName)
}
snippet, err = sharepkg.MarshalStation(st)
}
if err != nil {
return err
}
fmt.Print(snippet)
return nil
}
func runImport(path string) error {
var data []byte
var err error
if path == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(path)
}
if err != nil {
return err
}
stations, err := sharepkg.Parse(string(data))
if err != nil {
return err
}
cfg, err := config.Load()
if err != nil {
return err
}
newStations, skipped := newStationsOnly(cfg.Stations, stations)
if len(newStations) == 0 {
fmt.Fprintf(os.Stderr, "lofi-player: all %d station(s) already exist\n", skipped)
return nil
}
cfg.Stations = append(cfg.Stations, newStations...)
if err := config.Save(cfg); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "lofi-player: imported %d station(s), skipped %d duplicate(s)\n", len(newStations), skipped)
return nil
}
func findStationByName(stations []config.Station, name string) (config.Station, bool) {
for _, st := range stations {
if st.Name == name {
return st, true
}
}
for _, st := range stations {
if strings.EqualFold(st.Name, name) {
return st, true
}
}
return config.Station{}, false
}
func newStationsOnly(existing, incoming []config.Station) ([]config.Station, int) {
seen := make(map[string]struct{}, len(existing)+len(incoming))
for _, st := range existing {
seen[st.URL] = struct{}{}
}
out := make([]config.Station, 0, len(incoming))
skipped := 0
for _, st := range incoming {
if _, ok := seen[st.URL]; ok {
skipped++
continue
}
seen[st.URL] = struct{}{}
out = append(out, st)
}
return out, skipped
}
// runStatusline produces a single colored line and exits. Designed for
// tmux's status-right and similar integrations: configure tmux to run
// `lofi-player --statusline` periodically and embed the output.
func runStatusline() error {
cfg, err := config.Load()
if err != nil {
return err
}
st := state.Load()
themeName := cfg.Theme
if st.Theme != "" {
themeName = st.Theme
}
volume := cfg.Volume
if st.Volume > 0 {
volume = st.Volume
}
fmt.Println(tui.StatusLine(themeName, st.LastStationName, fmt.Sprintf("%d%%", volume), volume))
return nil
}
// preflightYouTube checks whether yt-dlp is on $PATH when the config
// contains YouTube stations. Returns the empty string when YouTube is
// either unused or fully wired; otherwise returns a one-line warning
// suitable for an in-app startup toast. The TUI then renders YouTube
// stations as unavailable and refuses to play them, but the rest of
// the app keeps working — losing one source kind shouldn't sink the
// whole player.
func preflightYouTube(stations []config.Station) string {
hasYouTube := false
for _, s := range stations {
if s.IsYouTube() {
hasYouTube = true
break
}
}
if !hasYouTube {
return ""
}
if _, err := exec.LookPath("yt-dlp"); err != nil {
return "yt-dlp not found — YouTube stations unavailable. install: brew install yt-dlp / pip install yt-dlp"
}
return ""
}
// stationIndex returns the index in stations matching name, or -1 if
// not found. Used to map the persisted LastStationName back to a cursor
// position so renaming a station doesn't break autoplay.
func stationIndex(stations []config.Station, name string) int {
if name == "" {
return -1
}
for i, s := range stations {
if s.Name == name {
return i
}
}
return -1
}