Esempio n. 1
0
def get_recent_listens_for_user_list(user_list):
    """
    Fetch the most recent listens for a comma separated list of users. Take care to properly HTTP escape
    user names that contain commas!

    :statuscode 200: Fetched listens successfully.
    :statuscode 400: Your user list was incomplete or otherwise invalid.
    :resheader Content-Type: *application/json*
    """

    limit = _parse_int_arg("limit", 2)
    users = parse_param_list(user_list)
    if not len(users):
        raise APIBadRequest("user_list is empty or invalid.")

    db_conn = webserver.create_timescale(current_app)
    listens = db_conn.fetch_recent_listens_for_users(users, limit=limit)
    listen_data = []
    for listen in listens:
        listen_data.append(listen.to_api())

    return jsonify({
        'payload': {
            'user_list': user_list,
            'count': len(listen_data),
            'listens': listen_data,
        }
    })
Esempio n. 2
0
def follow(user_list):
    """ Allow an LB user to follow the stream of one or more other LB users.
    """

    if user_list:
        default_list = {'name': ''}
        follow_list_members = parse_param_list(user_list)
    else:
        default_list = db_follow_list.get_latest(creator=current_user.id)
        if not default_list:
            default_list = {'name': '', 'members': []}
        follow_list_members = [
            member['musicbrainz_id'] for member in default_list['members']
        ]

    user_data = {
        "id": current_user.id,
        "name": current_user.musicbrainz_id,
        "auth_token": current_user.auth_token,
    }
    spotify_data = spotify.get_user_dict(current_user.id)
    props = {
        "user": user_data,
        "mode": "follow",
        "follow_list": follow_list_members,
        "spotify": spotify_data,
        "web_sockets_server_url": current_app.config["WEBSOCKETS_SERVER_URL"],
        "api_url": current_app.config["API_URL"],
        "save_url": "{}/1/follow/save".format(current_app.config["API_URL"]),
        "follow_list_name": default_list["name"],
        "follow_list_id": default_list["id"] if "id" in default_list else None,
    }

    return render_template(
        "index/follow.html",
        props=ujson.dumps(props),
        mode='follow',
        user=current_user,
        follow_list=follow_list_members,
        active_section='listens',
    )
def get_feedback_for_recordings_for_user(user_name):
    """
    Get feedback given by user ``user_name`` for the list of recordings supplied. The format for the JSON returned
    is defined in our :ref:`feedback-json-doc`.

    If the feedback for given recording MSID doesn't exist then a score 0 is returned for that recording.

    :param recordings: comma separated list of recording_msids for which feedback records are to be fetched.
    :type score: ``str``
    :statuscode 200: Yay, you have data!
    :resheader Content-Type: *application/json*
    """

    recordings = request.args.get('recordings')

    if not recordings:
        log_raise_400("'recordings' has no valid recording MSID.")

    recording_list = parse_param_list(recordings)
    if not len(recording_list):
        raise APIBadRequest("'recordings' has no valid recording MSID.")

    user = db_user.get_by_mb_id(user_name)
    if user is None:
        raise APINotFound("Cannot find user: %s" % user_name)

    try:
        feedback = db_feedback.get_feedback_for_multiple_recordings_for_user(
            user_id=user["id"], recording_list=recording_list)
    except ValidationError as e:
        # Validation errors from the Pydantic model are multi-line. While passing it as a response the new lines
        # are displayed as \n. str.replace() to tidy up the error message so that it becomes a good one line error message.
        log_raise_400(
            "Invalid JSON document submitted: %s" %
            str(e).replace("\n ", ":").replace("\n", " "), request.args)

    feedback = [_feedback_to_api(fb) for fb in feedback]

    return jsonify({
        "feedback": feedback,
    })
def get_feedback_for_recordings_for_user(user_name):
    """
    Get feedback given by user ``user_name`` for the list of recordings supplied. The format for the JSON returned
    is defined in our :ref:`feedback-json-doc`.

    If the feedback for given recording MSID doesn't exist then a score 0 is returned for that recording.

    .. note::

        If you get a 502 error while querying this endpoint, consider reducing the number of total recordings you are
        querying in 1 request. As a rule of thumb, requesting maximum ~75 recordings in 1 request will avert the error.

        The reason this error occurs is because the recording uuids are query params which are part of the request url.
        The length of the url is subject to a general limit imposed at the middleware level so requests with long urls
        never reach the ListenBrainz backend. Due to the same reason, the backend cannot provide a meaningful error.

    :param recordings: comma separated list of recording_msids for which feedback records are to be fetched.
        this param is deprecated and will be removed in the future. use recording_msids instead.
    :type recordings: ``str``
    :param recording_msids: comma separated list of recording_msids for which feedback records are to be fetched.
    :type recording_msids: ``str``
    :param recording_mbids: comma separated list of recording_mbids for which feedback records are to be fetched.
    :type recording_mbids: ``str``
    :statuscode 200: Yay, you have data!
    :resheader Content-Type: *application/json*
    """

    msids_unparsed = request.args.get("recording_msids")
    if msids_unparsed is None:
        msids_unparsed = request.args.get("recordings")
    mbids_unparsed = request.args.get("recording_mbids")

    recording_msids, recording_mbids = [], []
    if msids_unparsed:
        recording_msids = parse_param_list(msids_unparsed)
    if mbids_unparsed:
        recording_mbids = parse_param_list(mbids_unparsed)

    if not recording_msids and not recording_mbids:
        log_raise_400("No valid recording msid or recording mbid found.")

    user = db_user.get_by_mb_id(user_name)
    if user is None:
        raise APINotFound("Cannot find user: %s" % user_name)

    try:
        feedback = db_feedback.get_feedback_for_multiple_recordings_for_user(
            user_id=user["id"],
            user_name=user_name,
            recording_msids=recording_msids,
            recording_mbids=recording_mbids)
    except ValidationError as e:
        # Validation errors from the Pydantic model are multi-line. While passing it as a response the new lines
        # are displayed as \n. str.replace() to tidy up the error message so that it becomes a good one line error message.
        log_raise_400(
            "Invalid JSON document submitted: %s" %
            str(e).replace("\n ", ":").replace("\n", " "), request.args)

    feedback = [fb.to_api() for fb in feedback]

    return jsonify({
        "feedback": feedback,
    })