require("bit");

function issupport(url)
    if url:find("^http://dl.dbank.com/") then return true end
    if url:find("^http://dl.vmall.com/") then return true end
    return false
end

function xor(data, key)
	ret = ''
	for i=1,#data do
		j = ((i-1)%#key)+1
		ret= ret..string.char(bit.bxor(string.byte(data:sub(i)),string.byte(key:sub(j))))
	end
	print(ret)
	return ret
end

function rc4(g,k)
	local h={};local d=0; local c;local f=""
	for e=0,255 do
		h[e]=e
	end
	for e=0,255 do
		d=(d+h[e]+string.byte(g:sub((e%#g)+1)))%256;
		c=h[e];
		h[e]=h[d];
		h[d]=c
	end
	e=0;d=0;
	for l=0,#key-1 do
		e=(e+1)%256;
		d=(d+h[e])%256;
		c=h[e];h[e]=h[d];h[d]=c;
		j=h[(h[e]+h[d])%256];
		f=f..string.char(bit.bxor(string.byte(k:sub(l+1)),j))
	end
	return f
end

function decode_ed(data,key)
	local b64=idown.crypt.base64decode(data)
	local head=key:sub(1,2)
	if head=='ed' then
		local md5=idown.crypt.md5(key)
		return xor(b64,md5)
	end
	if head=='eb' then
		local k = rc4(key,key)
	  return xor(b64,k)
	end
	return b64
end

function analyze(url)
    local json = require('json')
    print('url:'..url)
    local page = idown.requesturl(url)
    local jsonstring = page:match('globallinkdata = (.-});')
    print(jsonstring)
		
    if not jsonstring then
			local task = {
				encode = 65001,
				files = {}
			}

			i=1
    	for subtitle,realurl in page:gmatch('name="list" title="(.-)" .- downloadUrl="(.-)"') do
				task.files[i] = {
					realurl = realurl,
					realname = subtitle,
				}
				print(task.files[i].realurl)
				if not title then title = subtitle end
    	end
    	
    	task.title = title
    	return 202, json:encode(task)
    end

    local globallinkdata = json:decode(jsonstring)
    print(globallinkdata.data.encryKey)
	
		local task = {
			title = globallinkdata.data.resource.title,
			encode = 65001,
			files = {}
		}
		for i=1,#globallinkdata.data.resource.files do
			local newurl = decode_ed(globallinkdata.data.resource.files[i].downloadurl,globallinkdata.data.encryKey)
			print(tmp)
			task.files[i] = {
				realurl = newurl,
				realname = globallinkdata.data.resource.files[i].name,
			}
			print(task.files[i].realurl)
		end
		
		return 202, json:encode(task)
end