Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions api/fixture_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,15 @@ var (
"created_at": time.Now(),
"updated_at": time.Now(),
},
"shares": {
"blockhash": "block_abc123",
"blocknumber": 101,
"share_item_id": nil,
"user_id": nil,
"share_type": nil,
"created_at": time.Now(),
"txhash": "tx123",
},
}
)

Expand Down
1 change: 1 addition & 0 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ func NewApiServer(config config.Config) *ApiServer {
g.Get("/tracks/inspect", app.v1TracksInspect)
g.Get("/tracks/feeling-lucky", app.v1TracksFeelingLucky)
g.Get("/tracks/recent-comments", app.v1TracksRecentComments)
g.Get("/tracks/most-shared", app.v1TracksMostShared)

g.Use("/tracks/:trackId", app.requireTrackIdMiddleware)
g.Get("/tracks/:trackId", app.v1Track)
Expand Down
51 changes: 51 additions & 0 deletions api/swagger/swagger-v1-full.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,57 @@ paths:
"400":
description: Bad request
content: {}
/tracks/most-shared:
get:
tags:
- tracks
description: Gets the most shared tracks for a given time range
operationId: Get Most Shared Tracks
parameters:
- name: user_id
in: query
description: The user ID of the user making the request
schema:
type: string
- name: limit
in: query
description: Number of tracks to fetch
schema:
type: integer
default: 10
minimum: 1
maximum: 100
- name: offset
in: query
description: The number of items to skip. Useful for pagination (page number
* limit)
schema:
type: integer
default: 0
minimum: 0
- name: time_range
in: query
description: The time range to consider
schema:
type: string
default: week
enum:
- week
- month
- allTime
responses:
"200":
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/full_tracks_response'
"400":
description: Bad request
content: {}
"500":
description: Server error
content: {}
/tracks/most_loved:
get:
tags:
Expand Down
51 changes: 51 additions & 0 deletions api/swagger/swagger-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,57 @@ paths:
"400":
description: Bad request
content: {}
/tracks/most-shared:
get:
tags:
- tracks
description: Gets the most shared tracks for a given time range
operationId: Get Most Shared Tracks
parameters:
- name: user_id
in: query
description: The user ID of the user making the request
schema:
type: string
- name: limit
in: query
description: Number of tracks to fetch
schema:
type: integer
default: 10
minimum: 1
maximum: 100
- name: offset
in: query
description: The number of items to skip. Useful for pagination (page number
* limit)
schema:
type: integer
default: 0
minimum: 0
- name: time_range
in: query
description: The time range to consider
schema:
type: string
default: week
enum:
- week
- month
- allTime
responses:
"200":
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/tracks_response'
"400":
description: Bad request
content: {}
"500":
description: Server error
content: {}
/tracks/search:
get:
tags:
Expand Down
80 changes: 80 additions & 0 deletions api/v1_tracks_most_shared.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package api

import (
"strings"

"bridgerton.audius.co/api/dbv1"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)

type GetTracksMostSharedParams struct {
Limit int `query:"limit" default:"10" validate:"min=1,max=100"`
Offset int `query:"offset" default:"0" validate:"min=0"`
TimeRange string `query:"time_range" default:"week" validate:"oneof=week month allTime"`
}

func (app *ApiServer) v1TracksMostShared(c *fiber.Ctx) error {
myId := app.getMyId(c)

var params = GetTracksMostSharedParams{}
if err := app.ParseAndValidateQueryParams(c, &params); err != nil {
return err
}

var shareFilters = []string{
"share_type = 'track'",
}
switch params.TimeRange {
case "week":
shareFilters = append(shareFilters, "created_at >= now() - interval '1 week'")
case "month":
shareFilters = append(shareFilters, "created_at >= now() - interval '1 month'")
}

sql := `
WITH most_shared AS (
SELECT share_item_id, count(*) as share_count
FROM shares
WHERE ` + strings.Join(shareFilters, " AND ") + `
GROUP BY share_item_id
ORDER BY share_count DESC
)
SELECT t.track_id
FROM most_shared ms
JOIN tracks t ON ms.share_item_id = t.track_id
WHERE
t.is_current = true AND
t.is_unlisted = false AND
t.is_available = true AND
t.is_delete = false
LIMIT @limit
OFFSET @offset;
`
args := pgx.NamedArgs{}
args["limit"] = params.Limit
args["offset"] = params.Offset

rows, err := app.pool.Query(c.Context(), sql, args)
if err != nil {
return err
}

trackIds, err := pgx.CollectRows(rows, pgx.RowTo[int32])
if err != nil {
return err
}

tracks, err := app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{
GetTracksParams: dbv1.GetTracksParams{
Ids: trackIds,
MyID: myId,
},
})

if err != nil {
return err
}

return v1TracksResponse(c, tracks)
}
132 changes: 132 additions & 0 deletions api/v1_tracks_most_shared_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package api

