require('idownx')

--http://www.xiami.com/album/359996
--http://www.xiami.com/u/9903959
local function sup_album(url)
    if url:match("^http://www.xiami.com/album/%d+") then return true end
    if url:match("^http://www.xiami.com/artist/%d+") then return true end
    if url:match("^http://www.xiami.com/u/%d+") then return true end
    if url:match("^http://www.xiami.com/song/showcollect/id/%d+") then return true end
    return false
end

local function ana_album(url)
    local page = idown.requesturl(url)
    --print(page)
    for u in page:gmatch("play%('(%d+)'%)") do
        local newurl = 'http://www.xiami.com/song/'..u
        print(newurl)
        idown.addtask(newurl)
    end
    return 200
end

--http://www.xiami.com/song/play?ids=/song/playlist/id/1769272381%2C1769272382%2C1769272383%2C1769272384%2C1769272385%2C1769272386%2C1769272387%2C1769272388%2C1769272389/object_name/default/object_id/0
local function sup_playlist(url)
    if url:match("^http://www.xiami.com/song/play%?ids=") then return true end
    return false
end

local function ana_playlist(url)
    local idstring = urldecode(url:match('/song/playlist/id/(.-)/object_name/'))
    local ids = split(idstring, ",")
    if #ids == 1 then
        local u = 'http://www.xiami.com/song/'..ids[1]
        local result={Location=u}
        retstr=idown.encode(result)
        return 301,retstr
    else
        for i = 1, #ids do
            local u = 'http://www.xiami.com/song/'..ids[i]
            idown.addtask(u)
        end
        return 200
    end
end

--http://www.xiami.com/radio/play/type/5/oid/63746
local function sup_radio(url)
    if url:match("^http://www.xiami.com/radio/play/") then return true end
    return false
end

local function ana_radio(url)
    local xmlurl = url:gsub('/play/','/xml/')
    xmlurl = xmlurl:gsub('/oid/','/id/')
    
    local xmlpage = idown.requesturl(xmlurl)
    for songid in xmlpage:gmatch('<song_id>(%d+)</song_id>') do
        local u = 'http://www.xiami.com/song/'..songid
        idown.addtask(u)
    end
    return 200
end


local dispatcher = {
    --function issupport, analyze
    {sup_album,     ana_album},
    {sup_playlist,  ana_playlist},
    {sup_radio,     ana_radio},
}

function issupport(url)
    for i =1,#dispatcher do
        if dispatcher[i][1](url) then return true end
    end
    return false
end

function analyze(url)
    for i =1,#dispatcher do
        if dispatcher[i][1](url) then return dispatcher[i][2](url) end
    end
    return 
end