2026-11-01 21:50:47 +01:00
package media
2026-10-19 21:14:31 +00:00
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// The tests in this file run the media routes against a real PostgreSQL database and a stand-in
// CarrierNode. They create the media tables and a few rows, so they are skipped unless
// SHARED_TEST_DATABASE_URL points at a scratch database, for example:
//
2026-11-01 21:50:47 +01:00
// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./media/
2026-10-19 21:14:31 +00:00
const (
aliceID = 9101
bobID = 9102
modID = 9103
)
// newIdentityAuthGuard answers GET /api/me for three fixed sessions: two ordinary users and a moderator.
func newIdentityAuthGuard ( t * testing . T ) * httptest . Server {
t . Helper ()
people := map [ string ] struct {
id int64
role string
}{ "alice-token" : { aliceID , "user" }, "bob-token" : { bobID , "user" }, "mod-token" : { modID , "moderator" }}
server := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
person , ok := people [ strings . TrimPrefix ( r . Header . Get ( "Authorization" ), "Bearer " )]
if ! ok || r . URL . Path != "/api/me" {
w . WriteHeader ( http . StatusUnauthorized )
return
}
w . Header (). Set ( "Content-Type" , "application/json" )
fmt . Fprintf ( w , `{"user":{"id":%d,"username":"u%d","role":%q}}` , person . id , person . id , person . role )
}))
t . Cleanup ( server . Close )
return server
}
// stubCarrierNode serves a body for every /media/ path and 404s the rest, recording what it was asked.
type stubCarrierNode struct {
mu sync . Mutex
requests [] string
}
func ( n * stubCarrierNode ) ServeHTTP ( w http . ResponseWriter , r * http . Request ) {
n . mu . Lock ()
n . requests = append ( n . requests , r . Method + " " + r . URL . EscapedPath ())
n . mu . Unlock ()
if ! strings . HasPrefix ( r . URL . Path , "/media/" ) {
http . NotFound ( w , r )
return
}
w . Header (). Set ( "Content-Type" , "application/octet-stream" )
if r . Method != http . MethodHead {
_ , _ = io . WriteString ( w , "BYTES" )
}
}
func ( n * stubCarrierNode ) seen () [] string {
n . mu . Lock ()
defer n . mu . Unlock ()
return append ([] string ( nil ), n . requests ... )
}
type dbHarness struct {
pool * pgxpool . Pool
router chi . Router
carrier * stubCarrierNode
hub * syncsocket . Hub
}
func newDBHarness ( t * testing . T ) * dbHarness {
t . Helper ()
url := os . Getenv ( "SHARED_TEST_DATABASE_URL" )
if url == "" {
t . Skip ( "SHARED_TEST_DATABASE_URL not set; skipping Postgres route tests" )
}
ctx := context . Background ()
pool , err := postgres . Open ( ctx , postgres . DefaultConfig ( url ))
if err != nil {
t . Fatalf ( "open pool: %v" , err )
}
t . Cleanup ( pool . Close )
carrier := & stubCarrierNode {}
carrierServer := httptest . NewServer ( carrier )
t . Cleanup ( carrierServer . Close )
guard := newIdentityAuthGuard ( t )
auth := sharedauth . NewWithStore ( loginRequiredStore {}, "session" , false , guard . URL , "testproject" )
hub := syncsocket . NewHub ()
core := New ( Config {
DB : pool ,
Auth : auth ,
CarrierNode : carriernodeclient . New ( "" , func ( context . Context ) string { return carrierServer . URL }),
ServiceName : "routes-test" ,
})
if err := core . Migrate ( ctx ); err != nil {
t . Fatalf ( "Migrate() error = %v" , err )
}
cleanup := func () {
for _ , statement := range [] string {
`DELETE FROM playlists WHERE user_id IN (9101, 9102, 9103)` ,
`DELETE FROM media_stats WHERE media_key LIKE 'rt-%' OR user_id IN (9101, 9102, 9103)` ,
`DELETE FROM media_view_sessions WHERE media_key LIKE 'rt-%'` ,
`DELETE FROM media_tag_votes WHERE media_key LIKE 'rt-%'` ,
`DELETE FROM media_tags WHERE media_key LIKE 'rt-%'` ,
`DELETE FROM media WHERE media_key LIKE 'rt-%'` ,
`DELETE FROM users WHERE id IN (9101, 9102, 9103)` ,
} {
if _ , err := pool . Exec ( ctx , statement ); err != nil {
t . Fatalf ( "cleanup %q: %v" , statement , err )
}
}
}
cleanup ()
t . Cleanup ( cleanup )
for _ , id := range [] int64 { aliceID , bobID , modID } {
if _ , err := pool . Exec ( ctx , `INSERT INTO users (id, email, username, password_hash) VALUES ($1, $2, $3, 'x')` , id , fmt . Sprintf ( "rt%d@example.com" , id ), fmt . Sprintf ( "rt%d" , id )); err != nil {
t . Fatalf ( "insert user: %v" , err )
}
}
router := chi . NewRouter ()
core . Mount ( router )
return & dbHarness { pool : pool , router : router , carrier : carrier , hub : hub }
}
func ( h * dbHarness ) insertMedia ( t * testing . T , key , mediaType , filePath string , active bool ) {
t . Helper ()
if _ , err := h . pool . Exec ( context . Background (), `INSERT INTO media (media_key, media_type, file_path, active) VALUES ($1, $2, $3, $4)` , key , mediaType , filePath , active ); err != nil {
t . Fatalf ( "insert media %s: %v" , key , err )
}
}
func ( h * dbHarness ) do ( method , target , token , body string ) * httptest . ResponseRecorder {
var reader io . Reader
if body != "" {
reader = strings . NewReader ( body )
}
request := httptest . NewRequest ( method , target , reader )
if token != "" {
request . AddCookie ( & http . Cookie { Name : "auth_session" , Value : token })
}
response := httptest . NewRecorder ()
h . router . ServeHTTP ( response , request )
return response
}
func decode ( t * testing . T , response * httptest . ResponseRecorder ) map [ string ] any {
t . Helper ()
var out map [ string ] any
if err := json . Unmarshal ( response . Body . Bytes (), & out ); err != nil {
t . Fatalf ( "body %q is not JSON: %v" , response . Body . String (), err )
}
return out
}
func dataOf ( t * testing . T , response * httptest . ResponseRecorder ) map [ string ] any {
t . Helper ()
data , _ := decode ( t , response )[ "data" ].( map [ string ] any )
if data == nil {
t . Fatalf ( "response %s has no data object" , response . Body . String ())
}
return data
}
func TestMediaStreamAndThumbnailAgainstPostgres ( t * testing . T ) {
h := newDBHarness ( t )
h . insertMedia ( t , "rt-visible" , "video" , "folder/clip one.mp4" , true )
h . insertMedia ( t , "rt-hidden" , "video" , "secret.mp4" , false )
h . insertMedia ( t , "rt-image" , "image" , "pics/photo.jpg" , true )
h . insertMedia ( t , "rt-escape" , "video" , "../etc/passwd" , true )
h . insertMedia ( t , "rt-query" , "video" , "a?b.mp4" , true )
var visibleID int64
if err := h . pool . QueryRow ( context . Background (), `SELECT id FROM media WHERE media_key='rt-visible'` ). Scan ( & visibleID ); err != nil {
t . Fatal ( err )
}
t . Run ( "an anonymous caller is refused while login is required" , func ( t * testing . T ) {
if code := h . do ( http . MethodGet , "/media/stream?mediaKey=rt-visible" , "" , "" ). Code ; code != http . StatusUnauthorized {
t . Fatalf ( "status = %d, want 401" , code )
}
})
t . Run ( "a stored path reaches CarrierNode escaped, by key or by id, for GET and HEAD" , func ( t * testing . T ) {
for _ , target := range [] string { "/media/stream?mediaKey=rt-visible" , fmt . Sprintf ( "/media/stream?id=%d" , visibleID )} {
response := h . do ( http . MethodGet , target , "alice-token" , "" )
if response . Code != http . StatusOK || response . Body . String () != "BYTES" {
t . Fatalf ( "GET %s = %d %q, want the proxied bytes" , target , response . Code , response . Body . String ())
}
}
if response := h . do ( http . MethodHead , "/media/stream?mediaKey=rt-visible" , "alice-token" , "" ); response . Code != http . StatusOK || response . Body . Len () != 0 {
t . Fatalf ( "HEAD = %d with %d body bytes, want 200 and none" , response . Code , response . Body . Len ())
}
for _ , request := range h . carrier . seen () {
if request != "GET /media/folder/clip%20one.mp4" && request != "HEAD /media/folder/clip%20one.mp4" {
t . Fatalf ( "CarrierNode saw %q, want the escaped stored path" , request )
}
}
})
t . Run ( "unsafe stored paths and unknown keys are not found, and never reach CarrierNode" , func ( t * testing . T ) {
before := len ( h . carrier . seen ())
for _ , key := range [] string { "rt-escape" , "rt-query" , "rt-missing" , "" } {
if code := h . do ( http . MethodGet , "/media/stream?mediaKey=" + key , "alice-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "stream of %q status = %d, want 404" , key , code )
}
}
if got := len ( h . carrier . seen ()); got != before {
t . Fatalf ( "CarrierNode got %d extra requests, want none" , got - before )
}
})
t . Run ( "hidden media is visible to moderators only" , func ( t * testing . T ) {
for _ , target := range [] string { "/media/stream?mediaKey=rt-hidden" , "/media/thumb?mediaKey=rt-hidden" } {
if code := h . do ( http . MethodGet , target , "alice-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "viewer GET %s = %d, want 404" , target , code )
}
}
if response := h . do ( http . MethodGet , "/media/stream?mediaKey=rt-hidden" , "mod-token" , "" ); response . Code != http . StatusOK {
t . Errorf ( "moderator stream of hidden media = %d, want 200" , response . Code )
}
})
t . Run ( "a thumbnail falls back to the original image, and only for images" , func ( t * testing . T ) {
response := h . do ( http . MethodGet , "/media/thumb?mediaKey=rt-image" , "alice-token" , "" )
if response . Code != http . StatusOK || response . Body . String () != "BYTES" {
t . Fatalf ( "image thumbnail = %d %q, want the original image" , response . Code , response . Body . String ())
}
if code := h . do ( http . MethodGet , "/media/thumb?mediaKey=rt-visible" , "alice-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "video without a thumbnail = %d, want 404" , code )
}
if code := h . do ( http . MethodGet , "/media/thumb?mediaKey=../x" , "alice-token" , "" ). Code ; code != http . StatusBadRequest {
t . Errorf ( "unsafe thumbnail id = %d, want 400" , code )
}
})
}
func TestMediaStatsAndViewsAgainstPostgres ( t * testing . T ) {
h := newDBHarness ( t )
2026-10-20 19:32:45 +00:00
h . insertMedia ( t , "rt-stats" , "video" , "rt-stats.mp4" , true )
2026-10-19 21:14:31 +00:00
state := func ( token string ) map [ string ] any {
return dataOf ( t , h . do ( http . MethodGet , "/media/state?mediaKey=rt-stats" , token , "" ))
}
if code := h . do ( http . MethodGet , "/media/state" , "" , "" ). Code ; code != http . StatusBadRequest {
t . Fatalf ( "state without a key = %d, want 400" , code )
}
for _ , body := range [] string { `{}` , `{"mediaKey":"rt-stats","bogus":1}` , `nope` } {
if code := h . do ( http . MethodPost , "/media/like" , "alice-token" , body ). Code ; code != http . StatusBadRequest {
t . Errorf ( "like with %q = %d, want 400" , body , code )
}
}
h . do ( http . MethodPost , "/media/like" , "alice-token" , `{"mediaKey":"rt-stats"}` )
h . do ( http . MethodPost , "/media/like" , "alice-token" , `{"mediaKey":"rt-stats"}` ) // a repeat is not a second like
h . do ( http . MethodPost , "/media/like" , "bob-token" , `{"mediaKey":"rt-stats","like":true}` )
h . do ( http . MethodPost , "/media/save" , "alice-token" , `{"mediaKey":"rt-stats"}` )
if got := state ( "alice-token" ); got [ "likeCount" ] != float64 ( 2 ) || got [ "saveCount" ] != float64 ( 1 ) || got [ "likedByUser" ] != true || got [ "savedByUser" ] != true {
t . Fatalf ( "state for alice = %v" , got )
}
if got := state ( "bob-token" ); got [ "likedByUser" ] != true || got [ "savedByUser" ] != false {
t . Fatalf ( "state for bob = %v" , got )
}
if response := h . do ( http . MethodPost , "/media/like" , "alice-token" , `{"mediaKey":"rt-stats","like":false}` ); dataOf ( t , response )[ "enabled" ] != false {
t . Fatalf ( "unlike = %s" , response . Body . String ())
}
if got := state ( "alice-token" ); got [ "likeCount" ] != float64 ( 1 ) || got [ "likedByUser" ] != false {
t . Fatalf ( "state after unliking = %v" , got )
}
h . do ( http . MethodPost , "/media/like" , "bob-token" , `{"mediaKey":"rt-stats","value":false}` )
if got := state ( "" ); got [ "likeCount" ] != float64 ( 0 ) {
t . Fatalf ( "anonymous state after both unlikes = %v" , got )
}
h . do ( http . MethodPost , "/media/like" , "alice-token" , `{"mediaKey":"rt-liked"}` )
liked := decode ( t , h . do ( http . MethodGet , "/media/liked" , "alice-token" , "" ))[ "items" ].([] any )
if len ( liked ) != 1 || liked [ 0 ].( map [ string ] any )[ "mediaKey" ] != "rt-liked" {
t . Fatalf ( "liked = %v, want only rt-liked" , liked )
}
// Views and watch sessions can be recorded without logging in.
if code := h . do ( http . MethodPost , "/media/view?mediaKey=rt-stats" , "" , "" ). Code ; code != http . StatusOK {
t . Fatalf ( "anonymous view = %d, want 200" , code )
}
if code := h . do ( http . MethodPost , "/media/view" , "" , "" ). Code ; code != http . StatusBadRequest {
t . Fatalf ( "view without a key = %d, want 400" , code )
}
if code := h . do ( http . MethodPost , "/media/view-session" , "" , `{"mediaKey":"rt-stats","durationMs":1500}` ). Code ; code != http . StatusOK {
t . Fatalf ( "view session = %d, want 200" , code )
}
for _ , body := range [] string { `{"mediaKey":"rt-stats"}` , `{"mediaKey":"rt-stats","durationMs":-3}` , `{"durationMs":10}` } {
if code := h . do ( http . MethodPost , "/media/view-session" , "" , body ). Code ; code != http . StatusBadRequest {
t . Errorf ( "view session %q = %d, want 400" , body , code )
}
}
if got := state ( "" ); got [ "viewCount" ] != float64 ( 1 ) {
t . Fatalf ( "view count = %v, want 1" , got [ "viewCount" ])
}
}
func TestTagsAgainstPostgres ( t * testing . T ) {
h := newDBHarness ( t )
for _ , body := range [] string { `{}` , `{"tag":" "}` , `{"tag":"` + strings . Repeat ( "x" , 81 ) + `"}` , `nope` } {
if code := h . do ( http . MethodPost , "/media/rt-tags/tags" , "alice-token" , body ). Code ; code != http . StatusBadRequest {
t . Errorf ( "add tag %q = %d, want 400" , body , code )
}
}
if code := h . do ( http . MethodPost , "/media/rt-tags/tags" , "alice-token" , `{"tag":"Funny"}` ). Code ; code != http . StatusCreated {
t . Fatalf ( "add tag = %d, want 201" , code )
}
h . do ( http . MethodPost , "/media/rt-tags/tags" , "alice-token" , `{"tag":"Funny"}` ) // the same user's repeat is ignored
h . do ( http . MethodPost , "/media/rt-tags/tags" , "bob-token" , `{"tag":"Quiet"}` )
for _ , vote := range [] string { "2" , "-2" , "\"up\"" } {
if code := h . do ( http . MethodPost , "/media/rt-tags/tags/Funny/vote" , "alice-token" , `{"vote":` + vote + `}` ). Code ; code != http . StatusBadRequest {
t . Errorf ( "vote %s = %d, want 400" , vote , code )
}
}
h . do ( http . MethodPost , "/media/rt-tags/tags/Funny/vote" , "alice-token" , `{"vote":1}` )
h . do ( http . MethodPost , "/media/rt-tags/tags/Funny/vote" , "bob-token" , `{"vote":1}` )
h . do ( http . MethodPost , "/media/rt-tags/tags/Quiet/vote" , "alice-token" , `{"vote":-1}` )
h . do ( http . MethodPost , "/media/rt-tags/tags/Funny/vote" , "bob-token" , `{"vote":0}` ) // clears bob's vote
tags := decode ( t , h . do ( http . MethodGet , "/media/rt-tags/tags" , "" , "" ))[ "tags" ].([] any )
if len ( tags ) != 2 {
t . Fatalf ( "tags = %v, want Funny and Quiet" , tags )
}
first , second := tags [ 0 ].( map [ string ] any ), tags [ 1 ].( map [ string ] any )
if first [ "tag" ] != "Funny" || first [ "score" ] != float64 ( 1 ) || second [ "tag" ] != "Quiet" || second [ "score" ] != float64 ( - 1 ) {
t . Fatalf ( "tags = %v, want Funny at 1 ahead of Quiet at -1" , tags )
}
2026-11-01 21:50:47 +01:00
// A tag keeps its rows after its media is hidden or leaves the library. Only the library's
// media is listed for the tag, so a tag's examples never point at a thumbnail that is not found.
h . insertMedia ( t , "rt-tags" , "video" , "tagged/clip.mp4" , true )
h . insertMedia ( t , "rt-tags-hidden" , "video" , "tagged/hidden.mp4" , false )
h . insertMedia ( t , "rt-tags-new" , "video" , "tagged/new.mp4" , true )
if _ , err := h . pool . Exec ( context . Background (), `UPDATE media SET content_scanner_processed = TRUE WHERE media_key IN ('rt-tags', 'rt-tags-hidden')` ); err != nil {
t . Fatalf ( "mark media processed: %v" , err )
}
h . do ( http . MethodPost , "/media/rt-tags-hidden/tags" , "alice-token" , `{"tag":"Funny"}` )
h . do ( http . MethodPost , "/media/rt-tags-new/tags" , "alice-token" , `{"tag":"Funny"}` )
2026-10-19 21:14:31 +00:00
listed := decode ( t , h . do ( http . MethodGet , "/tags/funny/media?limit=10" , "" , "" ))[ "items" ].([] any )
if len ( listed ) != 1 || listed [ 0 ].( map [ string ] any )[ "mediaKey" ] != "rt-tags" {
2026-11-01 21:50:47 +01:00
t . Fatalf ( "media for the tag = %v, want only rt-tags (the hidden and unprocessed items are not listed)" , listed )
}
2026-11-13 21:20:50 +01:00
// Suggestions count the library's media, so Funny and Quiet count rt-tags only: the hidden and
// unprocessed items above are not in the library.
suggestions := decode ( t , h . do ( http . MethodGet , "/tags/suggestions?limit=5" , "" , "" ))[ "tags" ].([] any )
if len ( suggestions ) != 2 || suggestions [ 0 ].( map [ string ] any )[ "tag" ] != "Funny" || suggestions [ 0 ].( map [ string ] any )[ "count" ] != float64 ( 1 ) || suggestions [ 1 ].( map [ string ] any )[ "tag" ] != "Quiet" || suggestions [ 1 ].( map [ string ] any )[ "count" ] != float64 ( 1 ) {
t . Fatalf ( "suggestions = %v, want Funny and Quiet at 1 each" , suggestions )
}
// Without a limit, suggestions list every tag, not only the first 1000. The bulk tags sit on a
// library item, because a tag on media that is not in the library is not suggested.
if _ , err := h . pool . Exec ( context . Background (), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) VALUES ('rt-many', 'video', 'many/clip.mp4', TRUE, TRUE)` ); err != nil {
t . Fatalf ( "insert many media: %v" , err )
}
2026-11-01 21:50:47 +01:00
if _ , err := h . pool . Exec ( context . Background (), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-many', 'bulk ' || g, NULL FROM generate_series(1, 1001) AS g` ); err != nil {
t . Fatalf ( "insert many tags: %v" , err )
}
every := decode ( t , h . do ( http . MethodGet , "/tags/suggestions" , "" , "" ))[ "tags" ].([] any )
if len ( every ) <= 1000 {
t . Fatalf ( "suggestions without a limit = %d tags, want every tag (more than 1000)" , len ( every ))
}
// The tag's media is paged, and the pagination reports the whole count so the page can reach every page.
if _ , err := h . pool . Exec ( context . Background (), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) SELECT 'rt-page-' || g, 'video', 'paged/' || g || '.mp4', TRUE, TRUE FROM generate_series(1, 30) AS g` ); err != nil {
t . Fatalf ( "insert paged media: %v" , err )
}
if _ , err := h . pool . Exec ( context . Background (), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-page-' || g, 'Paged', NULL FROM generate_series(1, 30) AS g` ); err != nil {
t . Fatalf ( "tag paged media: %v" , err )
}
pageTwo := decode ( t , h . do ( http . MethodGet , "/tags/paged/media?page=2&limit=24" , "" , "" ))
pagination , _ := pageTwo [ "pagination" ].( map [ string ] any )
if items := pageTwo [ "items" ].([] any ); len ( items ) != 6 || pagination [ "total" ] != float64 ( 30 ) || pagination [ "totalPages" ] != float64 ( 2 ) || pagination [ "page" ] != float64 ( 2 ) {
t . Fatalf ( "page 2 at 24 per page = %d items, pagination %v; want 6 items on page 2 of 2, total 30" , len ( items ), pagination )
2026-10-19 21:14:31 +00:00
}
}
func TestPlaylistsAgainstPostgres ( t * testing . T ) {
h := newDBHarness ( t )
create := func ( token , name string ) * httptest . ResponseRecorder {
return h . do ( http . MethodPost , "/playlists" , token , `{"name":` + fmt . Sprintf ( "%q" , name ) + `}` )
}
for _ , name := range [] string { "" , " " , strings . Repeat ( "n" , 121 )} {
if code := create ( "alice-token" , name ). Code ; code != http . StatusBadRequest {
t . Errorf ( "create %q = %d, want 400" , name , code )
}
}
response := create ( "alice-token" , "Road trip" )
if response . Code != http . StatusCreated {
t . Fatalf ( "create = %d, body %s" , response . Code , response . Body . String ())
}
id := int64 ( dataOf ( t , response )[ "playlist" ].( map [ string ] any )[ "id" ].( float64 ))
if again := create ( "alice-token" , "Road trip" ); int64 ( dataOf ( t , again )[ "playlist" ].( map [ string ] any )[ "id" ].( float64 )) != id {
t . Fatal ( "creating the same name again made a second playlist" )
}
base := fmt . Sprintf ( "/playlists/%d" , id )
// Another user cannot see, change or delete it.
if code := h . do ( http . MethodGet , base , "bob-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "bob reading alice's playlist = %d, want 404" , code )
}
if code := h . do ( http . MethodPost , base + "/items" , "bob-token" , `{"mediaKey":"rt-a"}` ). Code ; code != http . StatusNotFound {
t . Errorf ( "bob adding to alice's playlist = %d, want 404" , code )
}
if code := h . do ( http . MethodDelete , base , "bob-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "bob deleting alice's playlist = %d, want 404" , code )
}
if code := h . do ( http . MethodGet , base + "/items" , "" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "anonymous items = %d, want 404" , code )
}
if code := h . do ( http . MethodPost , "/playlists/abc/items" , "alice-token" , `{"mediaKey":"rt-a"}` ). Code ; code != http . StatusBadRequest {
t . Errorf ( "bad playlist id = %d, want 400" , code )
}
for _ , key := range [] string { "rt-a" , "rt-b" , "rt-c" } {
if code := h . do ( http . MethodPost , base + "/items" , "alice-token" , `{"mediaKey":"` + key + `"}` ). Code ; code != http . StatusCreated {
t . Fatalf ( "add %s = %d, want 201" , key , code )
}
}
h . do ( http . MethodPost , base + "/items" , "alice-token" , `{"media_key":"rt-a"}` ) // a repeat is ignored
if code := h . do ( http . MethodPost , base + "/items" , "alice-token" , `{}` ). Code ; code != http . StatusBadRequest {
t . Errorf ( "add without a key = %d, want 400" , code )
}
keys := func () [] string {
var out [] string
for _ , item := range dataOf ( t , h . do ( http . MethodGet , base + "/items" , "alice-token" , "" ))[ "items" ].([] any ) {
out = append ( out , item .( map [ string ] any )[ "mediaKey" ].( string ))
}
return out
}
itemIDs := map [ string ] int64 {}
for _ , item := range dataOf ( t , h . do ( http . MethodGet , base + "/items" , "alice-token" , "" ))[ "items" ].([] any ) {
entry := item .( map [ string ] any )
itemIDs [ entry [ "mediaKey" ].( string )] = int64 ( entry [ "id" ].( float64 ))
}
if len ( itemIDs ) != 3 {
t . Fatalf ( "items = %v, want three distinct entries" , itemIDs )
}
reorder := fmt . Sprintf ( `{"ids":[%d,%d,%d]}` , itemIDs [ "rt-c" ], itemIDs [ "rt-a" ], itemIDs [ "rt-b" ])
if code := h . do ( http . MethodPatch , base + "/items/reorder" , "alice-token" , reorder ). Code ; code != http . StatusOK {
t . Fatalf ( "reorder = %d, want 200" , code )
}
if got := strings . Join ( keys (), "," ); got != "rt-c,rt-a,rt-b" {
t . Fatalf ( "order after reorder = %s, want rt-c,rt-a,rt-b" , got )
}
// The older field name still works, and another user's reorder changes nothing.
h . do ( http . MethodPatch , base + "/items/reorder" , "alice-token" , fmt . Sprintf ( `{"itemIds":[%d,%d,%d]}` , itemIDs [ "rt-b" ], itemIDs [ "rt-c" ], itemIDs [ "rt-a" ]))
if got := strings . Join ( keys (), "," ); got != "rt-b,rt-c,rt-a" {
t . Fatalf ( "order after itemIds reorder = %s, want rt-b,rt-c,rt-a" , got )
}
h . do ( http . MethodPatch , base + "/items/reorder" , "bob-token" , reorder )
if got := strings . Join ( keys (), "," ); got != "rt-b,rt-c,rt-a" {
t . Fatalf ( "bob's reorder changed alice's playlist to %s" , got )
}
tooMany := make ([] string , maxPlaylistReorderItems + 1 )
for i := range tooMany {
tooMany [ i ] = "1"
}
if code := h . do ( http . MethodPatch , base + "/items/reorder" , "alice-token" , `{"ids":[` + strings . Join ( tooMany , "," ) + `]}` ). Code ; code != http . StatusBadRequest {
t . Errorf ( "an oversized reorder = %d, want 400" , code )
}
random := dataOf ( t , h . do ( http . MethodGet , base + "/random" , "alice-token" , "" ))
if key , _ := random [ "mediaKey" ].( string ); key != "rt-a" && key != "rt-b" && key != "rt-c" {
t . Fatalf ( "random item = %v" , random )
}
if code := h . do ( http . MethodGet , base + "/random" , "bob-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "bob's random pick from alice's playlist = %d, want 404" , code )
}
summary := dataOf ( t , h . do ( http . MethodGet , "/playlists/summary" , "alice-token" , "" ))[ "playlists" ].([] any )
if len ( summary ) != 1 || summary [ 0 ].( map [ string ] any )[ "item_count" ] != float64 ( 3 ) {
t . Fatalf ( "summary = %v, want one playlist with three items" , summary )
}
if anonymous := dataOf ( t , h . do ( http . MethodGet , "/playlists/summary" , "" , "" ))[ "playlists" ].([] any ); len ( anonymous ) != 0 {
t . Fatalf ( "anonymous summary = %v, want none" , anonymous )
}
deleteBody := `{"mediaKey":"rt-a"}`
if code := h . do ( http . MethodDelete , base + "/items" , "bob-token" , deleteBody ). Code ; code != http . StatusNotFound {
t . Errorf ( "bob removing alice's item = %d, want 404" , code )
}
if code := h . do ( http . MethodDelete , base + "/items" , "alice-token" , deleteBody ). Code ; code != http . StatusOK {
t . Errorf ( "alice removing her item = %d, want 200" , code )
}
if code := h . do ( http . MethodDelete , base + "/items" , "alice-token" , deleteBody ). Code ; code != http . StatusNotFound {
t . Errorf ( "removing it twice = %d, want 404" , code )
}
if code := h . do ( http . MethodDelete , base , "alice-token" , "" ). Code ; code != http . StatusOK {
t . Errorf ( "deleting the playlist = %d, want 200" , code )
}
if code := h . do ( http . MethodGet , base , "alice-token" , "" ). Code ; code != http . StatusNotFound {
t . Errorf ( "the deleted playlist = %d, want 404" , code )
}
if listed := dataOf ( t , h . do ( http . MethodGet , "/playlists" , "alice-token" , "" ))[ "playlists" ].([] any ); len ( listed ) != 0 {
t . Fatalf ( "playlists after deleting = %v, want none" , listed )
}
}