import (
"fmt"
"testing"
"time"

"bridgerton.audius.co/trashid"
"github.com/stretchr/testify/assert"
)

func TestV1TracksMostShared(t *testing.T) {
app := emptyTestApp(t)

users := []map[string]any{}
for i := range 5 {
userId := i + 1
users = append(users, map[string]any{
"user_id": userId,
"handle": fmt.Sprintf("user%d", userId),
})
}

tracks := []map[string]any{}
for i := range 5 {
trackId := i + 1
tracks = append(tracks, map[string]any{
"track_id": trackId,
"owner_id": trackId % 5,
})
}

fixtures := FixtureMap{
"users": users,
"tracks": tracks,
"shares": []map[string]any{
{
"share_item_id": 1,
"user_id": 1,
"share_type": "track",
"created_at": time.Now(),
},
{
"share_item_id": 1,
"user_id": 2,
"share_type": "track",
"created_at": time.Now(),
},
{
"share_item_id": 2,
"user_id": 1,
"share_type": "track",
"created_at": time.Now(),
},
{
"share_item_id": 2,
"user_id": 2,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*2) * time.Hour), // 2 weeks ago
},
{
"share_item_id": 2,
"user_id": 3,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*2) * time.Hour), // 2 weeks ago
},
{
"share_item_id": 3,
"user_id": 1,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*5) * time.Hour), // 5 weeks ago
},
{
"share_item_id": 3,
"user_id": 2,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*5) * time.Hour), // 5 weeks ago
},
{
"share_item_id": 3,
"user_id": 3,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*5) * time.Hour), // 5 weeks ago
},
{
"share_item_id": 3,
"user_id": 4,
"share_type": "track",
"created_at": time.Now().Add(-time.Duration(24*7*5) * time.Hour), // 5 weeks ago
},
},
}

createFixtures(app, fixtures)

// Default case (by week), track 1 has most shares, track 3 has none in the past week
{
status, body := testGet(t, app, "/v1/tracks/most-shared")
assert.Equal(t, 200, status)

jsonAssert(t, body, map[string]any{
"data.#": 2,
"data.0.id": trashid.MustEncodeHashID(1),
"data.1.id": trashid.MustEncodeHashID(2),
})
}

// By month, track 2 has most shares
{
status, body := testGet(t, app, "/v1/tracks/most-shared?time_range=month")
assert.Equal(t, 200, status)

jsonAssert(t, body, map[string]any{
"data.#": 2,
"data.0.id": trashid.MustEncodeHashID(2),
"data.1.id": trashid.MustEncodeHashID(1),
})
}

// By all time, track 3 has most shares
{
status, body := testGet(t, app, "/v1/tracks/most-shared?time_range=allTime")
assert.Equal(t, 200, status)

jsonAssert(t, body, map[string]any{
"data.#": 3,
"data.0.id": trashid.MustEncodeHashID(3),
"data.1.id": trashid.MustEncodeHashID(2),
"data.2.id": trashid.MustEncodeHashID(1),
})
}
}
Loading
Loading