--require('idownx')
require('common')
json=require('json')

function issupport(url)
    if url:match("^http://www.tudou.com/") then return true end
    return false   
end
    
function getvid(url)
    local id = ''
    if url:match('v.swf') then
        c=string.match(url,'v/(%d*)/v.swf')
        if(c~=nil)then
            id=c
            print(id)
        else
            d=string.match(url,'v/(.-)/v.swf')  
            if(d~=nil)then
                url='http://www.tudou.com/programs/view/'..d..'/'
                print(url)
                page1 = idown.requesturl(url)
                id = string.match(page1,'iid = (%d*)')
            end    
        end
    else
	page1 = idown.requesturl(url)
	listData = page1:match('itemData%s*=%s*%{(.-)};')	
	id = listData:match('iid%s*:%s*(%d+)')
    end
    return id
end

function analyze(url)
    require("xml")
    print('-----------------------enter analyze-----------------------')
    print('url:'..url)
    --判断url 是否有v.swf
 
    local agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1'
    local id = getvid(url)
    print(id)
    -- 通过id地址拼接成页面,并访问该页面
    page2 = string.format('http://v2.tudou.com/v?noCache=72555&si=sp&ui=0&it=%s&vn=02&st=1%%2C2%%2C3%%2C4%%2C99',id)
    print('page2:'..page2)


    --通过该页面抓取多个原始下载地址 比较size 
    local req = {}
    req.agent = agent
    page3 = idown.requesturl(page2,'',json:encode(req))
    local x = xml.eval(page3)
    print(x:str())

    size = 0
    for i,f in ipairs(x) do
    	print(f:str())
    	print(f.brt, f[1])
	temp = f[1]:match("sz=(%d+)")
    	if tonumber(temp) >= size then
    	size=tonumber(temp)
    	realurl=f[1]
    	end 
    end

    print('---------------------------------------------')
    print(size)
    print(realurl)
    realurl=unescapexml(realurl)
    print(realurl)
    
    realname = unescapexml(string.match(page3,'tt="(.-)"'))
    print(idown.toansi(realname))
    
    --获取文件后缀
    realfilename=realname..'.mp4'

    result = {}
    result['agent'] = agent 
    result['realurl'] = realurl
    result['title'] = realname
    result['realname'] = realfilename
    result['encode'] = 65001
    print('-----------------------leave analyze-----------------------')
    
    --return idown.download(json:encode(result))
    local ret = json:encode(result)
    print(ret)
    return 201,ret
end