ctrlsubsonic: move to new param package

This commit is contained in:
sentriz
2020-04-26 22:08:32 +01:00
committed by Senan Kelly
parent bf78ccfdfd
commit f4a1c3fb0c
4 changed files with 63 additions and 69 deletions

View File

@@ -97,12 +97,8 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
// getAlbumListTwo() function // getAlbumListTwo() function
func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response { func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
listType := params.Get("type")
if listType == "" {
return spec.NewError(10, "please provide a `type` parameter")
}
q := c.DB.DB q := c.DB.DB
switch listType { switch v, _ := params.Get("type"); v {
case "alphabeticalByArtist": case "alphabeticalByArtist":
q = q.Joins(` q = q.Joins(`
JOIN albums parent_albums JOIN albums parent_albums
@@ -129,7 +125,7 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
user.ID) user.ID)
q = q.Order("plays.time DESC") q = q.Order("plays.time DESC")
default: default:
return spec.NewError(10, "unknown value `%s` for parameter 'type'", listType) return spec.NewError(10, "unknown value `%s` for parameter 'type'", v)
} }
var folders []*db.Album var folders []*db.Album
// TODO: think about removing this extra join to count number // TODO: think about removing this extra join to count number
@@ -139,8 +135,8 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id"). Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Group("albums.id"). Group("albums.id").
Where("albums.tag_artist_id IS NOT NULL"). Where("albums.tag_artist_id IS NOT NULL").
Offset(params.GetIntOr("offset", 0)). Offset(params.GetOrInt("offset", 0)).
Limit(params.GetIntOr("size", 10)). Limit(params.GetOrInt("size", 10)).
Preload("Parent"). Preload("Parent").
Find(&folders) Find(&folders)
sub := spec.NewResponse() sub := spec.NewResponse()
@@ -155,8 +151,8 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response { func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
query := params.Get("query") query, err := params.Get("query")
if query == "" { if err != nil {
return spec.NewError(10, "please provide a `query` parameter") return spec.NewError(10, "please provide a `query` parameter")
} }
query = fmt.Sprintf("%%%s%%", strings.TrimSuffix(query, "*")) query = fmt.Sprintf("%%%s%%", strings.TrimSuffix(query, "*"))
@@ -169,8 +165,8 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
AND ( right_path LIKE ? OR AND ( right_path LIKE ? OR
right_path_u_dec LIKE ? )`, right_path_u_dec LIKE ? )`,
query, query). query, query).
Offset(params.GetIntOr("artistOffset", 0)). Offset(params.GetOrInt("artistOffset", 0)).
Limit(params.GetIntOr("artistCount", 20)). Limit(params.GetOrInt("artistCount", 20)).
Find(&artists) Find(&artists)
for _, a := range artists { for _, a := range artists {
results.Artists = append(results.Artists, results.Artists = append(results.Artists,
@@ -184,8 +180,8 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
AND ( right_path LIKE ? OR AND ( right_path LIKE ? OR
right_path_u_dec LIKE ? )`, right_path_u_dec LIKE ? )`,
query, query). query, query).
Offset(params.GetIntOr("albumOffset", 0)). Offset(params.GetOrInt("albumOffset", 0)).
Limit(params.GetIntOr("albumCount", 20)). Limit(params.GetOrInt("albumCount", 20)).
Find(&albums) Find(&albums)
for _, a := range albums { for _, a := range albums {
results.Albums = append(results.Albums, spec.NewTCAlbumByFolder(a)) results.Albums = append(results.Albums, spec.NewTCAlbumByFolder(a))
@@ -196,8 +192,8 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
Preload("Album"). Preload("Album").
Where("filename LIKE ? OR filename_u_dec LIKE ?", Where("filename LIKE ? OR filename_u_dec LIKE ?",
query, query). query, query).
Offset(params.GetIntOr("songOffset", 0)). Offset(params.GetOrInt("songOffset", 0)).
Limit(params.GetIntOr("songCount", 20)). Limit(params.GetOrInt("songCount", 20)).
Find(&tracks) Find(&tracks)
for _, t := range tracks { for _, t := range tracks {
results.Tracks = append(results.Tracks, results.Tracks = append(results.Tracks,

View File

@@ -97,8 +97,8 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
// getAlbumList() function // getAlbumList() function
func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response { func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
listType := params.Get("type") listType, err := params.Get("type")
if listType == "" { if err != nil {
return spec.NewError(10, "please provide a `type` parameter") return spec.NewError(10, "please provide a `type` parameter")
} }
q := c.DB.DB q := c.DB.DB
@@ -111,8 +111,8 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
case "byYear": case "byYear":
q = q.Where( q = q.Where(
"tag_year BETWEEN ? AND ?", "tag_year BETWEEN ? AND ?",
params.GetIntOr("fromYear", 1800), params.GetOrInt("fromYear", 1800),
params.GetIntOr("toYear", 2200)) params.GetOrInt("toYear", 2200))
q = q.Order("tag_year") q = q.Order("tag_year")
case "byGenre": case "byGenre":
q = q.Joins("JOIN genres ON albums.tag_genre_id=genres.id AND genres.name=?", q = q.Joins("JOIN genres ON albums.tag_genre_id=genres.id AND genres.name=?",
@@ -142,8 +142,8 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id"). Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Group("albums.id"). Group("albums.id").
Where("albums.tag_artist_id IS NOT NULL"). Where("albums.tag_artist_id IS NOT NULL").
Offset(params.GetIntOr("offset", 0)). Offset(params.GetOrInt("offset", 0)).
Limit(params.GetIntOr("size", 10)). Limit(params.GetOrInt("size", 10)).
Preload("TagArtist"). Preload("TagArtist").
Find(&albums) Find(&albums)
sub := spec.NewResponse() sub := spec.NewResponse()
@@ -158,8 +158,8 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response { func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
query := params.Get("query") query, err := params.Get("query")
if query == "" { if err != nil {
return spec.NewError(10, "please provide a `query` parameter") return spec.NewError(10, "please provide a `query` parameter")
} }
query = fmt.Sprintf("%%%s%%", query = fmt.Sprintf("%%%s%%",
@@ -170,8 +170,8 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
c.DB. c.DB.
Where("name LIKE ? OR name_u_dec LIKE ?", Where("name LIKE ? OR name_u_dec LIKE ?",
query, query). query, query).
Offset(params.GetIntOr("artistOffset", 0)). Offset(params.GetOrInt("artistOffset", 0)).
Limit(params.GetIntOr("artistCount", 20)). Limit(params.GetOrInt("artistCount", 20)).
Find(&artists) Find(&artists)
for _, a := range artists { for _, a := range artists {
results.Artists = append(results.Artists, results.Artists = append(results.Artists,
@@ -183,8 +183,8 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
Preload("TagArtist"). Preload("TagArtist").
Where("tag_title LIKE ? OR tag_title_u_dec LIKE ?", Where("tag_title LIKE ? OR tag_title_u_dec LIKE ?",
query, query). query, query).
Offset(params.GetIntOr("albumOffset", 0)). Offset(params.GetOrInt("albumOffset", 0)).
Limit(params.GetIntOr("albumCount", 20)). Limit(params.GetOrInt("albumCount", 20)).
Find(&albums) Find(&albums)
for _, a := range albums { for _, a := range albums {
results.Albums = append(results.Albums, results.Albums = append(results.Albums,
@@ -196,8 +196,8 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
Preload("Album"). Preload("Album").
Where("tag_title LIKE ? OR tag_title_u_dec LIKE ?", Where("tag_title LIKE ? OR tag_title_u_dec LIKE ?",
query, query). query, query).
Offset(params.GetIntOr("songOffset", 0)). Offset(params.GetOrInt("songOffset", 0)).
Limit(params.GetIntOr("songCount", 20)). Limit(params.GetOrInt("songCount", 20)).
Find(&tracks) Find(&tracks)
for _, t := range tracks { for _, t := range tracks {
results.Tracks = append(results.Tracks, results.Tracks = append(results.Tracks,
@@ -210,7 +210,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response { func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetInt("id") id, err := params.GetIDDefault()
if err != nil { if err != nil {
return spec.NewError(10, "please provide an `id` parameter") return spec.NewError(10, "please provide an `id` parameter")
} }
@@ -246,8 +246,8 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
sub.ArtistInfoTwo.LargeImageURL = image.Text sub.ArtistInfoTwo.LargeImageURL = image.Text
} }
} }
count := params.GetIntOr("count", 20) count := params.GetOrInt("count", 20)
includeNotPresent := params.Get("includeNotPresent") == "true" inclNotPresent := params.GetOrBool("includeNotPresent", false)
for i, similarInfo := range info.Similar.Artists { for i, similarInfo := range info.Similar.Artists {
if i == count { if i == count {
break break
@@ -260,7 +260,7 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
Group("artists.id"). Group("artists.id").
Find(artist). Find(artist).
Error Error
if gorm.IsRecordNotFoundError(err) && !includeNotPresent { if gorm.IsRecordNotFoundError(err) && !inclNotPresent {
continue continue
} }
similar := &spec.SimilarArtist{ID: -1} similar := &spec.SimilarArtist{ID: -1}
@@ -295,8 +295,8 @@ func (c *Controller) ServeGetGenres(r *http.Request) *spec.Response {
func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response { func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
genre := params.Get("genre") genre, err := params.Get("genre")
if genre == "" { if err != nil {
return spec.NewError(10, "please provide an `genre` parameter") return spec.NewError(10, "please provide an `genre` parameter")
} }
// TODO: add musicFolderId parameter // TODO: add musicFolderId parameter
@@ -306,8 +306,8 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
Joins("JOIN albums ON tracks.album_id=albums.id"). Joins("JOIN albums ON tracks.album_id=albums.id").
Joins("JOIN genres ON tracks.tag_genre_id=genres.id AND genres.name=?", genre). Joins("JOIN genres ON tracks.tag_genre_id=genres.id AND genres.name=?", genre).
Preload("Album"). Preload("Album").
Offset(params.GetIntOr("offset", 0)). Offset(params.GetOrInt("offset", 0)).
Limit(params.GetIntOr("count", 10)). Limit(params.GetOrInt("count", 10)).
Find(&tracks) Find(&tracks)
sub := spec.NewResponse() sub := spec.NewResponse()
sub.TracksByGenre = &spec.TracksByGenre{ sub.TracksByGenre = &spec.TracksByGenre{

View File

@@ -4,7 +4,6 @@ import (
"log" "log"
"net/http" "net/http"
"sort" "sort"
"strconv"
"time" "time"
"unicode" "unicode"
@@ -59,8 +58,8 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
Track: track, Track: track,
// clients will provide time in miliseconds, so use that or // clients will provide time in miliseconds, so use that or
// instead convert UnixNano to miliseconds // instead convert UnixNano to miliseconds
StampMili: params.GetIntOr("time", int(time.Now().UnixNano()/1e6)), StampMili: params.GetOrInt("time", int(time.Now().UnixNano()/1e6)),
Submission: params.GetOr("submission", "true") != "false", Submission: params.GetOrBool("submission", true),
} }
err = lastfm.Scrobble( err = lastfm.Scrobble(
c.DB.GetSetting("lastfm_api_key"), c.DB.GetSetting("lastfm_api_key"),
@@ -179,10 +178,7 @@ func (c *Controller) ServeGetPlaylist(r *http.Request) *spec.Response {
func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response { func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User) user := r.Context().Value(CtxUser).(*db.User)
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
var playlistID int playlistID := params.GetFirstOrInt( /* default */ 0, "id", "playlistId")
if p := params.GetFirstList("id", "playlistId"); p != nil {
playlistID, _ = strconv.Atoi(p[0])
}
// playlistID may be 0 from above. in that case we get a new playlist // playlistID may be 0 from above. in that case we get a new playlist
// as intended // as intended
var playlist db.Playlist var playlist db.Playlist
@@ -191,22 +187,22 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
FirstOrCreate(&playlist) FirstOrCreate(&playlist)
// ** begin update meta info // ** begin update meta info
playlist.UserID = user.ID playlist.UserID = user.ID
if val := params.Get("name"); val != "" { if val, err := params.Get("name"); err != nil {
playlist.Name = val playlist.Name = val
} }
if val := params.Get("comment"); val != "" { if val, err := params.Get("comment"); err != nil {
playlist.Comment = val playlist.Comment = val
} }
trackIDs := playlist.GetItems() trackIDs := playlist.GetItems()
// ** begin delete items // ** begin delete items
if p := params.GetFirstListInt("songIndexToRemove"); p != nil { if p, err := params.GetIntList("songIndexToRemove"); err == nil {
sort.Sort(sort.Reverse(sort.IntSlice(p))) sort.Sort(sort.Reverse(sort.IntSlice(p)))
for _, i := range p { for _, i := range p {
trackIDs = append(trackIDs[:i], trackIDs[i+1:]...) trackIDs = append(trackIDs[:i], trackIDs[i+1:]...)
} }
} }
// ** begin add items // ** begin add items
if p := params.GetFirstListInt("songId", "songIdToAdd"); p != nil { if p, err := params.GetFirstIntList("songId", "songIdToAdd"); err == nil {
trackIDs = append(trackIDs, p...) trackIDs = append(trackIDs, p...)
} }
// //
@@ -218,7 +214,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response { func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
c.DB. c.DB.
Where("id=?", params.GetIntOr("id", 0)). Where("id=?", params.GetOrInt("id", 0)).
Delete(&db.Playlist{}) Delete(&db.Playlist{})
return spec.NewResponse() return spec.NewResponse()
} }
@@ -255,16 +251,16 @@ func (c *Controller) ServeGetPlayQueue(r *http.Request) *spec.Response {
func (c *Controller) ServeSavePlayQueue(r *http.Request) *spec.Response { func (c *Controller) ServeSavePlayQueue(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
tracks := params.GetFirstListInt("id") tracks, err := params.GetIntList("id")
if tracks == nil { if err != nil {
return spec.NewError(10, "please provide some `id` parameters") return spec.NewError(10, "please provide some `id` parameters")
} }
user := r.Context().Value(CtxUser).(*db.User) user := r.Context().Value(CtxUser).(*db.User)
queue := &db.PlayQueue{UserID: user.ID} queue := &db.PlayQueue{UserID: user.ID}
c.DB.Where(queue).First(queue) c.DB.Where(queue).First(queue)
queue.Current = params.GetIntOr("current", 0) queue.Current = params.GetOrInt("current", 0)
queue.Position = params.GetIntOr("position", 0) queue.Position = params.GetOrInt("position", 0)
queue.ChangedBy = params.Get("c") queue.ChangedBy = params.GetOr("c", "") // must exist, middleware checks
queue.SetItems(tracks) queue.SetItems(tracks)
c.DB.Save(queue) c.DB.Save(queue)
return spec.NewResponse() return spec.NewResponse()
@@ -295,7 +291,7 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
var tracks []*db.Track var tracks []*db.Track
q := c.DB.DB. q := c.DB.DB.
Joins("JOIN albums ON tracks.album_id=albums.id"). Joins("JOIN albums ON tracks.album_id=albums.id").
Limit(params.GetIntOr("size", 10)). Limit(params.GetOrInt("size", 10)).
Preload("Album"). Preload("Album").
Order(gorm.Expr("random()")) Order(gorm.Expr("random()"))
if year, err := params.GetInt("fromYear"); err == nil { if year, err := params.GetInt("fromYear"); err == nil {
@@ -304,7 +300,7 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
if year, err := params.GetInt("toYear"); err == nil { if year, err := params.GetInt("toYear"); err == nil {
q = q.Where("albums.tag_year <= ?", year) q = q.Where("albums.tag_year <= ?", year)
} }
if genre := params.Get("genre"); genre != "" { if genre, err := params.Get("genre"); err == nil {
q = q.Joins( q = q.Joins(
"JOIN genres ON tracks.tag_genre_id=genres.id AND genres.name=?", "JOIN genres ON tracks.tag_genre_id=genres.id AND genres.name=?",
genre, genre,
@@ -324,7 +320,10 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
getTracks := func() []*db.Track { getTracks := func() []*db.Track {
var tracks []*db.Track var tracks []*db.Track
ids := params.GetFirstListInt("id") ids, err := params.GetIDList("id")
if err != nil {
return tracks
}
for _, id := range ids { for _, id := range ids {
track := &db.Track{} track := &db.Track{}
c.DB.Preload("Album").First(track, id) c.DB.Preload("Album").First(track, id)
@@ -351,7 +350,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response {
} }
return ret return ret
} }
switch act := params.Get("action"); act { switch act, _ := params.Get("action"); act {
case "set": case "set":
c.Jukebox.SetTracks(getTracks()) c.Jukebox.SetTracks(getTracks())
case "add": case "add":

View File

@@ -41,13 +41,11 @@ func (c *Controller) WithRequiredParams(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
for _, req := range requiredParameters { for _, req := range requiredParameters {
param := params.Get(req) if _, err := params.Get(req); err != nil {
if param != "" { _ = writeResp(w, r, spec.NewError(10,
continue "please provide a `%s` parameter", req))
return
} }
_ = writeResp(w, r, spec.NewError(10,
"please provide a `%s` parameter", req))
return
} }
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
@@ -56,10 +54,11 @@ func (c *Controller) WithRequiredParams(next http.Handler) http.Handler {
func (c *Controller) WithUser(next http.Handler) http.Handler { func (c *Controller) WithUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
username := params.Get("u") // ignoring errors here, a middleware has already ensured they exist
password := params.Get("p") username, _ := params.Get("u")
token := params.Get("t") password, _ := params.Get("p")
salt := params.Get("s") token, _ := params.Get("t")
salt, _ := params.Get("s")
// //
passwordAuth := token == "" && salt == "" passwordAuth := token == "" && salt == ""
tokenAuth := password == "" tokenAuth := password == ""