/
gonic.go
463 lines (398 loc) · 13.9 KB
/
gonic.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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//nolint:lll,gocyclo,forbidigo
package main
import (
"errors"
"expvar"
"flag"
"fmt"
"log"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
// avatar encode/decode
_ "image/gif"
_ "image/png"
"github.com/google/shlex"
"github.com/gorilla/securecookie"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/oklog/run"
"github.com/peterbourgon/ff"
"github.com/sentriz/gormstore"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/handlerutil"
"go.senan.xyz/gonic/jukebox"
"go.senan.xyz/gonic/lastfm"
"go.senan.xyz/gonic/listenbrainz"
"go.senan.xyz/gonic/playlist"
"go.senan.xyz/gonic/podcasts"
"go.senan.xyz/gonic/scanner"
"go.senan.xyz/gonic/scanner/tags/tagcommon"
"go.senan.xyz/gonic/scanner/tags/taglib"
"go.senan.xyz/gonic/scrobble"
"go.senan.xyz/gonic/server/ctrladmin"
"go.senan.xyz/gonic/server/ctrlsubsonic"
"go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
"go.senan.xyz/gonic/transcode"
)
func main() {
set := flag.NewFlagSet(gonic.Name, flag.ExitOnError)
confListenAddr := set.String("listen-addr", "0.0.0.0:4747", "listen address (optional)")
confTLSCert := set.String("tls-cert", "", "path to TLS certificate (optional)")
confTLSKey := set.String("tls-key", "", "path to TLS private key (optional)")
confPodcastPurgeAgeDays := set.Int("podcast-purge-age", 0, "age (in days) to purge podcast episodes if not accessed (optional)")
confPodcastPath := set.String("podcast-path", "", "path to podcasts")
confCachePath := set.String("cache-path", "", "path to cache")
var confMusicPaths pathAliases
set.Var(&confMusicPaths, "music-path", "path to music")
confPlaylistsPath := set.String("playlists-path", "", "path to your list of new or existing m3u playlists that gonic can manage")
confDBPath := set.String("db-path", "gonic.db", "path to database (optional)")
confScanIntervalMins := set.Int("scan-interval", 0, "interval (in minutes) to automatically scan music (optional)")
confScanAtStart := set.Bool("scan-at-start-enabled", false, "whether to perform an initial scan at startup (optional)")
confScanWatcher := set.Bool("scan-watcher-enabled", false, "whether to watch file system for new music and rescan (optional)")
confJukeboxEnabled := set.Bool("jukebox-enabled", false, "whether the subsonic jukebox api should be enabled (optional)")
confJukeboxMPVExtraArgs := set.String("jukebox-mpv-extra-args", "", "extra command line arguments to pass to the jukebox mpv daemon (optional)")
confProxyPrefix := set.String("proxy-prefix", "", "url path prefix to use if behind proxy. eg '/gonic' (optional)")
confHTTPLog := set.Bool("http-log", true, "http request logging (optional)")
confShowVersion := set.Bool("version", false, "show gonic version")
_ = set.String("config-path", "", "path to config (optional)")
confExcludePatterns := set.String("exclude-pattern", "", "regex pattern to exclude files from scan (optional)")
var confMultiValueGenre, confMultiValueAlbumArtist multiValueSetting
set.Var(&confMultiValueGenre, "multi-value-genre", "setting for mutli-valued genre scanning (optional)")
set.Var(&confMultiValueAlbumArtist, "multi-value-album-artist", "setting for mutli-valued album artist scanning (optional)")
confExpvar := set.Bool("expvar", false, "enable the /debug/vars endpoint (optional)")
deprecatedConfGenreSplit := set.String("genre-split", "", "(deprecated, see multi-value settings)")
if _, err := regexp.Compile(*confExcludePatterns); err != nil {
log.Fatalf("invalid exclude pattern: %v\n", err)
}
if err := ff.Parse(set, os.Args[1:],
ff.WithConfigFileFlag("config-path"),
ff.WithConfigFileParser(ff.PlainParser),
ff.WithEnvVarPrefix(gonic.NameUpper),
); err != nil {
log.Fatalf("error parsing args: %v\n", err)
}
if *confShowVersion {
fmt.Printf("v%s\n", gonic.Version)
os.Exit(0)
}
if len(confMusicPaths) == 0 {
log.Fatalf("please provide a music directory")
}
var err error
for i, confMusicPath := range confMusicPaths {
if confMusicPaths[i].path, err = validatePath(confMusicPath.path); err != nil {
log.Fatalf("checking music dir %q: %v", confMusicPath.path, err)
}
}
if *confPodcastPath, err = validatePath(*confPodcastPath); err != nil {
log.Fatalf("checking podcast directory: %v", err)
}
if *confCachePath, err = validatePath(*confCachePath); err != nil {
log.Fatalf("checking cache directory: %v", err)
}
if *confPlaylistsPath, err = validatePath(*confPlaylistsPath); err != nil {
log.Fatalf("checking playlist directory: %v", err)
}
cacheDirAudio := path.Join(*confCachePath, "audio")
cacheDirCovers := path.Join(*confCachePath, "covers")
if err := os.MkdirAll(cacheDirAudio, os.ModePerm); err != nil {
log.Fatalf("couldn't create audio cache path: %v\n", err)
}
if err := os.MkdirAll(cacheDirCovers, os.ModePerm); err != nil {
log.Fatalf("couldn't create covers cache path: %v\n", err)
}
dbc, err := db.New(*confDBPath, db.DefaultOptions())
if err != nil {
log.Fatalf("error opening database: %v\n", err)
}
defer dbc.Close()
err = dbc.Migrate(db.MigrationContext{
OriginalMusicPath: confMusicPaths[0].path,
PlaylistsPath: *confPlaylistsPath,
PodcastsPath: *confPodcastPath,
})
if err != nil {
log.Panicf("error migrating database: %v\n", err)
}
var musicPaths []ctrlsubsonic.MusicPath
for _, pa := range confMusicPaths {
musicPaths = append(musicPaths, ctrlsubsonic.MusicPath{Alias: pa.alias, Path: pa.path})
}
proxyPrefixExpr := regexp.MustCompile(`^\/*(.*?)\/*$`)
*confProxyPrefix = proxyPrefixExpr.ReplaceAllString(*confProxyPrefix, `/$1`)
if *deprecatedConfGenreSplit != "" && *deprecatedConfGenreSplit != "\n" {
confMultiValueGenre = multiValueSetting{Mode: scanner.Delim, Delim: *deprecatedConfGenreSplit}
*deprecatedConfGenreSplit = "<deprecated>"
}
log.Printf("starting gonic v%s\n", gonic.Version)
log.Printf("provided config\n")
set.VisitAll(func(f *flag.Flag) {
value := strings.ReplaceAll(f.Value.String(), "\n", "")
log.Printf(" %-25s %s\n", f.Name, value)
})
tagReader := tagcommon.ChainReader{
taglib.TagLib{},
// ffprobe reader?
// nfo reader?
}
scannr := scanner.New(
ctrlsubsonic.MusicPaths(musicPaths),
dbc,
map[scanner.Tag]scanner.MultiValueSetting{
scanner.Genre: scanner.MultiValueSetting(confMultiValueGenre),
scanner.AlbumArtist: scanner.MultiValueSetting(confMultiValueAlbumArtist),
},
tagReader,
*confExcludePatterns,
)
podcast := podcasts.New(dbc, *confPodcastPath, tagReader)
transcoder := transcode.NewCachingTranscoder(
transcode.NewFFmpegTranscoder(),
cacheDirAudio,
)
lastfmClientKeySecretFunc := func() (string, string, error) {
apiKey, _ := dbc.GetSetting(db.LastFMAPIKey)
secret, _ := dbc.GetSetting(db.LastFMSecret)
if apiKey == "" || secret == "" {
return "", "", fmt.Errorf("not configured")
}
return apiKey, secret, nil
}
listenbrainzClient := listenbrainz.NewClient()
lastfmClient := lastfm.NewClient(lastfmClientKeySecretFunc)
playlistStore, err := playlist.NewStore(*confPlaylistsPath)
if err != nil {
log.Panicf("error creating playlists store: %v", err)
}
var jukebx *jukebox.Jukebox
if *confJukeboxEnabled {
jukebx = jukebox.New()
}
sessKey, err := dbc.GetSetting("session_key")
if err != nil {
log.Panicf("error getting session key: %v\n", err)
}
if sessKey == "" {
if err := dbc.SetSetting("session_key", string(securecookie.GenerateRandomKey(32))); err != nil {
log.Panicf("error setting session key: %v\n", err)
}
}
sessDB := gormstore.New(dbc.DB, []byte(sessKey))
sessDB.SessionOpts.HttpOnly = true
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode
artistInfoCache := artistinfocache.New(dbc, lastfmClient)
scrobblers := []scrobble.Scrobbler{lastfmClient, listenbrainzClient}
resolveProxyPath := func(in string) string {
return path.Join(*confProxyPrefix, in)
}
ctrlAdmin, err := ctrladmin.New(dbc, sessDB, scannr, podcast, lastfmClient, resolveProxyPath)
if err != nil {
log.Panicf("error creating admin controller: %v\n", err)
}
ctrlSubsonic, err := ctrlsubsonic.New(dbc, scannr, musicPaths, *confPodcastPath, cacheDirAudio, cacheDirCovers, jukebx, playlistStore, scrobblers, podcast, transcoder, lastfmClient, artistInfoCache, resolveProxyPath)
if err != nil {
log.Panicf("error creating subsonic controller: %v\n", err)
}
chain := handlerutil.Chain()
if *confHTTPLog {
chain = handlerutil.Chain(handlerutil.Log)
}
chain = handlerutil.Chain(
chain,
handlerutil.BasicCORS,
)
trim := handlerutil.TrimPathSuffix(".view") // /x.view and /x should match the same
mux := http.NewServeMux()
mux.Handle("/admin/", http.StripPrefix("/admin", chain(ctrlAdmin)))
mux.Handle("/rest/", http.StripPrefix("/rest", chain(trim(ctrlSubsonic))))
mux.Handle("/ping", chain(handlerutil.Message("ok")))
mux.Handle("/", chain(handlerutil.Redirect(resolveProxyPath("/admin/home"))))
if *confExpvar {
mux.Handle("/debug/vars", expvar.Handler())
expvar.Publish("stats", expvar.Func(func() any {
var stats struct{ Albums, Tracks, Artists, InternetRadioStations, Podcasts uint }
dbc.Model(db.Album{}).Count(&stats.Albums)
dbc.Model(db.Track{}).Count(&stats.Tracks)
dbc.Model(db.Artist{}).Count(&stats.Artists)
dbc.Model(db.InternetRadioStation{}).Count(&stats.InternetRadioStations)
dbc.Model(db.Podcast{}).Count(&stats.Podcasts)
return stats
}))
}
noCleanup := func(_ error) {}
var g run.Group
g.Add(func() error {
log.Print("starting job 'http'\n")
server := &http.Server{
Addr: *confListenAddr,
Handler: mux,
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 80 * time.Second,
IdleTimeout: 60 * time.Second,
}
if *confTLSCert != "" && *confTLSKey != "" {
return server.ListenAndServeTLS(*confTLSCert, *confTLSKey)
}
return server.ListenAndServe()
}, noCleanup)
g.Add(func() error {
log.Printf("starting job 'session clean'\n")
ticker := time.NewTicker(10 * time.Minute)
for range ticker.C {
sessDB.Cleanup()
}
return nil
}, noCleanup)
g.Add(func() error {
log.Printf("starting job 'podcast refresher'\n")
ticker := time.NewTicker(time.Hour)
for range ticker.C {
if err := podcast.RefreshPodcasts(); err != nil {
log.Printf("failed to refresh some feeds: %s", err)
}
}
return nil
}, noCleanup)
if *confPodcastPurgeAgeDays > 0 {
g.Add(func() error {
log.Printf("starting job 'podcast purger'\n")
ticker := time.NewTicker(24 * time.Hour)
for range ticker.C {
if err := podcast.PurgeOldPodcasts(time.Duration(*confPodcastPurgeAgeDays) * 24 * time.Hour); err != nil {
log.Printf("error purging old podcasts: %v", err)
}
}
return nil
}, noCleanup)
}
if *confScanIntervalMins > 0 {
g.Add(func() error {
log.Printf("starting job 'scan timer'\n")
ticker := time.NewTicker(time.Duration(*confScanIntervalMins) * time.Minute)
for range ticker.C {
if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
log.Printf("error scanning: %v", err)
}
}
return nil
}, noCleanup)
}
if *confScanWatcher {
g.Add(func() error {
log.Printf("starting job 'scan watcher'\n")
return scannr.ExecuteWatch()
}, func(_ error) {
scannr.CancelWatch()
})
}
if jukebx != nil {
var jukeboxTempDir string
g.Add(func() error {
log.Printf("starting job 'jukebox'\n")
extraArgs, _ := shlex.Split(*confJukeboxMPVExtraArgs)
var err error
jukeboxTempDir, err = os.MkdirTemp("", "gonic-jukebox-*")
if err != nil {
return fmt.Errorf("create tmp sock file: %w", err)
}
sockPath := filepath.Join(jukeboxTempDir, "sock")
if err := jukebx.Start(sockPath, extraArgs); err != nil {
return fmt.Errorf("start jukebox: %w", err)
}
if err := jukebx.Wait(); err != nil {
return fmt.Errorf("start jukebox: %w", err)
}
return nil
}, func(_ error) {
if err := jukebx.Quit(); err != nil {
log.Printf("error quitting jukebox: %v", err)
}
_ = os.RemoveAll(jukeboxTempDir)
})
}
if _, _, err := lastfmClientKeySecretFunc(); err == nil {
g.Add(func() error {
log.Printf("starting job 'refresh artist info'\n")
return artistInfoCache.Refresh(8 * time.Second)
}, noCleanup)
}
if *confScanAtStart {
if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
log.Panicf("error scanning at start: %v\n", err)
}
}
if err := g.Run(); err != nil {
log.Panicf("error in job: %v", err)
}
}
const pathAliasSep = "->"
type (
pathAliases []pathAlias
pathAlias struct{ alias, path string }
)
func (pa pathAliases) String() string {
var strs []string
for _, p := range pa {
if p.alias != "" {
strs = append(strs, fmt.Sprintf("%s %s %s", p.alias, pathAliasSep, p.path))
continue
}
strs = append(strs, p.path)
}
return strings.Join(strs, ", ")
}
func (pa *pathAliases) Set(value string) error {
if name, path, ok := strings.Cut(value, pathAliasSep); ok {
*pa = append(*pa, pathAlias{alias: name, path: path})
return nil
}
*pa = append(*pa, pathAlias{path: value})
return nil
}
func validatePath(p string) (string, error) {
if p == "" {
return "", errors.New("path can't be empty")
}
if _, err := os.Stat(p); os.IsNotExist(err) {
return "", errors.New("path does not exist, please provide one")
}
p, err := filepath.Abs(p)
if err != nil {
return "", fmt.Errorf("make absolute: %w", err)
}
return p, nil
}
type multiValueSetting scanner.MultiValueSetting
func (mvs multiValueSetting) String() string {
switch mvs.Mode {
case scanner.Delim:
return fmt.Sprintf("delim(%s)", mvs.Delim)
case scanner.Multi:
return fmt.Sprint("multi", mvs.Delim)
default:
return "none"
}
}
func (mvs *multiValueSetting) Set(value string) error {
mode, delim, _ := strings.Cut(value, " ")
switch mode {
case "delim":
if delim == "" {
return fmt.Errorf("no delimiter provided for delimiter mode")
}
mvs.Mode = scanner.Delim
mvs.Delim = delim
case "multi":
mvs.Mode = scanner.Multi
case "none":
default:
return fmt.Errorf(`unknown multi value mode %q. should be "none" | "multi" | "delim <delim>"`, mode)
}
return nil
}