def get_session(request, data):
    """ Create new session after validating the API_key and token.
    """
    output_format = data.get('format', 'xml')
    try:
        api_key = data['api_key']
        token = Token.load(data['token'], api_key)
    except KeyError:
        raise InvalidAPIUsage(6, output_format=output_format)       # Missing Required Params

    if not token:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(10, output_format=output_format)  # Invalid API_key
        raise InvalidAPIUsage(4, output_format=output_format)       # Invalid token
    if token.has_expired():
        raise InvalidAPIUsage(15, output_format=output_format)      # Token expired
    if not token.user:
        raise InvalidAPIUsage(14, output_format=output_format)      # Unauthorized token

    session = Session.create(token)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('session'):
            with tag('name'):
                text(session.user.name)
            with tag('key'):
                text(session.sid)
            with tag('subscriber'):
                text('0')

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           data.get('format', "xml"))
def user_info(request, data):
    """ Gives information about the user specified in the parameters.
    """
    try:
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        sk = data.get('sk')
        username = data.get('user')
        if not (sk or username):
            raise KeyError

        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API key

        user = User.load_by_sessionkey(sk, api_key)
        if not user:
            raise InvalidAPIUsage(
                CompatError.INVALID_SESSION_KEY,
                output_format=output_format)  # Invalid Session key

        query_user = User.load_by_name(username) if (
            username and username != user.name) else user
        if not query_user:
            raise InvalidAPIUsage(
                CompatError.INVALID_RESOURCE,
                output_format=output_format)  # Invalid resource specified

    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Missing required params

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('user'):
            with tag('name'):
                text(query_user.name)
            with tag('realname'):
                text(query_user.name)
            with tag('url'):
                text('http://listenbrainz.org/user/' + query_user.name)
            with tag('playcount'):
                text(User.get_play_count(query_user.id))
            with tag('registered',
                     unixtime=str(query_user.created.strftime("%s"))):
                text(str(query_user.created))

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), data.get('format', "xml"))
def get_token(request, data):
    """ Issue a token to user after verying his API_KEY
    """
    output_format = data.get('format', 'xml')
    api_key = data.get('api_key')

    if not api_key:
        raise InvalidAPIUsage(6, output_format=output_format)   # Missing required params
    if not Token.is_valid_api_key(api_key):
        raise InvalidAPIUsage(10, output_format=output_format)   # Invalid API_KEY

    token = Token.generate(api_key)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('token'):
            text(token.token)
    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format)
def get_session(request, data):
    """ Create new session after validating the API_key and token.
    """
    output_format = data.get('format', 'xml')
    try:
        api_key = data['api_key']
        token = Token.load(data['token'], api_key)
    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Missing Required Params

    if not token:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API_key
        raise InvalidAPIUsage(CompatError.INVALID_TOKEN,
                              output_format=output_format)  # Invalid token
    if token.has_expired():
        raise InvalidAPIUsage(CompatError.TOKEN_EXPIRED,
                              output_format=output_format)  # Token expired
    if not token.user:
        raise InvalidAPIUsage(
            CompatError.UNAUTHORIZED_TOKEN,
            output_format=output_format)  # Unauthorized token

    session = Session.create(token)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('session'):
            with tag('name'):
                text(session.user.name)
            with tag('key'):
                text(session.sid)
            with tag('subscriber'):
                text('0')

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), data.get('format', "xml"))
def user_info(request, data):
    """ Gives information about the user specified in the parameters.
    """
    try:
        api_key = data['api_key']
        output_format = data.get('format', 'xml')
        sk = data.get('sk')
        username = data.get('user')
        if not (sk or username):
            raise KeyError

        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(10, output_format=output_format)  # Invalid API key

        user = User.load_by_sessionkey(sk, api_key)
        if not user:
            raise InvalidAPIUsage(9, output_format=output_format)  # Invalid Session key

        query_user = User.load_by_name(username) if (username and username != user.name) else user
        if not query_user:
            raise InvalidAPIUsage(7, output_format=output_format)  # Invalid resource specified

    except KeyError:
        raise InvalidAPIUsage(6, output_format=output_format)       # Missing required params

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('user'):
            with tag('name'):
                text(query_user.name)
            with tag('realname'):
                text(query_user.name)
            with tag('url'):
                text('http://listenbrainz.org/user/' + query_user.name)
            with tag('playcount'):
                text(User.get_play_count(query_user.id))
            with tag('registered', unixtime=str(query_user.created.strftime("%s"))):
                text(str(query_user.created))

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           data.get('format', "xml"))
def get_token(request, data):
    """ Issue a token to user after verying his API_KEY
    """
    output_format = data.get('format', 'xml')
    api_key = data.get('api_key')

    if not api_key:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Missing required params
    if not Token.is_valid_api_key(api_key):
        raise InvalidAPIUsage(CompatError.INVALID_API_KEY,
                              output_format=output_format)  # Invalid API_KEY

    token = Token.generate(api_key)

    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('token'):
            text(token.token)
    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), output_format)
 def test_is_valid_api_key(self):
     self.assertTrue(Token.is_valid_api_key(self.user.api_key))
     self.assertTrue(Token.is_valid_api_key(str(uuid.uuid4())))
 def test_is_valid_api_key(self):
     self.assertTrue(Token.is_valid_api_key(self.user.api_key))
     self.assertTrue(Token.is_valid_api_key(str(uuid.uuid4())))
