// Package httpapi is the first-party REST API (/api/v1). // // Handlers stay thin: they validate and serialize, then call services. package httpapi import ( "context" "io/fs" "net/http" "reflect" "strings" "time" "github.com/gin-gonic/gin" "go.uber.org/zap" "git.kmalloc.org/squid/sonda/internal/about" "git.kmalloc.org/squid/sonda/internal/auth" "git.kmalloc.org/squid/sonda/internal/catalog" "git.kmalloc.org/squid/sonda/internal/discover" "git.kmalloc.org/squid/sonda/internal/discovery" "git.kmalloc.org/squid/sonda/internal/duplicates" "git.kmalloc.org/squid/sonda/internal/feedback" "git.kmalloc.org/squid/sonda/internal/images" "git.kmalloc.org/squid/sonda/internal/jobs" "git.kmalloc.org/squid/sonda/internal/library" "git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/mastodon" "git.kmalloc.org/squid/sonda/internal/mixes" "git.kmalloc.org/squid/sonda/internal/naming" "git.kmalloc.org/squid/sonda/internal/opensubsonic" "git.kmalloc.org/squid/sonda/internal/playlists" "git.kmalloc.org/squid/sonda/internal/providers" "git.kmalloc.org/squid/sonda/internal/smart" "git.kmalloc.org/squid/sonda/internal/spotifyimport" "git.kmalloc.org/squid/sonda/internal/streaming" "git.kmalloc.org/squid/sonda/internal/taste" "git.kmalloc.org/squid/sonda/internal/usersettings" ) // maxBodyBytes bounds every request body. const maxBodyBytes = 64 << 10 type authService interface { Register(ctx context.Context, email, password string) (auth.User, error) Login(ctx context.Context, email, password string) (auth.Session, error) Refresh(ctx context.Context, refreshToken string) (auth.Session, error) Logout(ctx context.Context, refreshToken string) error User(ctx context.Context, id int64) (auth.User, error) ChangePassword(ctx context.Context, userID int64, current, next string) error ListUsers(ctx context.Context) ([]auth.User, error) CreateUser(ctx context.Context, email, password string, isAdmin bool) (auth.User, error) SetAdmin(ctx context.Context, id int64, isAdmin bool) (auth.User, error) ResetPassword(ctx context.Context, id int64, password string) error DeleteUser(ctx context.Context, id int64) error } type tokenParser interface { Parse(token string) (auth.Claims, error) } type listenService interface { Record(ctx context.Context, e listening.Event) (listening.Result, error) List(ctx context.Context, userID int64, f listening.Filter) (listening.Page, error) Months(ctx context.Context, userID int64, loc *time.Location) ([]listening.Month, error) } type streamService interface { Open(ctx context.Context, trackID int64) (*streaming.Stream, error) } type scanService interface { Start(full bool) error StartLibrary(id int64, full bool) error Status() library.Status } type providerService interface { List(ctx context.Context) ([]providers.Info, error) Update(ctx context.Context, name string, p providers.Patch) (providers.Info, error) Test(ctx context.Context, name string) (providers.TestResult, error) Purge(ctx context.Context, name string) (providers.Purged, error) } type tagService interface { Tags(ctx context.Context, artistID int64) (discovery.TagResult, error) } type discoveryService interface { Similar(ctx context.Context, artistID int64, limit int) (discovery.Result, error) } type discoverService interface { Discover(ctx context.Context, userID int64, q discover.Query) (discover.Result, error) } // playlistService is what the handlers need from playlists.Service. type playlistService interface { Create(ctx context.Context, userID int64, name, description string) (playlists.Playlist, error) List(ctx context.Context, userID int64, p playlists.Page) (playlists.Listing, error) Get(ctx context.Context, userID, id int64) (playlists.Playlist, error) Update(ctx context.Context, userID, id int64, name, description *string) (playlists.Playlist, error) Delete(ctx context.Context, userID, id int64) error Items(ctx context.Context, userID, id int64, p playlists.Page) (playlists.ItemsListing, error) AddTracks(ctx context.Context, userID, id int64, trackIDs []int64, position *int) (playlists.Playlist, error) RemoveItem(ctx context.Context, userID, id, itemID int64) error MoveItem(ctx context.Context, userID, id, itemID int64, position int) error } // spotifyImportService is what the handlers need from spotifyimport.Service. type spotifyImportService interface { Import(ctx context.Context, userID int64, files []spotifyimport.File) (spotifyimport.Run, error) History(ctx context.Context, userID int64, limit, offset int) (spotifyimport.RunPage, error) } // listeningSuggestionService is what the handlers need from affinity.Service. // (declared in handlers_suggestions.go) // mixService is what the handlers need from mixes.Service. type mixService interface { List(ctx context.Context, userID int64) ([]mixes.Mix, error) Get(ctx context.Context, userID int64, id string, variant int) (mixes.Mix, []catalog.Track, error) Radios(ctx context.Context, userID int64) ([]mixes.Mix, error) Radio(ctx context.Context, userID int64, id string) (mixes.Mix, []catalog.Track, error) } // namingService is what the handlers need from naming.Service. type namingService interface { FactsOf(ctx context.Context, kind string, tracks []catalog.Track, hint string) (naming.Facts, error) Suggest(ctx context.Context, f naming.Facts, lang string) (naming.Suggestion, error) Auto(ctx context.Context) bool Report(ctx context.Context, days int) (naming.Report, error) } // smartService is what the handlers need from smart.Service. type smartService interface { Create(ctx context.Context, userID int64, in smart.Input) (smart.SmartPlaylist, error) List(ctx context.Context, userID int64, limit, offset int) (smart.Listing, error) Get(ctx context.Context, userID, id int64) (smart.SmartPlaylist, error) Update(ctx context.Context, userID, id int64, p smart.Patch) (smart.SmartPlaylist, error) Delete(ctx context.Context, userID, id int64) error Tracks(ctx context.Context, userID, id int64, variant int) (smart.SmartPlaylist, []catalog.Track, error) Preview(ctx context.Context, userID int64, in smart.Input, variant int) ([]catalog.Track, error) Genres(ctx context.Context) ([]smart.GenreCount, error) SuggestedTracks(ctx context.Context, userID int64, key string, variant int) (smart.SuggestedPlaylist, []catalog.Track, error) Covers(ctx context.Context, userID, id int64, variant int) ([]int64, error) SuggestedCovers(ctx context.Context, userID int64, key string, variant int) ([]int64, error) } type feedbackService interface { Add(ctx context.Context, userID, artistID int64, kind feedback.Kind) error Remove(ctx context.Context, userID, artistID int64, kind feedback.Kind) error List(ctx context.Context, userID int64, kind feedback.Kind, p feedback.Page) (feedback.Listing, error) } type artistImageService interface { ArtistImage(ctx context.Context, artistID int64, size images.Size) (*images.Cover, error) } type aboutService interface { Description(ctx context.Context, artistID int64) (about.Result, error) } // jobService is one of the jobs that go through the library: jobs.Runner. type jobService interface { Start(refresh bool) error Stop() bool Status() jobs.Status } type duplicateService interface { Groups(ctx context.Context, limit, offset int) (duplicates.Page, error) Clean(ctx context.Context, keep int64, remove []int64) (duplicates.Result, error) } type coverService interface { AlbumCover(ctx context.Context, albumID int64, size images.Size) (*images.Cover, error) } type tasteService interface { Taste(ctx context.Context, userID int64, limit int) (taste.Profile, error) } type userSettingsService interface { Get(ctx context.Context, userID int64) (usersettings.Settings, error) Update(ctx context.Context, userID int64, p usersettings.Patch) (usersettings.Settings, error) } type mastodonService interface { Status(ctx context.Context, userID int64) (mastodon.Account, bool, error) Connect(ctx context.Context, userID int64, instance, token string) (mastodon.Account, error) Disconnect(ctx context.Context, userID int64) error // Announce asks for a listen to be posted, if the person connected an account. It never waits. Announce(userID, trackID int64) } type catalogService interface { Artists(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Artist], error) Albums(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Album], error) Tracks(ctx context.Context, f catalog.Filter) (catalog.Page[catalog.Track], error) Artist(ctx context.Context, id int64) (catalog.Artist, error) Album(ctx context.Context, id int64) (catalog.Album, error) Track(ctx context.Context, id int64) (catalog.Track, error) } type waveformService interface { Peaks(ctx context.Context, trackID int64) ([]byte, error) } type libraryService interface { List(ctx context.Context) ([]library.Library, error) Create(ctx context.Context, name, path string) (library.Library, error) Update(ctx context.Context, id int64, name, path *string) (library.Library, error) SetShared(ctx context.Context, id int64, shared bool) (library.Library, error) Delete(ctx context.Context, id int64) error } // Build says which Sonda is running: its version, and the commit it was built from when that is known. type Build struct { Version string `json:"version"` Revision string `json:"revision,omitempty"` // Modified is true when the files had changes that were not committed. Modified bool `json:"modified,omitempty"` } // Deps are the services the API needs. type Deps struct { Logger *zap.Logger Build Build Auth authService Tokens tokenParser Listening listenService Mastodon mastodonService Devices deviceService Favorites favoriteService Scan scanService Libraries libraryService Catalog catalogService Providers providerService Lidarr lidarrOptionsService LidarrArtists lidarrArtistService LidarrRequests lidarrRequestService Discovery discoveryService Tags tagService Taste tasteService Discover discoverService Feedback feedbackService Playlists playlistService SpotifyImport spotifyImportService Stats statsService Suggestions listeningSuggestionService Mixes mixService Smart smartService Naming namingService Images coverService CoversJob jobService ArtistImagesJob jobService DescriptionsJob jobService Duplicates duplicateService DuplicatesJob jobService About aboutService ArtistImages artistImageService Settings userSettingsService Streams streamService Federation federationService // What a friend's server reads: the catalogue and the files of the libraries that are shared, and only covers // that were already built. PeerCatalog catalogService PeerStreams streamService // PeerWaveform works out the shape of the tracks of the shared libraries, for a friend. PeerWaveform waveformService PeerCovers coverService // The shape of a track, for the seek bar. Waveform waveformService // OpenSubsonic is the API that other apps use, at /rest. It is optional: with none, /rest does not exist. OpenSubsonic *opensubsonic.Deps // Web is the built web app, served on / and for its own links. It is optional: with none (a build // without the app) / shows a page that says how to build it, and the API works the same. Web fs.FS } // missingDeps names the services of d that were not set. Every field but the logger is an // interface that a handler calls, so one that is nil would panic on its first request. func missingDeps(d Deps) []string { var out []string v := reflect.ValueOf(d) for i := 0; i < v.NumField(); i++ { f := v.Type().Field(i) if f.Name == "Logger" || f.Name == "Web" { continue } if v.Field(i).Kind() == reflect.Interface && v.Field(i).IsNil() { out = append(out, f.Name) } } return out } // NewRouter builds the gin engine with all routes. It panics, at start-up and not at the // first request, when a service was not wired. func NewRouter(d Deps) *gin.Engine { if m := missingDeps(d); len(m) > 0 { panic("httpapi: services not wired: " + strings.Join(m, ", ")) } r := gin.New() _ = r.SetTrustedProxies(nil) // use the socket address; no forwarded-header trust yet r.Use(gin.Recovery(), limitBody(maxBodyBytes), requestLog(d.Logger)) if d.OpenSubsonic != nil { opensubsonic.Register(r, *d.OpenSubsonic) } r.NoRoute(noRoute(d.Web)) v1 := r.Group("/api/v1") v1.GET("/health", health) registerDocs(r, v1) a := &authHandlers{svc: d.Auth} v1.POST("/auth/register", a.register) v1.POST("/auth/login", a.login) v1.POST("/auth/refresh", a.refresh) v1.POST("/auth/logout", a.logout) // Another Sonda server pairs here, with the code of an invite instead of a login. v1.POST("/peer/pair", (&federationHandlers{svc: d.Federation}).pair) registerPeer(v1, d) // Any signed-in user. protected := v1.Group("", requireAuth(d.Tokens, d.Auth, false)) protected.GET("/auth/me", a.me) protected.GET("/version", func(c *gin.Context) { c.JSON(http.StatusOK, d.Build) }) protected.POST("/auth/password", a.changePassword) l := &listenHandlers{svc: d.Listening, announce: d.Mastodon} protected.POST("/listens", l.record) protected.GET("/listens", l.list) protected.GET("/listens/months", l.months) sts := &statsHandlers{svc: d.Stats} protected.GET("/stats/library", sts.library) protected.GET("/stats/listening", sts.listening) sg := &listeningSuggestionHandlers{svc: d.Suggestions} protected.GET("/me/suggestions", sg.list) protected.POST("/me/suggestions/wishlist", sg.wish) ts := &tasteHandlers{svc: d.Taste} protected.GET("/me/taste", ts.taste) dc := &discoverHandlers{svc: d.Discover} protected.GET("/discover", dc.discover) fb := &feedbackHandlers{svc: d.Feedback} protected.GET("/discover/dismissed", fb.list(feedback.Dismissed)) protected.POST("/discover/:id/dismiss", fb.add(feedback.Dismissed)) protected.DELETE("/discover/:id/dismiss", fb.remove(feedback.Dismissed)) pl := &playlistHandlers{svc: d.Playlists} protected.GET("/playlists", pl.list) protected.POST("/playlists", pl.create) protected.GET("/playlists/:id", pl.get) protected.PATCH("/playlists/:id", pl.update) protected.DELETE("/playlists/:id", pl.remove) protected.GET("/playlists/:id/tracks", pl.items) protected.POST("/playlists/:id/tracks", pl.addTracks) protected.DELETE("/playlists/:id/tracks/:item", pl.removeItem) protected.PATCH("/playlists/:id/tracks/:item", pl.moveItem) mx := &mixHandlers{svc: d.Mixes, playlists: d.Playlists, naming: d.Naming} protected.GET("/mixes", mx.list) protected.GET("/mixes/:id", mx.get) protected.POST("/mixes/:id/playlist", mx.save) protected.GET("/radio", mx.radioList) protected.GET("/radio/:id", mx.radioGet) nm := &namingHandlers{svc: d.Naming, playlists: d.Playlists, mixes: d.Mixes, smart: d.Smart} protected.GET("/naming", nm.status) protected.POST("/playlists/:id/suggest-name", nm.playlistName) protected.POST("/mixes/:id/suggest-name", nm.mixName) protected.POST("/smart-playlists/:id/suggest-name", nm.smartName) sm := &smartHandlers{svc: d.Smart, playlists: d.Playlists, naming: d.Naming} protected.GET("/genres", sm.genres) protected.GET("/smart-playlists", sm.list) protected.POST("/smart-playlists", sm.create) protected.POST("/smart-playlists/preview", sm.preview) protected.GET("/smart-playlists/suggested", sm.suggestedList) protected.GET("/smart-playlists/suggested/:key/tracks", sm.suggestedTracks) protected.GET("/smart-playlists/suggested/:key/covers", sm.suggestedCovers) protected.POST("/smart-playlists/suggested/:key/playlist", sm.suggestedSave) protected.GET("/smart-playlists/:id", sm.get) protected.PATCH("/smart-playlists/:id", sm.update) protected.DELETE("/smart-playlists/:id", sm.remove) protected.GET("/smart-playlists/:id/tracks", sm.tracks) protected.GET("/smart-playlists/:id/covers", sm.covers) protected.POST("/smart-playlists/:id/playlist", sm.save) fr := &friendsHandlers{svc: d.Federation} protected.GET("/friends", fr.list) protected.GET("/friends/:friend/artists", relayPage[artistJSON](fr, "artists")) protected.GET("/friends/:friend/artists/:id", relayOne[artistJSON](fr, "artists")) protected.GET("/friends/:friend/albums", relayPage[albumJSON](fr, "albums")) protected.GET("/friends/:friend/albums/:id", relayOne[albumJSON](fr, "albums")) protected.GET("/friends/:friend/tracks", relayPage[trackJSON](fr, "tracks")) protected.GET("/friends/:friend/tracks/:id", relayOne[trackJSON](fr, "tracks")) protected.GET("/friends/:friend/tracks/:id/peaks", fr.peaks) protected.GET("/wishlist", fb.list(feedback.Wishlist)) protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist)) protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist)) us := &userSettingsHandlers{svc: d.Settings} protected.GET("/me/settings", us.get) protected.PATCH("/me/settings", us.update) ma := &mastodonHandlers{svc: d.Mastodon} spotify := &spotifyImportHandlers{svc: d.SpotifyImport} protected.POST("/me/import/spotify", spotify.importExport) protected.GET("/me/import/spotify", spotify.list) protected.GET("/me/mastodon", ma.get) protected.PUT("/me/mastodon", ma.connect) protected.DELETE("/me/mastodon", ma.disconnect) fv := &favoriteHandlers{svc: d.Favorites, catalog: d.Catalog} protected.GET("/me/favorites/ids", fv.ids) protected.GET("/me/favorites/:kind", fv.list) protected.PUT("/me/favorites/:kind/:id", fv.add) protected.DELETE("/me/favorites/:kind/:id", fv.remove) dv := &deviceHandlers{svc: d.Devices} protected.GET("/me/devices", dv.list) protected.POST("/me/devices", dv.create) protected.DELETE("/me/devices/:id", dv.revoke) lib := &libraryHandlers{scan: d.Scan} protected.GET("/library/scan", lib.scanStatus) cj := &jobHandlers{job: d.CoversJob, runningCode: "covers_job_running", summary: coversSummary} protected.GET("/library/covers", cj.status) aj := &jobHandlers{job: d.ArtistImagesJob, runningCode: "artist_images_job_running", summary: artistSummary} protected.GET("/library/artist-images", aj.status) dj := &jobHandlers{job: d.DescriptionsJob, runningCode: "descriptions_job_running", summary: artistSummary} protected.GET("/library/descriptions", dj.status) cat := &catalogHandlers{svc: d.Catalog} protected.GET("/artists", cat.listArtists) protected.GET("/artists/:id", cat.getArtist) disc := &discoveryHandlers{svc: d.Discovery} protected.GET("/artists/:id/similar", disc.similar) tg := &tagsHandlers{svc: d.Tags} protected.GET("/artists/:id/tags", tg.tags) ab := &aboutHandlers{svc: d.About} protected.GET("/artists/:id/description", ab.description) la := &lidarrArtistHandlers{svc: d.LidarrArtists, requests: d.LidarrRequests} protected.GET("/artists/:id/lidarr", la.presence) protected.GET("/artists/:id/image/credit", (&artistImageHandlers{svc: d.ArtistImages}).credit) protected.GET("/albums", cat.listAlbums) protected.GET("/albums/:id", cat.getAlbum) protected.GET("/tracks", cat.listTracks) protected.GET("/tracks/:id", cat.getTrack) protected.GET("/tracks/:id/peaks", (&waveformHandlers{svc: d.Waveform}).peaks) // Audio loaded by an