#~DamnVid-module:metacafe

class DamnModule_Metacafe(DamnVideoModule):
	def __init__(self,uri):
		DamnVideoModule.__init__(self,uri)
		self.name='metacafe'
		self.regex={
			'url':re.compile('metacafe\.com/+(?:watch/)?(\d+)/?',re.IGNORECASE),
			'title':re.compile('<h1[^<>]*>\s*([^<>"]+?)\s*</h1>',re.IGNORECASE),
			'ticket':re.compile('mediaURL=([^&<>]+)(?:&gdaKey=([-_\w]+))?',re.IGNORECASE)
		}
		self.valid=self.regex['url'].search(uri)
		if self.valid:
			self.id='mc:'+self.valid.group(1)
			self.link='http://www.metacafe.com/watch/'+self.valid.group(1)
	def getTitle(self):
		if self.title is not None:
			return self.title
		html=DamnURLOpen(self.link)
		total=''
		for i in html:
			total+=i
		res1,res2=self.regex['title'].search(total),self.regex['ticket'].search(total)
		if res1:
			self.title=DamnHtmlEntities(res1.group(1))
		if res2:
			if res2.group(2) is not None:
				self.newTicket(urllib2.unquote(res2.group(1))+'?__gda__='+res2.group(2))
			else:
				self.newTicket(urllib2.unquote(res2.group(1)))
		return DamnVideoModule.getTitle(self)
	def renewTicket(self):
		if self.ticket is not None and self.ticketdate+15>time.time():
			return
		html=DamnURLOpen(self.link)
		for i in html:
			res=self.regex['ticket'].search(i)
			if res:
				if res.group(2) is not None:
					self.newTicket(urllib2.unquote(res2.group(1))+'?__gda__='+res2.group(2))
				else:
					self.newTicket(urllib2.unquote(res2.group(1)))
DamnRegisterModule({
	'name':'metacafe',
	'title':'Metacafe',
	'type':'video',
	'version':'1.1',
	'author':{
		'name':'Etienne Perot',
		'email':'admin@biringa.com',
		'url':'http://biringa.com/'
	},
	'icon':{
		'small':'metacafe.png',
		'large':'metacafe-large.png',
	},
	'about':{
		'short':'DamnVid module for Metacafe.',
		'long':"""This is a video plugin for DamnVid that adds Metacafe video downloading capabilities.""",
		'url':'http://code.google.com/p/damnvid/wiki/Modules'
	},
	'sites':[
		{
			'title':'Metacafe',
			'icon':'metacafe.png',
			'url':'http://www.metacafe.com/'
		}
	],
	'class':DamnModule_Metacafe,
	'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/Metacafe/'
		}
	},
	'register':{
		'listicons':{
			'metacafe':'metacafe.png'
		}
	}
})
