#~DamnVid-module:youku

class DamnModule_Youku(DamnVideoModule):
	def __init__(self,uri):
		DamnVideoModule.__init__(self,uri)
		self.name='youku'
		self.regex={
			'url':re.compile('youku\.com/(?:v_show/id_)?([-+_\w]+)=*\.html',re.IGNORECASE),
			'title':re.compile('</span>\s*(.*?)\s*</h1>',re.IGNORECASE),
			'ticket':(re.compile('addVariable\s*\(\s*[\'"]VideoIDS[\'"]\s*,\s*(\d+)\s*\)',re.IGNORECASE),re.compile('sendVideoLink\s*\(\s*[\'"][^\'"]+[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]',re.IGNORECASE),re.compile('[\'"\s]+?key1[\'"\s]+?:\s*[\'"]([^\'"]+)[\'"]\s*,\s*[\'"\s]+?key2[\'"\s]+?:\s*[\'"]([^\'"]+)[\'"]',re.IGNORECASE))
		}
		self.valid=self.regex['url'].search(uri)
		if self.valid:
			self.id='yk:'+self.valid.group(1)
			self.link='http://v.youku.com/v_show/id_'+self.valid.group(1)
	def renewTicket(self):
		if self.ticket is not None and self.ticketdate+15>time.time():
			return
		shortid=''
		longid=''
		key1=''
		key2=''
		html=DamnURLOpen(self.link)
		for i in html:
			res1,res2=self.regex['ticket'][0].search(i),self.regex['ticket'][1].search(i)
			if res1:
				shortid=res1.group(1)
			if res2:
				longid=res2.group(1)
		if shortid and longid:
			html=DamnURLOpen('http://v.youku.com/player/getPlayList/VideoIDS/'+shortid)
			for i in html:
				res=self.regex['ticket'][2].search(i)
				if res:
					key1=res.group(1)
					key2=res.group(2)
			if key1 and key2:
				self.newTicket('http://f.youku.com/player/getFlvPath/'+longid+'?k='+key2+hex(int(key1,16)^0xA55AA5A5)[2:])
DamnRegisterModule({
	'name':'youku',
	'title':'Youku',
	'type':'video',
	'version':'1.1',
	'author':{
		'name':'Etienne Perot',
		'email':'admin@biringa.com',
		'url':'http://biringa.com/'
	},
	'icon':{
		'small':'youku.png',
		'large':'youku-large.png',
	},
	'about':{
		'short':'DamnVid module for Youku.',
		'long':"""This is a video plugin for DamnVid that adds video downloading capabilities from Youku.""",
		'url':'http://code.google.com/p/damnvid/wiki/Modules'
	},
	'sites':[
		{
			'title':'Youku',
			'icon':'youku.png',
			'url':'http://www.youku.com/v/'
		}
	],
	'class':DamnModule_Youku,
	'preferences':{
		'profile':{
			'name':'Default profile',
			'type':DV.preference_type_profile,
			'kind':'profile',
			'strict':True,
			'default':3
		},
		'outdir':{
			'name':'Output directory',
			'type':DV.preference_type_misc,
			'kind':'dir',
			'strict':True,
			'default':'?DAMNVID_MY_VIDEOS?/DamnVid/Youku/'
		}
	},
	'preferences_order':['profile','outdir'],
	'register':{
		'listicons':{
			'youku':'youku.png'
		}
	}
})
