require('idownx')

function issupport(url)
    if url:find("^http://www.iqiyi.com/") then return true end
    return false
end

function gettimestamp()
		local page = idown.requesturl('http://data.video.qiyi.com/t.hml?tn='..math.random(0,10000))
		local t = idown.decode(page)
    require('BinDecHex')
    local h1 = BinDecHex.Dec2Hex(t.t)
    local h2 = BinDecHex.Dec2Hex("2519219136")
    local x = BinDecHex.BMXOr(h1, h2)
		print(x)
		return BinDecHex.Hex2Dec(x)
end

function getdata(iid)
    print("iid:"..iid)
    url3 ='http://cache.video.qiyi.com/v/'..iid
    page3 =idown.requesturl(url3)
    local y = xml.eval(page3)
    local fileurl =y:find('fileUrl')
    print(fileurl)
    local size = y:find('totalBytes')
    print(size)
		local title = y:find('title')
    print(title)
    title=unescapexml(title[1])
    print(title) 

    return title,tonumber(size[1]),fileurl
end

function getids(iid)
    print("iid:"..iid)
    url3 ='http://cache.video.qiyi.com/v/'..iid
    page3 =idown.requesturl(url3)
    local y = xml.eval(page3)
    local ids =y:find('relative')
    return ids
end

function analyze(url)
    require("xml")
    print('-----------------------enter analyze-----------------------')
    print('url:'..url)
    
    --´ò¿ªÍøÕ¾
    page1 = idown.requesturl(url)
		--print('page1:\n'..page1)
		id =page1:match('"videoId":"(.-)"')
    print('id:'..id)
    
    local title,size,fileurl = getdata(id)
    title = normalize(title)
    ids = getids(id)
    for i=1,#ids do
    	local _,tmpsize,tmpfileurl = getdata(ids[i][1])
    	if tmpsize > size then fileurl = tmpfileurl end
    end
        
    --Full request URI: http://data.video.qiyi.com/t.hml?tn=0.18110732082277536
    realurl=''
    local mergeparam = {}
    mergeparam.files = {}
    for i=1,#fileurl do
        local t = gettimestamp()
        print(t)
        fakeurl = fileurl[i][1]
        local orgurl = fileurl[i][1]
        local newurl = orgurl..'?v='..t
        local page = idown.requesturl(newurl, '', '')
        local p = idown.decode(page)
        print(p.l)
        
        local result = {}
        result['realurl'] = p.l
        result['encode'] = 65001
        if #fileurl > 1 then 
            result['title'] = string.format("[%d/%d]",i,#fileurl)..title
            result['realname'] = title..'.'..i..'.mp4'
        else
            result['title'] = title
            result['realname'] = title..'.mp4'
        end
        local ret = idown.download(idown.encode(result))
        print(ret)
        if ret~=0 then return ret end
        table.insert(mergeparam.files, result)
    end
    if #fileurl > 1 then
	mergeparam.title = title
	mergeparam.realname = title..'.mp4'
	mergeparam.encode = 65001
	idown.merge(idown.encode(mergeparam))
	end
    return 200
end