#~DamnVid-module:megavideo

class DamnModule_Megavideo(DamnVideoModule):
	def __init__(self,uri):
		DamnVideoModule.__init__(self,uri)
		self.name='megavideo'
		self.regex={
			'url':re.compile('megavideo\.com/(?:\?v=)(\w+)',re.IGNORECASE),
			'title':re.compile('\.title\s*=\s*[\'"]([^\s"\']+)[\'"]',re.IGNORECASE),
			'ticket':(re.compile('\.k1\s*=\s*[\'"]?(\w+)[\'"]?',re.IGNORECASE),re.compile('\.k2\s*=\s*[\'"]?(\w+)[\'"]?',re.IGNORECASE),re.compile('\.un\s*=\s*[\'"]?(\w+)[\'"]?',re.IGNORECASE),re.compile('\.s\s*=\s*[\'"]?(\w+)[\'"]?',re.IGNORECASE))
		}
		self.valid=self.regex['url'].search(uri)
		self.megavideo={
			'k1':None,
			'k2':None,
			'un':None,
			's':None
		}
		if self.valid:
			self.id='mv:'+self.valid.group(1)
			self.link='http://megavideo.com/?v='+self.valid.group(1)
	def megavideo_newInfo(self,k1=None,k2=None,un=None,s=None):
		if k1 is not None:
			self.megavideo['k1']=k1
		if k2 is not None:
			self.megavideo['k2']=k2
		if un is not None:
			self.megavideo['un']=un
		if s is not None:
			self.megavideo['s']=s
	def megavideo_allInfo(self):
		return (self.megavideo['k1'] is not None and self.megavideo['k2'] is not None and self.megavideo['un'] is not None and self.megavideo['s'] is not None)
	def megavideo_decrypt(self,un,k1,k2): # This required a nice bit of reverse-engineering, but it works!
		binary=''
		assoc={
			'0':'0000',
			'1':'0001',
			'2':'0010',
			'3':'0011',
			'4':'0100',
			'5':'0101',
			'6':'0110',
			'7':'0111',
			'8':'1000',
			'9':'1001',
			'a':'1010',
			'b':'1011',
			'c':'1100',
			'd':'1101',
			'e':'1110',
			'f':'1111'
		}
		theotherway={
			'0000':'0',
			'0001':'1',
			'0010':'2',
			'0011':'3',
			'0100':'4',
			'0101':'5',
			'0110':'6',
			'0111':'7',
			'1000':'8',
			'1001':'9',
			'1010':'a',
			'1011':'b',
			'1100':'c',
			'1101':'d',
			'1110':'e',
			'1111':'f'
		}
		for i in un:
			if assoc.has_key(i):
				binary+=assoc[i]
		ar2=[]
		for i in range(384):
			k1=(k1*11+77213)%81371
			k2=(k2*17+92717)%192811
			ar2.append((k1+k2)%128)
		for i in range(256,-1,-1):
			mi=min((ar2[i],i%128))
			ma=max((ar2[i],i%128))
			if mi!=ma:
				binary=binary[0:mi]+binary[ma]+binary[mi+1:ma]+binary[mi]+binary[ma+1:]
		for i in range(128):
			if binary[i]=='0':
				tmp=ar2[i+256]%2
			else:
				tmp=not bool(ar2[i+256]%2)
			binary=binary[0:i]+str(int(tmp))+binary[i+1:]
		result=''
		for i in range(0,len(binary),4):
			if theotherway.has_key(binary[i:i+4]):
				result+=theotherway[binary[i:i+4]]
		return result
	def getTitle(self):
		if self.title is not None:
			return self.title
		html=DamnURLOpen(self.link)
		for i in html:
			res1,res2,res3,res4,res5=self.regex['title'].search(i),self.regex['ticket'][0].search(i),self.regex['ticket'][1].search(i),self.regex['ticket'][2].search(i),self.regex['ticket'][3].search(i)
			if res1:
				self.title=DamnHtmlEntities(urllib2.unquote(res1.group(1).replace('+',' '))).title()
			if res2:
				self.megavideo_newInfo(k1=int(res2.group(1)))
			if res3:
				self.megavideo_newInfo(k2=int(res3.group(1)))
			if res4:
				self.megavideo_newInfo(un=res4.group(1))
			if res5:
				self.megavideo_newInfo(s=res5.group(1))
		return DamnVideoModule.getTitle(self)
	def renewTicket(self):
		if self.ticket is not None:
			return
		if not self.megavideo_allInfo():
			self.title=None
			self.getTitle() # Pass over the thing again?
		self.newTicket('http://www'+str(self.megavideo['s'])+'.megavideo.com/files/'+self.megavideo_decrypt(self.megavideo['un'],self.megavideo['k1'],self.megavideo['k2'])+'/')
DamnRegisterModule({
	'name':'megavideo',
	'title':'Megavideo',
	'type':'video',
	'version':'1.0',
	'author':{
		'name':'Etienne Perot',
		'email':'admin@biringa.com',
		'url':'http://biringa.com/'
	},
	'icon':{
		'small':'megavideo.png',
		'large':'megavideo-large.png',
	},
	'about':{
		'short':'DamnVid module for Megavideo.',
		'long':"""This is a video plugin for DamnVid that adds Megavideo video downloading capabilities.""",
		'url':'http://code.google.com/p/damnvid/wiki/Modules'
	},
	'sites':[
		{
			'title':'Megavideo',
			'icon':'megavideo.png',
			'url':'http://megavideo.com/?c=videos'
		}
	],
	'class':DamnModule_Megavideo,
	'preferences':{
		'profile':{
			'name':'Default profile',
			'type':DV.preference_type_profile,
			'kind':'profile',
			'strict':True,
			'default':-1
		},
		'outdir':{
			'name':'Output directory',
			'type':DV.preference_type_misc,
			'kind':'dir',
			'strict':True,
			'default':'?DAMNVID_MY_VIDEOS?/DamnVid/Megavideo/'
		}
	},
	'register':{
		'listicons':{
			'megavideo':'megavideo.png'
		}
	}
})
