- PUT/DELETE /wishlist/{artist} and GET /wishlist: the artists I want.
- POST/DELETE /discover/{artist}/dismiss and GET /discover/dismissed: the
artists I am not interested in. An artist is wished or dismissed, never both,
and both lists are mine alone.
- Discover never suggests a dismissed artist, does not use one as a seed taken
from my listening, and marks the wished ones it shows (wishlisted).
- New artist_feedback table (migration 0012, SQLite and PostgreSQL), removed
with the account.
- An artist I marked is not cleaned up when the list that named it is replaced,
and goes when its last mark is taken off and nobody names it. Taking a
provider's data back still removes what only it named, marks included.
- Spec, contract test and README updated.
Closes #35
202 lines
6.7 KiB
Go
202 lines
6.7 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
|
|
httpapi "codeberg.org/squidd/sonda/internal/api/http"
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
"codeberg.org/squidd/sonda/internal/catalog"
|
|
"codeberg.org/squidd/sonda/internal/config"
|
|
"codeberg.org/squidd/sonda/internal/discover"
|
|
"codeberg.org/squidd/sonda/internal/discovery"
|
|
"codeberg.org/squidd/sonda/internal/feedback"
|
|
"codeberg.org/squidd/sonda/internal/library"
|
|
"codeberg.org/squidd/sonda/internal/listening"
|
|
"codeberg.org/squidd/sonda/internal/providers"
|
|
"codeberg.org/squidd/sonda/internal/providers/lastfm"
|
|
"codeberg.org/squidd/sonda/internal/providers/musicbrainz"
|
|
"codeberg.org/squidd/sonda/internal/providers/outbound"
|
|
"codeberg.org/squidd/sonda/internal/storage"
|
|
"codeberg.org/squidd/sonda/internal/streaming"
|
|
"codeberg.org/squidd/sonda/internal/taste"
|
|
"codeberg.org/squidd/sonda/internal/usersettings"
|
|
"codeberg.org/squidd/sonda/migrations"
|
|
)
|
|
|
|
const defaultConfigFile = "sonda.toml"
|
|
|
|
// version goes into the User-Agent sent to providers.
|
|
const version = "0.1.0"
|
|
|
|
// lastfmMinInterval spaces the requests to Last.fm well below its limit.
|
|
const lastfmMinInterval = 250 * time.Millisecond
|
|
|
|
// musicbrainzMinInterval keeps a little above MusicBrainz's rule of one request a second.
|
|
const musicbrainzMinInterval = 1100 * time.Millisecond
|
|
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintln(os.Stderr, "sondad:", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run() error {
|
|
configPath := flag.String("config", "", "path to the TOML config file (default ./"+defaultConfigFile+" if present)")
|
|
flag.Parse()
|
|
|
|
path := *configPath
|
|
if path == "" {
|
|
if _, err := os.Stat(defaultConfigFile); err == nil {
|
|
path = defaultConfigFile
|
|
}
|
|
}
|
|
|
|
cfg, err := config.Load(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := cfg.Validate(); err != nil {
|
|
return fmt.Errorf("invalid config: %w", err)
|
|
}
|
|
|
|
logger, err := newLogger(cfg.Log.Env)
|
|
if err != nil {
|
|
return fmt.Errorf("create logger: %w", err)
|
|
}
|
|
defer func() { _ = logger.Sync() }()
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
target := cfg.Database.Path
|
|
if cfg.Database.Driver == storage.DriverPostgres {
|
|
target = cfg.Database.DSN
|
|
}
|
|
db, err := storage.Open(cfg.Database.Driver, target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = db.Close() }()
|
|
|
|
dbMigrations, err := migrations.For(cfg.Database.Driver)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := storage.Migrate(ctx, db, dbMigrations); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Composition root: build services and hand them to the HTTP layer.
|
|
tokens := auth.NewTokenIssuer(cfg.Auth.JWTSecret, cfg.Auth.AccessTTL())
|
|
if cfg.Log.Env == "production" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
libraryRepo := storage.NewLibraryRepo(db)
|
|
if err := libraryRepo.RefreshMatchKeys(ctx); err != nil {
|
|
return err
|
|
}
|
|
scanner := library.NewScanner(libraryRepo, library.TaglibReader{}, library.NewHub(), cfg.Library.ScanWorkers)
|
|
scans := library.NewManager(scanner, libraryRepo)
|
|
logScanResults(logger, scans)
|
|
|
|
libraries := library.NewLibraries(libraryRepo)
|
|
libraries.SetBusy(func() bool { return scans.Status().Running })
|
|
warnAboutLibraries(ctx, logger, libraries)
|
|
|
|
// External providers: nothing is contacted unless an admin switched one on.
|
|
providerSettings := providers.NewService(storage.NewProviderRepo(db))
|
|
lastfmClient := lastfm.New(outbound.New(outbound.Options{
|
|
UserAgent: providers.UserAgent(version, ""),
|
|
MinInterval: lastfmMinInterval,
|
|
}), lastfm.BaseURL)
|
|
providerSettings.SetChecker(providers.LastFM, lastfmClient.Probe)
|
|
// MusicBrainz wants a contact in the User-Agent, which an admin can change: it
|
|
// is read again for every request.
|
|
musicbrainzClient := musicbrainz.New(outbound.New(outbound.Options{
|
|
UserAgentFunc: providerSettings.UserAgentFor(providers.MusicBrainz, version),
|
|
MinInterval: musicbrainzMinInterval,
|
|
}), musicbrainz.BaseURL)
|
|
providerSettings.SetChecker(providers.MusicBrainz, func(ctx context.Context, _ string) error {
|
|
return musicbrainzClient.Probe(ctx)
|
|
})
|
|
discoveryRepo := storage.NewDiscoveryRepo(db)
|
|
providerSettings.SetPurger(func(ctx context.Context, name string) (providers.Purged, error) {
|
|
return discoveryRepo.Purge(ctx, name)
|
|
})
|
|
discoveries := discovery.NewService(discoveryRepo, lastfmClient, providerSettings, logger)
|
|
tags := discovery.NewTagService(discoveryRepo, map[string]discovery.TagSource{
|
|
providers.LastFM: discovery.LastfmTags{Client: lastfmClient},
|
|
providers.MusicBrainz: discovery.MusicBrainzTags{Client: musicbrainzClient},
|
|
}, providerSettings, logger)
|
|
|
|
tasteRepo := storage.NewTasteRepo(db)
|
|
tasteService := taste.NewService(tasteRepo, taste.Options{MinListen: cfg.Listening.MinListen(), HalfLife: cfg.Taste.HalfLife()})
|
|
userSettings := usersettings.NewService(storage.NewUserSettingsRepo(db))
|
|
feedbacks := feedback.NewService(storage.NewFeedbackRepo(db))
|
|
weights := discover.Weights{
|
|
Affinity: cfg.Scoring.WeightAffinity, Genre: cfg.Scoring.WeightGenre,
|
|
Preference: cfg.Scoring.WeightPreference, Discovery: cfg.Scoring.WeightDiscovery,
|
|
}
|
|
|
|
router := httpapi.NewRouter(httpapi.Deps{
|
|
Logger: logger,
|
|
Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()),
|
|
Tokens: tokens,
|
|
Listening: listening.NewService(storage.NewListeningRepo(db), cfg.Listening.MinListen()),
|
|
Scan: scanControl{ctx: ctx, m: scans},
|
|
Libraries: libraries,
|
|
Catalog: catalog.NewService(storage.NewCatalogRepo(db)),
|
|
Providers: providerSettings,
|
|
Discovery: discoveries,
|
|
Tags: tags,
|
|
Taste: tasteService,
|
|
Discover: discover.NewService(tasteService, discoveries, tags, tasteRepo, userSettings, feedbacks, weights),
|
|
Feedback: feedbacks,
|
|
Settings: userSettings,
|
|
Streams: streaming.NewService(libraryRepo),
|
|
})
|
|
|
|
// No WriteTimeout: audio streaming (later) needs long responses.
|
|
srv := &http.Server{
|
|
Addr: cfg.Server.Listen,
|
|
Handler: router,
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
IdleTimeout: 2 * time.Minute,
|
|
}
|
|
|
|
logger.Info("sondad starting",
|
|
zap.String("config", path),
|
|
zap.String("env", cfg.Log.Env),
|
|
zap.String("listen", cfg.Server.Listen),
|
|
zap.String("database_driver", cfg.Database.Driver), // never log the DSN: it holds the password
|
|
)
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- srv.ListenAndServe() }()
|
|
|
|
select {
|
|
case err := <-serveErr:
|
|
return fmt.Errorf("http server: %w", err)
|
|
case <-ctx.Done():
|
|
logger.Info("shutting down")
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
return fmt.Errorf("shutdown: %w", err)
|
|
}
|
|
return nil
|
|
}
|