def record_listens(request, data):
    """ Submit the listen in the lastfm format to be inserted in db.
        Accepts listens for both track.updateNowPlaying and track.scrobble methods.
    """
    output_format = data.get('format', 'xml')
    try:
        sk, api_key = data['sk'], data['api_key']
    except KeyError:
        raise InvalidAPIUsage(
            CompatError.INVALID_PARAMETERS,
            output_format=output_format)  # Invalid parameters

    session = Session.load(sk, api_key)
    if not session:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(
                CompatError.INVALID_API_KEY,
                output_format=output_format)  # Invalid API_KEY
        raise InvalidAPIUsage(
            CompatError.INVALID_SESSION_KEY,
            output_format=output_format)  # Invalid Session KEY

    lookup = defaultdict(dict)
    for key, value in data.items():
        if key in ["sk", "token", "api_key", "method", "api_sig"]:
            continue
        matches = re.match('(.*)\[(\d+)\]', key)
        if matches:
            key = matches.group(1)
            number = matches.group(2)
        else:
            number = 0
        lookup[number][key] = value

    if request.form['method'].lower() == 'track.updatenowplaying':
        for i, listen in lookup.iteritems():
            if 'timestamp' not in listen:
                listen['timestamp'] = calendar.timegm(
                    datetime.now().utctimetuple())

    # Convert to native payload then submit 'em after validation.
    listen_type, native_payload = _to_native_api(lookup, data['method'],
                                                 output_format)
    for listen in native_payload:
        validate_listen(listen, listen_type)
    augmented_listens = insert_payload(native_payload,
                                       session.user,
                                       listen_type=listen_type)

    # With corrections than the original submitted listen.
    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('nowplaying' if listen_type ==
                 'playing_now' else 'scrobbles'):

            for origL, augL in zip(lookup.values(), augmented_listens):
                corr = defaultdict(lambda: '0')

                track = augL['track_metadata']['track_name']
                if origL['track'] != augL['track_metadata']['track_name']:
                    corr['track'] = '1'

                artist = augL['track_metadata']['artist_name']
                if origL['artist'] != augL['track_metadata']['artist_name']:
                    corr['artist'] = '1'

                ts = augL['listened_at']

                albumArtist = artist
                if origL.get('albumArtist', origL['artist']) != artist:
                    corr['albumArtist'] = '1'

                album = augL['track_metadata'].get('release_name', '')
                if origL.get('album', '') != album:
                    corr['album'] = '1'

                with tag('scrobble'):
                    with tag('track', corrected=corr['track']):
                        text(track)
                    with tag('artist', corrected=corr['artist']):
                        text(artist)
                    with tag('album', corrected=corr['album']):
                        text(album)
                    with tag('albumArtist', corrected=corr['albumArtist']):
                        text(albumArtist)
                    with tag('timestamp'):
                        text(ts)
                    with tag('ignoredMessage', code="0"):
                        text('')

    return format_response(
        '<?xml version="1.0" encoding="utf-8"?>\n' +
        yattag.indent(doc.getvalue()), output_format)
def record_listens(request, data):
    """ Submit the listen in the lastfm format to be inserted in db.
        Accepts listens for both track.updateNowPlaying and track.scrobble methods.
    """
    output_format = data.get('format', 'xml')
    try:
        sk, api_key = data['sk'], data['api_key']
    except KeyError:
        raise InvalidAPIUsage(6, output_format=output_format)       # Invalid parameters

    session = Session.load(sk, api_key)
    if not session:
        if not Token.is_valid_api_key(api_key):
            raise InvalidAPIUsage(10, output_format=output_format)   # Invalid API_KEY
        raise InvalidAPIUsage(9, output_format=output_format)        # Invalid Session KEY

    lookup = defaultdict(dict)
    for key, value in data.items():
        if key == "sk" or key == "token" or key == "api_key" or key == "method":
            continue
        matches = re.match('(.*)\[(\d+)\]', key)
        if matches:
            key = matches.group(1)
            number = matches.group(2)
        else:
            number = 0
        lookup[number][key] = value

    if request.form['method'].lower() == 'track.updatenowplaying':
        for i, listen in lookup.iteritems():
            if 'timestamp' not in listen:
                listen['timestamp'] = calendar.timegm(datetime.now().utctimetuple())

    # Convert to native payload then submit 'em.
    listen_type, native_payload = _to_native_api(lookup, data['method'], output_format)
    augmented_listens = insert_payload(native_payload, str(session.user.id), listen_type=listen_type)

    # With corrections than the original submitted listen.
    doc, tag, text = Doc().tagtext()
    with tag('lfm', status='ok'):
        with tag('nowplaying' if listen_type == 'playing_now' else 'scrobbles'):

            for origL, augL in zip(lookup.values(), augmented_listens):
                corr = defaultdict(lambda: '0')

                track = augL['track_metadata']['track_name']
                if origL['track'] != augL['track_metadata']['track_name']:
                    corr['track'] = '1'

                artist = augL['track_metadata']['artist_name']
                if origL['artist'] != augL['track_metadata']['artist_name']:
                    corr['artist'] = '1'

                ts = augL['listened_at']

                albumArtist = artist
                if origL.get('albumArtist', origL['artist']) != artist:
                    corr['albumArtist'] = '1'

                # TODO: Add the album part
                album = ""

                with tag('scrobble'):
                    with tag('track', corrected=corr['track']):
                        text(track)
                    with tag('artist', corrected=corr['artist']):
                        text(artist)
                    with tag('album', corrected=corr['album']):
                        text(album)
                    with tag('albumArtist', corrected=corr['albumArtist']):
                        text(albumArtist)
                    with tag('timestamp'):
                        text(ts)
                    with tag('ignoredMessage', code="0"):
                        text('')

    return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
                           output_format)