Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 134
Enable post request track listen query for tag search#138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| import logging # pylint: disable=C0302 | ||
| import json | ||
| import requests | ||
| from sqlalchemy import func, desc | ||
| from urllib.parse import urljoin | ||
| @@ -540,24 +541,23 @@ def get_followee_count_dict(session, user_ids): | ||
| return followee_count_dict | ||
| def get_track_play_counts(track_ids): | ||
| identity_url = shared_config['discprov']['identity_service_url'] | ||
| querystring = {} | ||
| track_listen_counts = {} | ||
| key_str = "id[{}]" | ||
| index = 0 | ||
| # Generate track listen query dict with format id[0]=x, id[1]=y, etc. | ||
| for track_id in track_ids: | ||
| key = key_str.format(index) | ||
| index += 1 | ||
| querystring[key] = str(track_id) | ||
| if not track_ids: | ||
| return track_listen_counts | ||
hareeshnagaraj marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| identity_url = shared_config['discprov']['identity_service_url'] | ||
| # Create and query identity service endpoint | ||
| identity_tracks_endpoint = urljoin(identity_url, 'tracks/listens') | ||
| post_body = {} | ||
| post_body['track_ids'] = track_ids | ||
| try: | ||
| resp = requests.get(identity_tracks_endpoint, params=querystring) | ||
| resp = requests.post(identity_tracks_endpoint, json=post_body) | ||
| except Exception as e: | ||
| logger.error(f'Error retrieving play count - {identity_tracks_endpoint}, {querystring}') | ||
| logger.error( | ||
| f'Error retrieving play count - {identity_tracks_endpoint}, {e}' | ||
| ) | ||
| return track_listen_counts | ||
| json_resp = resp.json() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -15,6 +15,107 @@ let oneWeekInMs = oneDayInMs * 7 | ||
| let oneMonthInMs = oneDayInMs * 30 | ||
| let oneYearInMs = oneMonthInMs * 12 | ||
| const parseTimeframe = (inputTime) => { | ||
| switch (inputTime) { | ||
| case 'day': | ||
| case 'week': | ||
| case 'month': | ||
| case 'year': | ||
| case 'millennium': | ||
| break | ||
| default: | ||
| inputTime = undefined | ||
| } | ||
| // Allow default empty value | ||
| if (inputTime === undefined) { | ||
| inputTime = 'millennium' | ||
| } | ||
| return inputTime | ||
| } | ||
| const getTrackListens = async ( | ||
| idList, | ||
| timeFrame = undefined, | ||
| startTime = undefined, | ||
hareeshnagaraj marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| endTime = undefined, | ||
| limit = undefined, | ||
| offset = undefined) => { | ||
| if (idList !== undefined && !Array.isArray(idList)) { | ||
| return errorResponseBadRequest('Invalid id list provided. Please provide an array of track IDs') | ||
| } | ||
| let boundariesRequested = false | ||
| try { | ||
| if (startTime !== undefined && endTime !== undefined) { | ||
| startTime = Date.parse(startTime) | ||
| endTime = Date.parse(endTime) | ||
| boundariesRequested = true | ||
| } | ||
| } catch (e) { | ||
| logger.error(e) | ||
| } | ||
| // Allow default empty value | ||
| if (timeFrame === undefined) { | ||
| timeFrame = 'millennium' | ||
| } | ||
| let dbQuery = { | ||
| attributes: [ | ||
| [models.Sequelize.col('trackId'), 'trackId'], | ||
| [ | ||
| models.Sequelize.fn('date_trunc', timeFrame, models.Sequelize.col('hour')), | ||
| 'date' | ||
| ], | ||
| [models.Sequelize.fn('sum', models.Sequelize.col('listens')), 'listens'] | ||
| ], | ||
| group: ['trackId', 'date'], | ||
| order: [[models.Sequelize.col('listens'), 'DESC']], | ||
| where: {} | ||
| } | ||
| if (idList && idList.length > 0) { | ||
| dbQuery.where.trackId = { [models.Sequelize.Op.in]: idList } | ||
| } | ||
| if (limit) { | ||
| dbQuery.limit = limit | ||
| } | ||
| if (offset) { | ||
| dbQuery.offset = offset | ||
| } | ||
| if (boundariesRequested) { | ||
| dbQuery.where.hour = { [models.Sequelize.Op.gte]: startTime, [models.Sequelize.Op.lte]: endTime } | ||
| } | ||
| let listenCounts = await models.TrackListenCount.findAll(dbQuery) | ||
| let output = {} | ||
| for (let i = 0; i < listenCounts.length; i++) { | ||
| let currentEntry = listenCounts[i] | ||
| let values = currentEntry.dataValues | ||
| let date = (values['date']).toISOString() | ||
| let listens = parseInt(values.listens) | ||
| currentEntry.dataValues.listens = listens | ||
| let trackId = values.trackId | ||
| if (!output.hasOwnProperty(date)) { | ||
| output[date] = {} | ||
| output[date]['utcMilliseconds'] = values['date'].getTime() | ||
| output[date]['totalListens'] = 0 | ||
| output[date]['trackIds'] = [] | ||
| output[date]['listenCounts'] = [] | ||
| } | ||
| output[date]['totalListens'] += listens | ||
| if (!output[date]['trackIds'].includes(trackId)) { | ||
| output[date]['trackIds'].push(trackId) | ||
| } | ||
| output[date]['listenCounts'].push(currentEntry) | ||
| output[date]['timeFrame'] = timeFrame | ||
| } | ||
| return output | ||
| } | ||
| module.exports = function (app) { | ||
| app.post('/tracks/:id/listen', handleResponse(async (req, res) => { | ||
| const trackId = parseInt(req.params.id) | ||
| @@ -42,110 +143,55 @@ module.exports = function (app) { | ||
| * - <time> - day, week, month, year | ||
| * - returns all track listen info for given time period, sorted by play count | ||
| * | ||
| * query parameters (optional): | ||
| * POST body parameters (optional): | ||
| * limit (int) - limits number of results | ||
| * offset (int) - offset results | ||
| * start (string) - ISO time string, used to define the start time period for query | ||
| * end (string) - ISO time string, used to define the end time period for query | ||
| * start/end are BOTH required if filtering based on time | ||
| * track_ids - filter results for specific track(s) | ||
| * | ||
| * GET query parameters (optional): | ||
| * limit (int) - limits number of results | ||
| * offset (int) - offset results | ||
| * start (string) - ISO time string, used to define the start time period for query | ||
| * end (string) - ISO time string, used to define the end time period for query | ||
| * start/end are BOTH required if filtering based on time | ||
| * id (array of int) - filter results for specific track(s) | ||
| */ | ||
| app.post('/tracks/listens/:timeframe*?', handleResponse(async (req, res, next) => { | ||
| let body = req.body | ||
| let idList = body.track_ids | ||
| let limit = body.limit | ||
| let offset = body.offset | ||
| let startTime = body.startTime | ||
| let endTime = body.endTime | ||
| let time = parseTimeframe(req.params.timeframe) | ||
| let output = await getTrackListens( | ||
| idList, | ||
| time, | ||
| startTime, | ||
| endTime, | ||
| limit, | ||
| offset | ||
| ) | ||
| return successResponse(output) | ||
| })) | ||
| app.get('/tracks/listens/:timeframe*?', handleResponse(async (req, res) => { | ||
| let limit = req.query.limit | ||
| let offset = req.query.offset | ||
| let idList = req.query.id | ||
| let startTime = req.query.start | ||
| let endTime = req.query.end | ||
| let boundariesRequested = false | ||
| if (idList !== undefined && !Array.isArray(idList)) { | ||
| return errorResponseBadRequest('Invalid id list provided. Please provide an array of track IDs') | ||
| } | ||
| try { | ||
| if (startTime !== undefined && endTime !== undefined) { | ||
| startTime = Date.parse(req.query.start) | ||
| endTime = Date.parse(req.query.end) | ||
| boundariesRequested = true | ||
| } | ||
| } catch (e) { | ||
| logger.error(e) | ||
| } | ||
| let time = req.params.timeframe | ||
| switch (time) { | ||
| case 'day': | ||
| case 'week': | ||
| case 'month': | ||
| case 'year': | ||
| case 'millennium': | ||
| break | ||
| default: | ||
| time = undefined | ||
| } | ||
| // Allow default empty value | ||
| if (time === undefined) { | ||
| time = 'millennium' | ||
| } | ||
| let dbQuery = { | ||
| attributes: [ | ||
| [models.Sequelize.col('trackId'), 'trackId'], | ||
| [ | ||
| models.Sequelize.fn('date_trunc', time, models.Sequelize.col('hour')), | ||
| 'date' | ||
| ], | ||
| [models.Sequelize.fn('sum', models.Sequelize.col('listens')), 'listens'] | ||
| ], | ||
| group: ['trackId', 'date'], | ||
| order: [[models.Sequelize.col('listens'), 'DESC']], | ||
| where: {} | ||
| } | ||
| // If id list present, add filter | ||
| if (idList && idList.length > 0) { | ||
| dbQuery.where.trackId = { [models.Sequelize.Op.in]: idList } | ||
| } | ||
| if (limit) { | ||
| dbQuery.limit = limit | ||
| } | ||
| if (offset) { | ||
| dbQuery.offset = offset | ||
| } | ||
| if (boundariesRequested) { | ||
| dbQuery.where.hour = { [models.Sequelize.Op.gte]: startTime, [models.Sequelize.Op.lte]: endTime } | ||
| } | ||
| let listenCounts = await models.TrackListenCount.findAll(dbQuery) | ||
| let output = {} | ||
| for (let i = 0; i < listenCounts.length; i++) { | ||
| let currentEntry = listenCounts[i] | ||
| let values = currentEntry.dataValues | ||
| let date = (values['date']).toISOString() | ||
| let listens = parseInt(values.listens) | ||
| currentEntry.dataValues.listens = listens | ||
| let trackId = values.trackId | ||
| if (!output.hasOwnProperty(date)) { | ||
| output[date] = {} | ||
| output[date]['utcMilliseconds'] = values['date'].getTime() | ||
| output[date]['totalListens'] = 0 | ||
| output[date]['trackIds'] = [] | ||
| output[date]['listenCounts'] = [] | ||
| } | ||
| output[date]['totalListens'] += listens | ||
| if (!output[date]['trackIds'].includes(trackId)) { | ||
| output[date]['trackIds'].push(trackId) | ||
| } | ||
| output[date]['listenCounts'].push(currentEntry) | ||
| output[date]['timeFrame'] = time | ||
| } | ||
| let time = parseTimeframe(req.params.timeframe) | ||
| let output = await getTrackListens( | ||
| idList, | ||
| time, | ||
| startTime, | ||
| endTime, | ||
| limit, | ||
| offset) | ||
| return successResponse(output) | ||
| })) | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.