-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathmain.go
More file actions
441 lines (393 loc) · 13.2 KB
/
main.go
File metadata and controls
441 lines (393 loc) · 13.2 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
tea "charm.land/bubbletea/v2"
"cliamp/applog"
"cliamp/config"
"cliamp/external/emby"
"cliamp/external/jellyfin"
"cliamp/external/local"
"cliamp/external/navidrome"
"cliamp/external/plex"
"cliamp/external/radio"
"cliamp/external/soundcloud"
"cliamp/external/spotify"
"cliamp/external/ytmusic"
"cliamp/internal/appdir"
"cliamp/internal/appmeta"
"cliamp/internal/playback"
"cliamp/internal/resume"
"cliamp/ipc"
"cliamp/luaplugin"
"cliamp/mediactl"
"cliamp/player"
"cliamp/playlist"
"cliamp/resolve"
"cliamp/theme"
"cliamp/ui"
"cliamp/ui/model"
)
// version is set at build time via -ldflags "-X main.version=vX.Y.Z".
var version string
func run(overrides config.Overrides, positional []string, daemon bool) error {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("config: %w", err)
}
overrides.Apply(&cfg)
closeLog, appliedLevel, logErr := initLogging(cfg.LogLevel)
defer closeLog()
if logErr != nil {
fmt.Fprintf(os.Stderr, "logging: %v (continuing without file log)\n", logErr)
applog.Status("logging: %v", logErr)
} else {
applog.Info("cliamp starting (version=%s level=%s)", appmeta.Version(), appliedLevel)
}
// Build provider list: Radio is always available, Navidrome and Spotify if configured.
radioProv := radio.New()
localProv := local.New()
var providers []model.ProviderEntry
providers = append(providers, model.ProviderEntry{Key: "radio", Name: "Radio", Provider: radioProv})
if localProv != nil {
providers = append(providers, model.ProviderEntry{Key: "local", Name: "Local", Provider: localProv})
}
var navClient *navidrome.NavidromeClient
if c := navidrome.NewFromConfig(cfg.Navidrome); c != nil {
navClient = c
} else if c := navidrome.NewFromEnv(); c != nil {
navClient = c
}
if navClient != nil {
providers = append(providers, model.ProviderEntry{Key: "navidrome", Name: "Navidrome", Provider: navClient})
}
if plexProv := plex.NewFromConfig(cfg.Plex); plexProv != nil {
providers = append(providers, model.ProviderEntry{Key: "plex", Name: "Plex", Provider: plexProv})
}
if jellyProv := jellyfin.NewFromConfig(cfg.Jellyfin); jellyProv != nil {
providers = append(providers, model.ProviderEntry{Key: "jellyfin", Name: "Jellyfin", Provider: jellyProv})
}
if embyProv := emby.NewFromConfig(cfg.Emby); embyProv != nil {
providers = append(providers, model.ProviderEntry{Key: "emby", Name: "Emby", Provider: embyProv})
}
var spotifyProv *spotify.SpotifyProvider
if cfg.Spotify.IsSet() {
spotifyProv = spotify.New(nil, cfg.Spotify.ClientID, cfg.Spotify.Bitrate)
providers = append(providers, model.ProviderEntry{Key: "spotify", Name: "Spotify", Provider: spotifyProv})
}
if scProv := soundcloud.NewFromConfig(soundcloud.Config{
Enabled: cfg.SoundCloud.Enabled,
User: cfg.SoundCloud.User,
CookiesFrom: cfg.SoundCloud.CookiesFrom,
}); scProv != nil {
// Mirror the cookies_from setting onto the player so streaming yt-dlp
// invocations use the same browser session as resolve. Last write wins
// if [ytmusic] cookies_from also set this earlier in run().
if cfg.SoundCloud.CookiesFrom != "" {
player.SetYTDLCookiesFrom(cfg.SoundCloud.CookiesFrom)
}
providers = append(providers, model.ProviderEntry{Key: "soundcloud", Name: "SoundCloud", Provider: scProv})
}
var ytProviders ytmusic.Providers
ytWanted := cfg.YouTubeMusic.IsSetOrFallback(ytmusic.FallbackCredentials)
if !ytWanted {
switch cfg.Provider {
case "yt", "youtube", "ytmusic":
ytWanted = true
}
}
if ytWanted {
ytClientID, ytClientSecret := cfg.YouTubeMusic.ResolveCredentials(ytmusic.FallbackCredentials)
if cfg.YouTubeMusic.CookiesFrom != "" {
player.SetYTDLCookiesFrom(cfg.YouTubeMusic.CookiesFrom)
}
if ytClientID == "" || ytClientSecret == "" {
fmt.Fprintf(os.Stderr, "YouTube: no credentials available (configure client_id/client_secret in config.toml)\n")
} else {
if !player.YTDLPAvailable() {
fmt.Fprintf(os.Stderr, "\nYouTube requires yt-dlp for audio playback.\n")
fmt.Fprintf(os.Stderr, "Install command: %s\n\n", player.YtdlpInstallHint())
fmt.Fprintf(os.Stderr, "Press Enter to install automatically, or Ctrl+C to skip... ")
fmt.Scanln()
fmt.Fprintf(os.Stderr, "Installing yt-dlp...\n")
if err := player.InstallYTDLP(); err != nil {
fmt.Fprintf(os.Stderr, "Installation failed: %v\n", err)
fmt.Fprintf(os.Stderr, "YouTube providers disabled. Install manually and restart.\n\n")
} else {
fmt.Fprintf(os.Stderr, "yt-dlp installed successfully!\n\n")
}
}
if player.YTDLPAvailable() {
ytProviders = ytmusic.New(nil, ytClientID, ytClientSecret, cfg.YouTubeMusic.CookiesFrom != "")
providers = append(providers,
model.ProviderEntry{Key: "yt", Name: "YouTube (All)", Provider: ytProviders.All},
model.ProviderEntry{Key: "youtube", Name: "YouTube", Provider: ytProviders.Video},
model.ProviderEntry{Key: "ytmusic", Name: "YouTube Music", Provider: ytProviders.Music},
)
}
}
}
if spotifyProv != nil {
defer spotifyProv.Close()
}
if ytProviders.Music != nil {
defer ytProviders.Music.Close()
}
if len(positional) > 0 && (positional[0] == "search" || positional[0] == "search-sc") {
if len(positional) == 1 {
return fmt.Errorf("search requires a query string (e.g. cliamp search \"never gonna give you up\")")
}
prefix := "ytsearch1:"
if positional[0] == "search-sc" {
prefix = "scsearch1:"
}
query := strings.Join(positional[1:], " ")
positional = []string{prefix + query}
}
resolved, err := resolve.Args(positional)
if err != nil {
return err
}
defaultProvider := cfg.Provider
if defaultProvider == "" {
defaultProvider = "radio"
}
defaultRadio := len(positional) == 0 && defaultProvider == "radio"
pl := playlist.New()
if cfg.Playlist != "" && localProv != nil {
tracks, err := localProv.Tracks(cfg.Playlist)
if err != nil {
return fmt.Errorf("playlist %q: %w", cfg.Playlist, err)
}
pl.Add(tracks...)
cfg.AutoPlay = true
} else if defaultRadio {
pl.Add(
playlist.Track{Path: "http://radio.cliamp.stream/lofi/stream", Title: "Lofi Stream", Stream: true},
playlist.Track{Path: "http://radio.cliamp.stream/synthwave/stream", Title: "Synthwave Stream", Stream: true},
playlist.Track{Path: "http://radio.cliamp.stream/edm/stream", Title: "EDM Stream", Stream: true},
)
}
pl.Add(resolved.Tracks...)
if cfg.AudioDevice != "" {
cleanup := player.PrepareAudioDevice(cfg.AudioDevice)
defer cleanup()
}
sampleRate := cfg.SampleRate
if sampleRate == 0 {
if detected := player.DeviceSampleRate(); detected > 0 {
sampleRate = detected
} else {
sampleRate = 44100
}
}
p, err := player.New(player.Quality{
SampleRate: sampleRate,
BufferMs: cfg.BufferMs,
ResampleQuality: cfg.ResampleQuality,
BitDepth: cfg.BitDepth,
})
if err != nil {
return fmt.Errorf("player: %w", err)
}
defer p.Close()
if spotifyProv != nil {
p.RegisterStreamerFactory("spotify:", spotifyProv.NewStreamer)
}
p.RegisterBufferedURLMatcher(func(u string) bool {
return navidrome.IsSubsonicStreamURL(u) || jellyfin.IsStreamURL(u) || emby.IsStreamURL(u)
})
cfg.ApplyPlayer(p)
cfg.ApplyPlaylist(pl)
ui.SetPadding(cfg.PaddingH, cfg.PaddingV)
if daemon {
return runDaemon(p, pl, localProv, cfg.AutoPlay)
}
themes := theme.LoadAll()
luaMgr, luaErr := luaplugin.New(cfg.Plugins)
if luaErr != nil {
fmt.Fprintf(os.Stderr, "lua plugins: %v\n", luaErr)
}
if luaMgr != nil {
defer luaMgr.Close()
luaMgr.SetReservedKeys(model.ReservedKeys())
}
m := model.New(p, pl, providers, defaultProvider, localProv, themes, luaMgr, config.SaveFunc{})
if luaMgr != nil {
luaMgr.SetStateProvider(luaplugin.StateProvider{
PlayerState: func() string {
if !p.IsPlaying() {
return "stopped"
}
if p.IsPaused() {
return "paused"
}
return "playing"
},
Position: func() float64 { return p.Position().Seconds() },
Duration: func() float64 { return p.Duration().Seconds() },
Volume: func() float64 { return p.Volume() },
Speed: func() float64 { return p.Speed() },
Mono: func() bool { return p.Mono() },
RepeatMode: func() string { return pl.Repeat().String() },
Shuffle: func() bool { return pl.Shuffled() },
EQBands: func() [10]float64 { return p.EQBands() },
TrackTitle: func() string { t, _ := pl.Current(); return t.Title },
TrackArtist: func() string { t, _ := pl.Current(); return t.Artist },
TrackAlbum: func() string { t, _ := pl.Current(); return t.Album },
TrackGenre: func() string { t, _ := pl.Current(); return t.Genre },
TrackYear: func() int { t, _ := pl.Current(); return t.Year },
TrackNumber: func() int { t, _ := pl.Current(); return t.TrackNumber },
TrackPath: func() string { t, _ := pl.Current(); return t.Path },
TrackIsStream: func() bool { t, _ := pl.Current(); return t.Stream },
TrackDuration: func() int { t, _ := pl.Current(); return t.DurationSecs },
PlaylistCount: func() int { return pl.Len() },
CurrentIndex: func() int { return pl.Index() },
})
}
if luaMgr != nil {
if names := luaMgr.Visualizers(); len(names) > 0 {
m.RegisterLuaVisualizers(names, luaMgr.RenderVis)
}
}
m.SetSeekStepLarge(cfg.SeekStepLargeDuration())
m.SetInitialDirectory(cfg.InitialDirectory)
m.SetPendingURLs(resolved.Pending)
if len(resolved.Tracks) == 0 && len(resolved.Pending) == 0 && pl.Len() == 0 {
m.StartInProvider()
}
if cfg.EQPreset != "" && cfg.EQPreset != "Custom" {
m.SetEQPreset(cfg.EQPreset, nil)
}
if cfg.Theme != "" {
m.SetTheme(cfg.Theme)
}
if cfg.Visualizer != "" {
m.SetVisualizer(cfg.Visualizer)
}
if cfg.AutoPlay {
m.SetAutoPlay(true)
}
if cfg.Compact {
m.SetCompact(true)
}
if !defaultRadio && len(positional) > 0 {
if rs := resume.Load(); rs.Path != "" && rs.PositionSec > 0 {
m.SetResume(rs.Path, rs.PositionSec)
}
}
prog := tea.NewProgram(m)
svc, svcErr := wireMediaCtl(prog)
if svcErr == nil && svc != nil {
defer svc.Close()
}
if luaMgr != nil {
luaMgr.SetControlProvider(luaplugin.ControlProvider{
SetVolume: func(db float64) { p.SetVolume(db) },
SetSpeed: func(ratio float64) { p.SetSpeed(ratio) },
SetEQBand: func(band int, db float64) { p.SetEQBand(band, db) },
ToggleMono: func() { p.ToggleMono() },
TogglePause: func() { p.TogglePause() },
Stop: func() { p.Stop() },
Seek: func(secs float64) {
_ = p.Seek(time.Duration(secs * float64(time.Second)))
},
SetEQPreset: func(name string, bands *[10]float64) {
prog.Send(model.SetEQPresetMsg{Name: name, Bands: bands})
},
Next: func() { prog.Send(playback.NextMsg{}) },
Prev: func() { prog.Send(playback.PrevMsg{}) },
})
luaMgr.SetUIProvider(luaplugin.UIProvider{
ShowMessage: func(text string, duration time.Duration) {
prog.Send(model.ShowStatusMsg{Text: text, Duration: duration})
},
})
}
ipcSrv, ipcErr := ipc.NewServer(ipc.DefaultSocketPath(), ipc.DispatcherFunc(func(msg any) { prog.Send(msg) }))
if ipcErr != nil {
fmt.Fprintf(os.Stderr, "ipc: %v\n", ipcErr)
} else {
defer ipcSrv.Close()
if luaMgr != nil {
ipcSrv.SetPluginDispatcher(luaMgr)
}
}
finalModel, err := mediactl.Run(prog, svc)
if err != nil {
return err
}
if fm, ok := finalModel.(model.Model); ok {
themeName := fm.ThemeName()
if themeName == theme.DefaultName {
themeName = ""
}
_ = config.Save("theme", fmt.Sprintf("%q", themeName))
if path, secs, pl := fm.ResumeState(); path != "" && secs > 0 {
resume.Save(path, secs, pl)
}
}
return nil
}
// initLogging always returns a non-nil close func so the caller can defer
// it unconditionally, plus the applied level as a string for diagnostics.
// Errors come back as the third return value; the close func is a no-op
// and the level string is empty in that case.
func initLogging(levelStr string) (func() error, string, error) {
noop := func() error { return nil }
level, err := applog.ParseLevel(levelStr)
if err != nil {
return noop, "", err
}
dir, err := appdir.Dir()
if err != nil {
return noop, "", fmt.Errorf("resolve config dir: %w", err)
}
closeFn, err := applog.Init(filepath.Join(dir, "cliamp.log"), level)
if err != nil {
return noop, "", err
}
return closeFn, level.String(), nil
}
func wireMediaCtl(prog *tea.Program) (*mediactl.Service, error) {
svc, err := mediactl.New(prog.Send)
if err != nil || svc == nil {
return svc, err
}
go prog.Send(model.AttachNotifier(svc))
return svc, nil
}
func ipcSend(req ipc.Request) (ipc.Response, error) {
resp, err := ipc.Send(ipc.DefaultSocketPath(), req)
if err != nil {
return resp, err
}
if !resp.OK {
return resp, fmt.Errorf("%s", resp.Error)
}
return resp, nil
}
// ipcSendLong is like ipcSend with a caller-chosen deadline, for plugin
// commands that can legitimately run for minutes (e.g. yt-dlp downloads).
func ipcSendLong(req ipc.Request, deadline time.Duration) (ipc.Response, error) {
resp, err := ipc.SendWithDeadline(ipc.DefaultSocketPath(), req, deadline)
if err != nil {
return resp, err
}
if !resp.OK {
return resp, fmt.Errorf("%s", resp.Error)
}
return resp, nil
}
func main() {
appmeta.SetVersion(version)
app := buildApp()
if err := app.Run(context.Background(), os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}