- feat: GET /api/v1/artists/{id}/similar lists the artists Last.fm finds similar
to one in the library, best first, each with the provider's own score and
rank and a flag saying whether it is in the library. It answers 200 when the
provider is off or failing, with provider_status, stale and retrieved_at
- feat: a thin Last.fm client on top of the outbound client. It always sends
autocorrect=0 so a misspelled local name cannot turn into another artist,
prefers the MusicBrainz id when known, always sets a limit, and reads the
error field even when the status is 200. Errors never carry the URL or the
provider's own message, because the key travels in the query string
- feat: results are stored in artist_similar with a freshness ledger in
provider_fetches: 7 days for an answer, 1 day for "unknown artist". Old data
is served when the provider fails, and concurrent requests for the same
artist share one call that does not depend on the first caller staying
- feat: artists named by a provider but without files become artists without
tracks. GET /artists/{id} can show them (track_count 0), the lists of the
library never include them, and a later scan adopts them by name. A provider
id is never written onto an existing artist; names match only when at least
one side has no id, and different ids always mean different artists
- feat: POST /providers/{name}/test (admin) checks a stored key with one cheap
request, whether the provider is on or off, and reports ok, no_api_key,
key_refused, rate_limited, unreachable or error
- test: the whole request is checked from the receiving end, with a user, a
listen, a title and a library path in the database: only the artist and the
key leave, with a User-Agent that names the project
- docs: README and OpenAPI updated; the contract test calls the new operations
168 lines
5.8 KiB
Go
168 lines
5.8 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"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
"codeberg.org/squidd/sonda/internal/catalog"
|
|
"codeberg.org/squidd/sonda/internal/discovery"
|
|
"codeberg.org/squidd/sonda/internal/library"
|
|
"codeberg.org/squidd/sonda/internal/listening"
|
|
"codeberg.org/squidd/sonda/internal/providers"
|
|
"codeberg.org/squidd/sonda/internal/streaming"
|
|
)
|
|
|
|
// maxBodyBytes bounds every request body.
|
|
const maxBodyBytes = 64 << 10
|
|
|
|
type authService interface {
|
|
Register(ctx context.Context, username, password string) (auth.User, error)
|
|
Login(ctx context.Context, username, 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, username, 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() error
|
|
StartLibrary(id int64) 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)
|
|
}
|
|
|
|
type discoveryService interface {
|
|
Similar(ctx context.Context, artistID int64, limit int) (discovery.Result, 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
|
|
Discovery discoveryService
|
|
Streams streamService
|
|
}
|
|
|
|
// NewRouter builds the gin engine with all routes.
|
|
func NewRouter(d Deps) *gin.Engine {
|
|
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, 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)
|
|
|
|
lib := &libraryHandlers{scan: d.Scan}
|
|
protected.GET("/library/scan", lib.scanStatus)
|
|
|
|
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)
|
|
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, true))
|
|
audio.GET("/tracks/:id/stream", st.stream)
|
|
audio.HEAD("/tracks/:id/stream", st.stream)
|
|
|
|
// Admins only.
|
|
admin := protected.Group("", requireAdmin(d.Auth))
|
|
admin.POST("/library/scan", lib.startScan)
|
|
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}
|
|
admin.GET("/providers", prov.list)
|
|
admin.PUT("/providers/:name", prov.update)
|
|
admin.POST("/providers/:name/test", prov.test)
|
|
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"})
|
|
}
|