Source

gSharkDown / lib / lyrdblib.py

Full commit
#!/usr/bin/env python
#-*- encoding: utf-8 -*-

import urllib2
from xml.etree import ElementTree

__doc__ = """Lyrbrary to work with the lyrdb webservices"""
__author__ = "Vladimir Kolev <vladimir.r.kolev@gmail.com>"
__version__ = 1.0
__license__ = "GNU General Public License v.3"

LOOKUP_URL = "http://webservices.lyrdb.com/lookup.php?q=%s&for=%s&agent=gSharkDown"
GETLYR_URL = "http://webservices.lyrdb.com/getlyr.php?q=%s"
CHART_URL = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=%s&song=%s"

def search(artist, track, method="match"):
    first = searchlyr(artist, track, method)
    if "error" in first:
        second = searchchart(artist, track)
        if "error" in second:
            lyrics = "ERROR: Cant't find lyrics for %s - %s" % (artist,
                                                               track)
        else:
            lyrics = second
    else:
        lyrics = getlyrics(first)

    return lyrics


def getlyrics(songid):
    req = urllib2.urlopen(GETLYR_URL % songid)
    lyric = req.read()
    return lyric

def searchlyr(artist, track, method):
    query = artist.replace(" ", "+")
    query += "|"
    query += track.replace(" ", "+")

    if method == "trackname":
        query = track.replace(" ", "+")
    elif method == "artist":
        query = artist.replace(" ", "+")
    elif method == "fullt":
        query = artist.replace(" ", "+")
        query += "+"
        query += track.replace(" ", "+")

    req = urllib2.urlopen(LOOKUP_URL % (query, method))
    result = req.read()
    resp = ""
    if "error" in result:
        resp = "error"
    elif result == "":
        resp = "error"
    else:
        t = result.splitlines()
        resp = t[0].split("\\")[0]
    return resp

def searchchart(artist, track):
    artist = artist.replace(" ", "%20")
    track = track.replace(" ", "%20")

    req = urllib2.urlopen(CHART_URL % (artist, track))
    result = req.read()
    resp = ""
    if "<LyricChecksum>" in result:
        lyric = ElementTree.fromstring(result)
        lyr = lyric.getchildren()[len(lyric.getchildren()) - 1]
        resp = lyr.text
    else:
        resp = "error"
    return resp