Registration, login and the admin's create-user call take `email` instead of `username`, and the user object returns `email`. The address is checked for its shape (a plain address, no display name, at most 254 bytes), trimmed, lowercased and unique. Sonda sends no mail and does not verify it. - Migration 0018 renames the users column (and the PostgreSQL index); values are kept, so an account made before keeps its plain name and still logs in with it (login does not check the shape). - Error code username_taken becomes email_taken; the JWT claim is now `email`, so access tokens issued before the upgrade are refused once and clients refresh. - OpenAPI spec, README, the web login form (type email), strings (en, it) and the generated API types follow. Closes #65
298 lines
11 KiB
Go
298 lines
11 KiB
Go
// Package httpapi is the first-party REST API (/api/v1).
|
|
//
|
|
// Handlers stay thin: they validate and serialize, then call services.
|
|
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
|
|
"codeberg.org/squidd/sonda/internal/about"
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
"codeberg.org/squidd/sonda/internal/catalog"
|
|
"codeberg.org/squidd/sonda/internal/discover"
|
|
"codeberg.org/squidd/sonda/internal/discovery"
|
|
"codeberg.org/squidd/sonda/internal/feedback"
|
|
"codeberg.org/squidd/sonda/internal/images"
|
|
"codeberg.org/squidd/sonda/internal/jobs"
|
|
"codeberg.org/squidd/sonda/internal/library"
|
|
"codeberg.org/squidd/sonda/internal/listening"
|
|
"codeberg.org/squidd/sonda/internal/providers"
|
|
"codeberg.org/squidd/sonda/internal/streaming"
|
|
"codeberg.org/squidd/sonda/internal/taste"
|
|
"codeberg.org/squidd/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)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
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 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 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 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)
|
|
Delete(ctx context.Context, id int64) error
|
|
}
|
|
|
|
// Deps are the services the API needs.
|
|
type Deps struct {
|
|
Logger *zap.Logger
|
|
Auth authService
|
|
Tokens tokenParser
|
|
Listening listenService
|
|
Scan scanService
|
|
Libraries libraryService
|
|
Catalog catalogService
|
|
Providers providerService
|
|
Lidarr lidarrOptionsService
|
|
LidarrArtists lidarrArtistService
|
|
Discovery discoveryService
|
|
Tags tagService
|
|
Taste tasteService
|
|
Discover discoverService
|
|
Feedback feedbackService
|
|
Images coverService
|
|
CoversJob jobService
|
|
ArtistImagesJob jobService
|
|
DescriptionsJob jobService
|
|
About aboutService
|
|
ArtistImages artistImageService
|
|
Settings userSettingsService
|
|
Streams streamService
|
|
}
|
|
|
|
// 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" {
|
|
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))
|
|
r.NoRoute(func(c *gin.Context) { writeError(c, http.StatusNotFound, "not_found", "no such route") })
|
|
|
|
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)
|
|
|
|
// Any signed-in user.
|
|
protected := v1.Group("", requireAuth(d.Tokens, d.Auth, false))
|
|
protected.GET("/auth/me", a.me)
|
|
protected.POST("/auth/password", a.changePassword)
|
|
l := &listenHandlers{svc: d.Listening}
|
|
protected.POST("/listens", l.record)
|
|
protected.GET("/listens", l.list)
|
|
|
|
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))
|
|
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)
|
|
|
|
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}
|
|
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)
|
|
|
|
// Audio loaded by an <audio> element cannot send headers, so this route also
|
|
// takes the access token as a query parameter. It never records a listen.
|
|
st := &streamHandlers{svc: d.Streams}
|
|
audio := v1.Group("", requireAuth(d.Tokens, d.Auth, true))
|
|
audio.GET("/tracks/:id/stream", st.stream)
|
|
audio.HEAD("/tracks/:id/stream", st.stream)
|
|
// An <img> element cannot send headers either, so covers take the token the same way.
|
|
cv := &coverHandlers{svc: d.Images}
|
|
audio.GET("/albums/:id/cover", cv.album)
|
|
audio.HEAD("/albums/:id/cover", cv.album)
|
|
ai := &artistImageHandlers{svc: d.ArtistImages}
|
|
audio.GET("/artists/:id/image", ai.image)
|
|
audio.HEAD("/artists/:id/image", ai.image)
|
|
|
|
// Admins only.
|
|
admin := protected.Group("", requireAdmin(d.Auth))
|
|
admin.POST("/library/scan", lib.startScan)
|
|
admin.POST("/library/covers", cj.start)
|
|
admin.DELETE("/library/covers", cj.stop)
|
|
admin.POST("/library/artist-images", aj.start)
|
|
admin.DELETE("/library/artist-images", aj.stop)
|
|
admin.POST("/library/descriptions", dj.start)
|
|
admin.DELETE("/library/descriptions", dj.stop)
|
|
libs := &librariesHandlers{svc: d.Libraries}
|
|
admin.GET("/libraries", libs.list)
|
|
admin.POST("/libraries", libs.create)
|
|
admin.PATCH("/libraries/:id", libs.update)
|
|
admin.DELETE("/libraries/:id", libs.remove)
|
|
admin.POST("/libraries/:id/scan", lib.startLibraryScan)
|
|
prov := &providersHandlers{svc: d.Providers, lidarr: d.Lidarr}
|
|
admin.GET("/providers", prov.list)
|
|
admin.PUT("/providers/:name", prov.update)
|
|
admin.GET("/providers/lidarr/options", prov.lidarrOptions)
|
|
admin.POST("/artists/:id/lidarr", la.send)
|
|
admin.POST("/providers/:name/test", prov.test)
|
|
admin.DELETE("/providers/:name/data", prov.purge)
|
|
u := &usersHandlers{svc: d.Auth}
|
|
admin.GET("/users", u.list)
|
|
admin.POST("/users", u.create)
|
|
admin.PATCH("/users/:id", u.update)
|
|
admin.PUT("/users/:id/password", u.resetPassword)
|
|
admin.DELETE("/users/:id", u.remove)
|
|
|
|
return r
|
|
}
|
|
|
|
func health(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
}
|