"""Service handlers.""" from flask import request from marshmallow import ValidationError from owsresponse import response from owsresponse.adaptors.flask import flaskify from participant import config from participant.api import app from participant.constants import error from participant.logic.service import apple_music as apple_music_logic from participant.logic.service import spotify as spotify_logic from participant.schemas.input.participant_artist_dataloader import ParticipantArtistIds from participant.schemas.input.service_participant_search import ( ServiceParticipantSearchSchema, ) from participant.utils.handler import validate_request_data @app.route('/service//search', methods=['GET']) def participant_search(service): """Search participants by name or name substring. Args: service (str): Name of the service for the search. Returns: flask.Response: Matched artists on the specified service. """ if service == config.SPOTIFY_SERVICE: service_handler = spotify_logic.artist_search elif service == config.APPLE_MUSIC_SERVICE: service_handler = apple_music_logic.artist_search else: return flaskify( response.create_error_response( code=error.ERROR_CODE_INVALID_USAGE, message=error.ERROR_MESSAGE_INVALID_USAGE, ) ) params = dict( query=request.args.get('query'), limit=request.args.get('limit', 10), offset=request.args.get('offset', 0), localization=request.args.get('localization') or 'en', ) try: cleaned = ServiceParticipantSearchSchema().load(params) except ValidationError as err: return flaskify( response.create_error_response( code=error.ERROR_CODE_INVALID_USAGE, message=err.messages ) ) result = service_handler(**cleaned) return flaskify(result) @app.route('/service//artist/', methods=['GET']) def participant_artist(service, artist_id): """Search participant by service and ID. Args: service (str): Name of the service for the search. artist_id (str): Artist id. Returns: flask.Response: Matched artist on the specified service. """ if service == config.SPOTIFY_SERVICE: service_handler = spotify_logic.get_artist_by_id elif service == config.APPLE_MUSIC_SERVICE: service_handler = apple_music_logic.get_artist_by_id else: return flaskify( response.create_error_response( code=error.ERROR_CODE_INVALID_USAGE, message=error.ERROR_MESSAGE_INVALID_USAGE, ) ) return flaskify(service_handler(artist_id)) @app.route('/service//artist/dataloader', methods=['POST']) @validate_request_data(schema=ParticipantArtistIds()) def participant_artist_dataloader(service): """Get a list of participants by service and IDs. Args: service (str): Name of the service for the search. Returns: flask.Response: Matched artists on the specified service. """ if service == config.SPOTIFY_SERVICE: service_handler = spotify_logic.get_artists_by_ids else: return flaskify( response.create_error_response( code=error.ERROR_CODE_INVALID_USAGE, message=error.ERROR_MESSAGE_INVALID_USAGE, ) ) return flaskify(service_handler(artist_ids=request.get_json()['ids']))