#~DamnVid-module:wattv

class DamnModule_WatTV(DamnVideoModule):
	def __init__(self,uri):
		DamnVideoModule.__init__(self,uri)
		self.name='wattv'
		self.regex={
			'url':re.compile('wat\.tv/video/(.*)$',re.IGNORECASE),
			'title':re.compile('<a[^<>]+class="[^"]*title[^"]*"[^<>]*>\s*([^<>]+)\s*</a>',re.IGNORECASE),
			'ticket':(re.compile('<input[^<>]*id="media"[^<>]*value="([^"]+)"',re.IGNORECASE),re.compile(r'id\s*"?\s*:[^,]+,\s*"?url"?\s*:\s*"(http[^"]+)"',re.IGNORECASE))
		}
		self.valid=self.regex['url'].search(uri)
		self.wattv_requestid=None
		if self.valid:
			self.id='wt:'+self.valid.group(1)
			self.link='http://www.wat.tv/video/'+self.valid.group(1)
	def getTitle(self):
		if self.title is None:
			html=DamnURLOpen(self.link)
			for i in html:
				res1,res2=self.regex['title'].search(i),self.regex['ticket'][0].search(i)
				if res1:
					self.title=DamnHtmlEntities(res1.group(1))
				if res2:
					self.wattv_requestid=DamnHtmlEntities(res2.group(1))
		return DamnVideoModule.getTitle(self)
	def renewTicket(self):
		if self.ticket is not None and self.ticketdate+15>time.time():
			return
		if self.wattv_requestid is None:
			return None
		ticketurl=None
		html=DamnURLOpen('http://www.wat.tv/interface/contentv2/'+self.wattv_requestid)
		for i in html:
			res=self.regex['ticket'][1].search(i)
			if res:
				ticketurl=res.group(1).replace('\\','')
		if ticketurl is None:
			return
		finalhttp=DamnURLOpen(ticketurl+'?getURL=1')
		self.newTicket([finalhttp.read(-1),ticketurl])
		finalhttp.close()
DamnRegisterModule({
	'name':'wattv',
	'title':'wat.tv',
	'type':'video',
	'version':'1.0',
	'author':{
		'name':'Etienne Perot',
		'email':'admin@biringa.com',
		'url':'http://biringa.com/'
	},
	'icon':{
		'small':'wattv.png',
		'large':'wattv-large.png',
	},
	'about':{
		'short':'DamnVid module for wat.tv.',
		'long':"""This is a video plugin for DamnVid that adds wat.tv video downloading capabilities.
Works on "undownloadable" videos as well.""",
		'url':'http://code.google.com/p/damnvid/wiki/Modules'
	},
	'sites':[
		{
			'title':'wat.tv',
			'icon':'wattv.png',
			'url':'http://www.wat.tv/'
		}
	],
	'class':DamnModule_WatTV,
	'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/wat.tv/'
		}
	},
	'register':{
		'listicons':{
			'wattv':'wattv.png'
		}
	}
})
